Imagine printing a multiplication table. You could write twelve print() lines, or you could use a loop and write one.
The for loop
for repeats once for each item. range(1, 6) gives the numbers 1, 2, 3, 4, 5 (it stops before the second number).
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
A multiplication table:
for i in range(1, 6):
print(f"7 x {i} = {7 * i}")
Output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
You can loop over text and lists too:
for letter in "Nepal":
print(letter)
Output:
N
e
p
a
l
Adding things up
total = 0
for n in range(1, 11):
total = total + n
print(total)
Output:
55
The while loop
while keeps repeating as long as a condition stays true. Be careful: something inside the loop must eventually make the condition false, or it will run forever.
count = 3
while count > 0:
print(count)
count = count - 1
print("Go!")
Output:
3
2
1
Go!
break and continue
breakleaves the loop immediately.continueskips the rest of this round and starts the next.
for n in range(1, 10):
if n % 2 == 0:
continue # skip even numbers
if n > 7:
break # stop completely
print(n)
Output:
1
3
5
7
Try it yourself
- Print the even numbers from 2 to 20.
- Add up all the numbers from 1 to 100.
- Print a countdown from 10 to 1 using a
whileloop.
Next lesson: storing many values in lists and dictionaries.

Comments
Loading comments…