Lesson 1
for loops and range()
Repeat code a set number of times.
Repeat with for
for i in range(3): runs the indented lines under it 3 times.
Like if, the line ends with a colon and the lines inside are indented.
for i in range(3):
print("Hip hip hooray!")
Counting with range()
Each time round the loop, the variable (here n) holds the next number from the range:
range(5)gives 0, 1, 2, 3, 4: five numbers, starting at 0
range(1, 6)gives 1, 2, 3, 4, 5: it stops before the second number
range(0, 10, 2)counts in steps of 2: 0, 2, 4, 6, 8
for n in range(1, 6):
print(n)
Lesson 2
while loops
Keep going while something is true, and stop with break.
Repeat while it’s true
while condition: checks the condition, runs the lines inside if it’s true, and then checks again, over and over.
Something inside has to change, so the condition becomes false one day. If not, the loop goes on forever. (Here, the game stops it after a few seconds.)
count = 3
while count > 0:
print(count)
count -= 1
print("Lift off!")
break and continue
breakleaves the loop straight away
continueskips the rest of this round and starts the next one
while True: with a break inside is a common way to write “keep going until…”.
n = 0
while True:
n += 1
if n == 3:
continue
if n > 5:
break
print(n)
Lesson 3
Adding things up
Running totals, counting, and looping over the letters in a word.
A running total
To add up numbers in a loop, make a variable before the loop that starts at 0. Inside the loop, add each number to it.
This is one of the most useful patterns in programming.
total = 0
for n in range(1, 5):
total += n
print(total)
Looping over text
for letter in word: goes through a string one letter at a time.
Add an if inside to count only some of them.
word = "banana"
count = 0
for letter in word:
if letter == "a":
count += 1
print(f"{word}: {count}")
Recap
What Level 3 covers, in a few lines.
for i in range(5):runs the indented lines 5 times, withigoing 0, 1, 2, 3, 4.range(start, stop)counts fromstartup to, but not including,stop. A third number is the step:range(0, 10, 2).while condition:repeats as long as the condition is true. Something inside has to change, or it never stops.breakleaves a loop straight away;continueskips to the next round.- To add things up, start a total at 0 before the loop and add to it inside.
for letter in word:goes through text one letter at a time.
Now try it in Python School
Write real Python and run it right there, with a check after every step and a test at the end of each level. Free.