MyMisPal
← Python lessons
Lesson 6 of 13

Loops: for and while

PYTHON
for i in range(1, 6):
    print("Order", i)

range(1, 6) gives 1 to 5 (the end is excluded). range(5) goes 0 to 4, and range(0, 10, 2) steps by 2.

PYTHON
total = 0
for n in range(1, 101):
    total += n
print(total)

while repeats as long as a condition is true. Example: how many years until money doubles at 10% a year?

PYTHON
balance = 1000
years = 0
while balance < 2000:
    balance = balance * 1.1
    years += 1
print(years, round(balance, 2))

break exits the loop and continue skips to the next round.

PYTHON
for n in range(1, 50):
    if n % 7 == 0:
        print("First multiple of 7:", n)
        break
Watch outIf you forget to change the variable inside while, the loop never ends. The editor here stops the program after a few seconds, and there's a Stop button too.

Exercises

Exercise 1

Print the 7 times table from 1 to 10 in the form: 7 x 1 = 7.

Exercise 2

Read a number n and print the sum of the even numbers from 1 to n.

Spotted a mistake on this page, or have an idea to improve the site?