Loops — for & while
Repeat actions with for loops, while loops, and range().
OK here's my frustration. Yesterday I wrote a function that grades one student. But I have 200 students in my spreadsheet. Am I seriously supposed to call get_grade() two hundred times by hand? That's worse than Excel.
Not even close. That's what loops are for. A for loop runs a block of code once for every item in a sequence. You write the logic once, and Python repeats it as many times as you need:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}!")
Output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
Python grabs the first item from names, assigns it to name, runs the indented body, then moves to the next item and repeats. When the list is exhausted, the loop ends. Three students, three greetings, one line of logic.
Wait, so that names thing in square brackets — that's a list? Like a column in my spreadsheet?
Exactly. A Python list is an ordered collection of items. Square brackets, comma-separated. You can put anything in there — strings, numbers, even a mix. But the power is that for lets you process every item without knowing in advance how many there are.
What if you don't have a list, though? What if you just need to repeat something a fixed number of times? That's where range() comes in:
for i in range(5):
print(i)
# 0, 1, 2, 3, 4
Hold on — range(5) gives me 0 through 4? Why not 1 through 5? That makes no sense.
I know it feels weird coming from spreadsheets where Row 1 is the first row. But in programming, counting from zero is the convention. range(5) means "give me 5 numbers, starting from 0." You'll get used to it faster than you think.
You can also customize the start and step:
for i in range(2, 10, 3):
print(i)
# 2, 5, 8
That reads: start at 2, go up to (but not including) 10, step by 3.
OK, for loops go through a list or a range. But what about situations where you don't know when to stop? Like, keep asking for a password until they get it right?
That's a while loop. It keeps running as long as a condition is True:
count = 0
while count < 3:
print(f"Count is {count}")
count = count + 1
Output:
Count is 0
Count is 1
Count is 2
The loop checks count < 3 before every pass. Once count hits 3, the condition becomes False and the loop stops. Be careful — if you forget count = count + 1, the condition stays True forever and you get an infinite loop. Your program just runs until you force-quit it.
Rule of thumb: for when you know what you're looping over. while when you're waiting for a condition to change.
Got it. But back to my original question — I have 200 student scores and I need to add them up. Can a loop do that?
That's one of the most fundamental patterns in programming — the accumulator:
def total(numbers):
result = 0
for n in numbers:
result = result + n
return result
print(total([10, 20, 30])) # 60
You start with result = 0, then add each number to it as you loop through. When the loop finishes, result holds the sum. This pattern — start with an empty thing, build it up one step at a time — works for counting, averaging, building strings, filtering items, anything.
So for goes through items, while waits for a condition, and the accumulator lets me build up a total as I go. This is like the SUMIF in my spreadsheets but way more flexible.
Exactly — and unlike SUMIF, you're not limited to one operation. You can sum, count, filter, transform, all in the same loop. Let's practice the accumulator now.
Practice your skills
Sign up to write and run code in this lesson.
Loops — for & while
Repeat actions with for loops, while loops, and range().
OK here's my frustration. Yesterday I wrote a function that grades one student. But I have 200 students in my spreadsheet. Am I seriously supposed to call get_grade() two hundred times by hand? That's worse than Excel.
Not even close. That's what loops are for. A for loop runs a block of code once for every item in a sequence. You write the logic once, and Python repeats it as many times as you need:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(f"Hello, {name}!")
Output:
Hello, Alice!
Hello, Bob!
Hello, Charlie!
Python grabs the first item from names, assigns it to name, runs the indented body, then moves to the next item and repeats. When the list is exhausted, the loop ends. Three students, three greetings, one line of logic.
Wait, so that names thing in square brackets — that's a list? Like a column in my spreadsheet?
Exactly. A Python list is an ordered collection of items. Square brackets, comma-separated. You can put anything in there — strings, numbers, even a mix. But the power is that for lets you process every item without knowing in advance how many there are.
What if you don't have a list, though? What if you just need to repeat something a fixed number of times? That's where range() comes in:
for i in range(5):
print(i)
# 0, 1, 2, 3, 4
Hold on — range(5) gives me 0 through 4? Why not 1 through 5? That makes no sense.
I know it feels weird coming from spreadsheets where Row 1 is the first row. But in programming, counting from zero is the convention. range(5) means "give me 5 numbers, starting from 0." You'll get used to it faster than you think.
You can also customize the start and step:
for i in range(2, 10, 3):
print(i)
# 2, 5, 8
That reads: start at 2, go up to (but not including) 10, step by 3.
OK, for loops go through a list or a range. But what about situations where you don't know when to stop? Like, keep asking for a password until they get it right?
That's a while loop. It keeps running as long as a condition is True:
count = 0
while count < 3:
print(f"Count is {count}")
count = count + 1
Output:
Count is 0
Count is 1
Count is 2
The loop checks count < 3 before every pass. Once count hits 3, the condition becomes False and the loop stops. Be careful — if you forget count = count + 1, the condition stays True forever and you get an infinite loop. Your program just runs until you force-quit it.
Rule of thumb: for when you know what you're looping over. while when you're waiting for a condition to change.
Got it. But back to my original question — I have 200 student scores and I need to add them up. Can a loop do that?
That's one of the most fundamental patterns in programming — the accumulator:
def total(numbers):
result = 0
for n in numbers:
result = result + n
return result
print(total([10, 20, 30])) # 60
You start with result = 0, then add each number to it as you loop through. When the loop finishes, result holds the sum. This pattern — start with an empty thing, build it up one step at a time — works for counting, averaging, building strings, filtering items, anything.
So for goes through items, while waits for a condition, and the accumulator lets me build up a total as I go. This is like the SUMIF in my spreadsheets but way more flexible.
Exactly — and unlike SUMIF, you're not limited to one operation. You can sum, count, filter, transform, all in the same loop. Let's practice the accumulator now.
Practice your skills
Sign up to write and run code in this lesson.