Python for AIPython for AI
Python Basics

Loops

Repeat code multiple times

Sometimes you need your computer to do the same thing many, many times. That's where loops come in!

What are loops?

Loops are super handy when you want to repeat a block of code multiple times. Instead of writing the same lines over and over, you can tell Python to loop through them.

Imagine printing a message ten times. Without a loop, you'd write ten print statements. With a loop, it's just a few lines of code.

For loops

for loops are great when you know how many times you want to repeat something, or when you want to go through each item in a collection.

Start
items left?
→
Take item
next value
→
Run body
indented code
→
Repeat
loop back
→
Done
no items left
A for loop walks through each item, runs the body, then moves on.

Repeat a specific number of times

The range() function is your friend here. It gives you a sequence of numbers. You can loop through these numbers.

python
for i in range(5):
    print("Hello!")

This code will print "Hello!" exactly five times. The variable i will take values 0, 1, 2, 3, and 4.

Count from different starting points

You can tell range() where to start and stop. The first number is included, but the last one is not.

python
for count in range(1, 4):
    print(f"Countdown: {count}")

This prints "Countdown: 1", "Countdown: 2", then "Countdown: 3".

Loop through text

You can also loop through each character in a string. Python treats a string as a sequence of characters.

python
word = "Python"
for char in word:
    print(char)

This will print each letter of "Python" on a new line.

Loop through a list (preview)

While we haven't covered lists yet, they're another common thing to loop through. You'll often use for loops to process every item in a list.

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I love {fruit}s!")

While loops

while loops keep going as long as a certain condition is true. They're useful when you don't know exactly how many times you need to repeat something.

python
count = 0
while count < 3:
    print("Counting...")
    count = count + 1 # Don't forget to change the condition!

This loop will print "Counting..." three times, then stop because count becomes 3, making the count < 3 condition false.

Common mistakes

  • Forgetting the colon (:) at the end of the for or while line.
  • Incorrect indentation. Python uses spaces to know what code belongs inside the loop.
  • Forgetting to update the condition in a while loop, which can lead to an infinite loop (it never stops!). Press Ctrl+C to stop a runaway script.

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
What values does `range(1, 4)` produce?
Fill in the blanks
Not started
Complete the loop so it sums numbers 1 through 5.
1total = 0
2
3 total += i
4print(total)
Code challenge
Not started
Print the numbers 1 through 10, each on its own line.