Loops
Repeat code without writing it twice.
for loops
Repeat a set number of times
Use a for loop with range() when you know the count up front.
Repeat something 3 times
Use range() even when you do not need the number.
for i in range(3):
print("Go Tigers!")Go Tigers! Go Tigers! Go Tigers!
range(stop)
Starts at 0 and stops just before the number.
for i in range(4):
print(i)0 1 2 3
range(start, stop)
Starts where you say, still stops just before the second number.
for i in range(2, 5):
print(i)2 3 4
range(start, stop, step)
The third number is how much to count by.
for i in range(34, 41, 2):
print(i)34 36 38 40
Counting down
A negative step counts backwards.
for i in range(41, 34, -2):
print(i)41 39 37 35
Go through a list
Loop over every item
No range() and no index numbers needed.
names = ["Steve", "Becca", "Alex"]
for name in names:
print(name)Steve Becca Alex
Loop with an index
Use range() when you need the position of each item, or only some of the items. When you want every item, for name in names is simpler.
Only the first few
range(2) gives the indexes 0 and 1.
menu = ["Burger", "Fries", "Ribs", "Salad"]
for i in range(2):
print(menu[i])Burger Fries
Every item, with its index
range(len(menu)) works however long the list gets.
menu = ["Burger", "Fries", "Ribs", "Salad"]
for i in range(len(menu)):
print(f"{i}: {menu[i]}")0: Burger 1: Fries 2: Ribs 3: Salad
The last two
-2 is second to last. The loop stops just before 0, after -1.
menu = ["Burger", "Fries", "Ribs", "Salad"]
for i in range(-2, 0):
print(menu[i])Ribs Salad
Every other item
Count by 2, starting at index 0.
menu = ["Burger", "Fries", "Ribs", "Salad"]
for i in range(0, len(menu), 2):
print(menu[i])Burger Ribs
Number the items
enumerate() gives you the index and the item together, so you do not need menu[i].
Index and item
The first name gets the index, the second gets the item.
menu = ["Burger", "Fries", "Ribs"]
for i, item in enumerate(menu):
print(f"{i} {item}")0 Burger 1 Fries 2 Ribs
A numbered list
Indexes start at 0, so add 1 for a list people read.
menu = ["Burger", "Fries", "Ribs"]
for i, item in enumerate(menu):
print(f"{i + 1}. {item}")1. Burger 2. Fries 3. Ribs
Two lists side by side
zip() pairs up two lists: first with first, second with second. Lists that go together like this are called parallel lists.
Go through two lists at once
One name for each list, in the same order as inside zip().
menu = ["Burger", "Fries", "Ribs"]
costs = [1.59, 2.79, 8.99]
for item, cost in zip(menu, costs):
print(f"{item} ${cost}")Burger $1.59 Fries $2.79 Ribs $8.99
Line up the prices
:<10 gives every item the same width, so the prices line up.
menu = ["Burger", "Fries", "Ribs"]
costs = [1.59, 2.79, 8.99]
for item, cost in zip(menu, costs):
print(f"{item:<10}${cost}")Burger $1.59 Fries $2.79 Ribs $8.99
Number them too
Hand what zip() makes to enumerate(). Each pair goes in parentheses.
menu = ["Burger", "Fries", "Ribs"]
costs = [1.59, 2.79, 8.99]
pairs = zip(menu, costs)
for i, (item, cost) in enumerate(pairs):
print(f"{i + 1}. {item:<10}${cost}")1. Burger $1.59 2. Fries $2.79 3. Ribs $8.99
while loops
Repeat until something changes
Use a while loop when you do not know how many times it will take.
The same count as a for loop
This does what for i in range(1, 5) does. A while loop needs the start, the condition, and the change written out.
i = 1
while i < 5:
print(i)
i = i + 11 2 3 4
Count down with while
Something inside has to change, or the loop never ends.
count = 3
while count > 0:
print(count)
count = count - 1
print("Liftoff!")3 2 1 Liftoff!
Keep asking until it is right
Notice the question is written twice, once before and once inside.
guess = int(input("Guess: "))
while guess != 7:
guess = int(input("Guess: "))
print("You got it!")Guess: 5 Guess: 3 Guess: 7 You got it!
Tell them, then ask again
Inside the loop, say it was wrong first, then ask again. The line after the loop only runs once they get it.
guess = int(input("Guess: "))
while guess != 7:
print("Wrong. Try again.")
guess = int(input("Guess: "))
print("You won!")Guess: 5 Wrong. Try again. Guess: 7 You won!
Repeat until you say stop
while True: repeats forever, so your job is deciding when to get out. break leaves the loop.
while True with break
Only writes the question once. break jumps out of the loop.
while True:
guess = int(input("Guess: "))
if guess == 7:
break
print("You got it!")Guess: 5 Guess: 3 Guess: 7 You got it!
while True with a message each time
Print the winning message before break. The else handles every wrong guess.
while True:
guess = int(input("Guess: "))
if guess == 7:
print("You won!")
break
else:
print("Wrong. Try again.")Guess: 5 Wrong. Try again. Guess: 7 You won!
Counting with while True
Stop with > instead of ==. Counting by 2 goes 0, 2, 4, 6 and is never 5, so if i == 5 would never stop the loop.
i = 0
while True:
print(i)
i = i + 2
if i > 5:
break0 2 4
Code under break never runs
break leaves the loop right away, so the print under it is skipped every time.
while True:
guess = int(input("Guess: "))
if guess == 7:
break
print("You won!")Guess: 7