Part 4: Loops — Automating Repetition and Making Simple Games (with Help from AI)

Loops let your code do more with less — running the same block of code multiple times until a condition is met. In this part, we’ll explore:

  • for loops and range()
  • while loops and loop control
  • A mini number guessing game
  • How to use AI tools to generate custom loop challenges

🔁 Why Use Loops?

Loops are useful when you want to:

  • Repeat an action multiple times
  • Iterate through a list of items
  • Keep asking for user input until a correct response is given

🔂 for Loops with range()

Use a for loop when you know how many times to repeat something.

for i in range(5):
print("Looping:", i)

This prints:

Looping: 0
Looping: 1
Looping: 2
Looping: 3
Looping: 4

Note: range(5) starts at 0 and ends at 4 (not 5!).


🔄 while Loops

Use while loops when you want to repeat something until a condition is false.

count = 0

while count < 3:
print("Counting:", count)
count += 1

Be careful! while loops can go forever if the condition never becomes false.


⏹ Loop Control: break and continue

  • break: exit the loop early
  • continue: skip the current iteration and continue
for i in range(5):
if i == 3:
break
print(i)
for i in range(5):
if i == 2:
continue
print(i)

🎮 Mini Project: Number Guessing Game

Let’s make a simple game!

import random

secret = random.randint(1, 10)
guess = None

while guess != secret:
guess = int(input("Guess a number between 1 and 10: "))

if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print("You got it!")

🧠 AI Tip: Use ChatGPT to Create Loop Challenges

Ask:

“Give me 5 Python loop challenges for beginners.”

ChatGPT can generate tasks like:

  • Print the first 10 squares
  • Loop through a string and count vowels
  • Make a simple password checker

Want to level up? Ask:

“Can you turn that number guessing game into a two-player version?”


📚 Reinforcement Resources


🎯 Practice Challenge

Create a loop that:

  • Asks the user for a number between 1–10
  • Keeps asking until the correct number is guessed
  • Counts how many tries it took

Bonus: Ask ChatGPT to help you make the game “smarter” by giving hints.


🏁 Coming Up in Part 5…

Next up, we’ll cover lists, tuples, and dictionaries — three core Python data structures. You’ll learn how to store and manipulate collections of data, and use AI to simulate real-world data sets.

Hint: We’ll build a simple contact book using a dictionary!

Share the Post:

Related Posts

Join the Codexa Crew – It’s free!

Stay Updated with the Latest in Tech & Automation

Be the first to know when new content drops on Green Codexa!