Loops
Repeat code without writing it twice.
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!")Output
Go Tigers! Go Tigers! Go Tigers!
range(stop)
Starts at 0 and stops just before the number.
for i in range(4):
print(i)Output
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)Output
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)Output
34 36 38 40
Counting down
A negative step counts backwards.
for i in range(41, 34, -2):
print(i)Output
41 39 37 35
Repeat until something changes
Use a while loop when you do not know how many times it will take.
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!")Output
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!")Sample run
Guess: 5 Guess: 3 Guess: 7 You got it!
while True with break
Use this oneOnly writes the question once. break jumps out of the loop.
while True:
guess = int(input("Guess: "))
if guess == 7:
break
print("You got it!")Sample run
Guess: 5 Guess: 3 Guess: 7 You got it!
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)Output
Steve Becca Alex