Core by Critic
ChaptersStreak: 0 days

Ultimate Core Python · Chapter 14

for Loops and range

This lesson goes with Episode 14 of the Ultimate Core Python course on the Core by Critic channel on YouTube.

0 of 0 done

14.1 The for statement

Print each letter of a word on its own line. With while, you need an index, a condition and an update:

word = "cat"
i = 0
while i < len(word):
    print(word[i])
    i += 1

Output

c
a
t

Five lines, three of them bookkeeping, and three places to make a mistake. Here is the same job with for:

word = "cat"
for letter in word:
    print(letter)

Output

c
a
t

No index. No condition. No update. Nothing to forget.

The parts of a for

   keyword  loop variable  keyword  the sequence  colon
      │          │            │          │          │
     for      letter          in        word        :
         print(letter)       ◄── the block, run once per item

Read it as: "for each letter in word, do this."

Here is exactly what Python does:

  1. It takes the first item of the sequence and assigns it to the loop variable.
  2. It runs the block.
  3. It takes the next item, assigns it to the loop variable, and runs the block again.
  4. When there are no items left, the loop ends, and the program continues after it.
Pass letter Prints
1 "c" c
2 "a" a
3 "t" t
— nothing left the loop ends

The loop variable (letter here) is an ordinary variable. You choose its name, and Python assigns it a new value at the start of every pass. You do not create it beforehand and you do not update it yourself.

A for loop over an empty sequence simply does nothing: the block runs zero times.

for letter in "":
    print("This never appears")
print("Done")

Output

Done

What can go after in?

Anything Python can step through one item at a time. Such a thing is called an iterable. So far you know two kinds: strings, and the lists that split() gives you (Chapter 9):

for word in "the quick brown fox".split():
    print(word, len(word))

Output

the 3
quick 5
brown 5
fox 3

In the coming chapters nearly every collection you meet (lists, tuples, dictionaries, sets, files) will be iterable, and this same loop will work on all of them → Chapter 25. A plain number is not iterable, because it has no items:

for i in 5:
    print(i)

Output

Traceback (most recent call last):
  File "count.py", line 1, in <module>
    for i in 5:
             ^
TypeError: 'int' object is not iterable

To loop five times, you need something that produces five numbers. That is what range is for.

Quick check

What does this print? for ch in "hi!": with the block print(ch * 2, end=" ")

Show the answer

Answer: hh ii !! on one line. Each character in turn is repeated twice.

Practice 14.1

Predict the output

What does it print?

for ch in "sun":
    print(ch + ch)

Multiple choice

What happens when this program runs?

for i in 3:
    print(i)
Choose one answer

Put the lines in order

Put the lines in order. The program prints each letter of the word in capitals, one per line, and prints Done at the very end.

The program in the right order prints:

Target

K
I
T
E
Done
  1. word = "kite"
  2. print("Done")
  3. for letter in word:
  4. print(letter.upper())

14.2 range(): numbers on demand

range(n) produces the whole numbers from 0 up to, but not including, n:

for i in range(5):
    print(i, end=" ")
print()

Output

0 1 2 3 4

Five numbers, starting at zero, and 5 itself is not one of them. This is the standard way to say "do this five times":

for i in range(3):
    print("Hello!")

Output

Hello!
Hello!
Hello!

If the block does not use the number at all, Python programmers often name the variable _, a single underscore, as a signal to the reader: "I need a variable here, but I do not care about its value."

To look at the numbers a range holds, hand it to list(), which collects them into a list → Chapter 25:

print(list(range(5)))
print(list(range(1)))
print(list(range(0)))

Output

[0, 1, 2, 3, 4]
[0]
[]

Start and stop

With two arguments, range(start, stop) begins at start:

print(list(range(1, 6)))
print(list(range(5, 10)))
print(list(range(-2, 3)))

Output

[1, 2, 3, 4, 5]
[5, 6, 7, 8, 9]
[-2, -1, 0, 1, 2]

stop is still left out. To count from 1 to 5, you write range(1, 6).

Start, stop and step

A third argument is the step, the distance between one number and the next:

print(list(range(0, 10, 2)))
print(list(range(1, 10, 3)))
print(list(range(10, 0, -1)))
print(list(range(10, 0, -3)))

Output

[0, 2, 4, 6, 8]
[1, 4, 7]
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
[10, 7, 4, 1]

A negative step counts down. For that, start must be the larger number, and stop is again left out: range(10, 0, -1) ends at 1.

The three forms

Call Produces Example Numbers
range(stop) from 0, up by 1 range(4) 0, 1, 2, 3
range(start, stop) from start, up by 1 range(2, 6) 2, 3, 4, 5
range(start, stop, step) from start, in jumps of step range(2, 12, 4) 2, 6, 10

This should look familiar. It is exactly the slice notation from Chapter 8, s[start:stop:step], with commas where the colons were, and with the same rule that stop is not included.

Why is stop left out?

For the same reasons as in slicing:

  • range(n) produces exactly n numbers.
  • range(len(word)) produces exactly the valid indexes of word: 0 to len(word) - 1.
  • range(0, 5) followed by range(5, 10) covers 0 to 9 with no gap and no overlap.

Ranges that are empty

If the numbers cannot get from start to stop in the direction of the step, the range is simply empty. No error:

print(list(range(5, 2)))
print(list(range(2, 5, -1)))
print(list(range(3, 3)))

Output

[]
[]
[]

An empty range means the loop runs zero times. The first line is a classic mistake: to count down from 5, you must give a negative step. range(5, 2) does not guess.

What range refuses

The arguments must be whole numbers, and the step cannot be zero:

for x in range(0, 1, 0.1):
    print(x)

Output

Traceback (most recent call last):
  File "steps.py", line 1, in <module>
    for x in range(0, 1, 0.1):
             ~~~~~^^^^^^^^^^^
TypeError: 'float' object cannot be interpreted as an integer

To step through decimal values, loop over whole numbers and calculate the decimal from each one. This also avoids the creeping float errors you saw in Chapter 13:

for i in range(5):
    print(i / 4, end=" ")
print()

Output

0.0 0.25 0.5 0.75 1.0

Quick check

Write the numbers each of these produces: range(3, 8), range(0, 20, 5), range(6, 0, -2), range(4, 4).

Show the answer

Answer: 3 4 5 6 7; 0 5 10 15; 6 4 2; and nothing (an empty range).

Practice 14.2

Predict the output

What does it print?

for i in range(2, 9, 3):
    print(i, end=" ")
print()
for i in range(4, 0, -1):
    print(i, end=" ")
print()

Fill in the blank

Fill in the arguments of range so that the program prints 10 8 6 4 2.

for i in range():
    print(i, end=" ")
print()

The finished program prints:

Target

10 8 6 4 2

Multiple choice

How many passes does the loop for i in range(5, 2): make?

Choose one answer

14.3 for or while?

Both can do anything the other can. Choosing well makes the code say what you mean.

total = 0
for number in range(1, 6):
    total += number
print(total)

Output

15

Compare this with the while version in Chapter 13: the start, the condition and the update have all moved into the single phrase range(1, 6). The body contains only the real work.

for while
Repeats once for each item as long as a condition is true
How many passes? known when the loop starts not known in advance
Counter handled for you you manage it
Can it run for ever by accident? no yes
Typical jobs every character, every number from 1 to n, every line of a file until the user quits, until the input is valid, until a value is reached

The rule of thumb:

  • If you can finish the sentence "for each ... in ...", use for. This is called a definite loop: the amount of work is fixed before it starts.
  • If the sentence is "keep going until ...", use while. This is an indefinite loop.

Asking for a password until it is right: while. Printing a 12-times table: for. Taking the digits off a number with % 10 and // 10: while. Looking at each character of the text of that number: for.

Practice 14.3

Multiple choice

A loop whose amount of work is fixed before it starts has a special name. Which one?

Choose one answer

Put the lines in order

Put the lines in order. The program adds the numbers 1 to 4 and prints the total one time.

The program in the right order prints:

Target

10
  1. for number in range(1, 5):
  2. total = 0
  3. total += number
  4. print(total)

14.4 The patterns, in for form

Every pattern from Chapter 13 has a shorter for version.

Adding up

n = int(input("Add the numbers from 1 to: "))
total = 0
for number in range(1, n + 1):
    total += number
print("Total:", total)

Output

Add the numbers from 1 to: 100
Total: 5050

Notice the n + 1. To include n, the stop value must be one past it. This is the single most common thing to get wrong with range.

Multiplying

product = 1
for number in range(1, 6):
    product *= number
print(product)

Output

120

Counting things in a string

How many vowels are in a sentence? Look at each character and count the ones that pass a test:

sentence = "Programming is fun"
vowels = 0
for ch in sentence.lower():
    if ch in "aeiou":
        vowels += 1
print("Vowels:", vowels)

Output

Vowels: 5

ch in "aeiou" asks whether the character is one of those five letters, using the membership test from Chapter 5. The sentence is lowercased once, before the loop, so capitals are counted too.

Building a new string

A string can be an accumulator too. Start with the empty string and add to it. This removes every space:

text = "one two  three"
result = ""
for ch in text:
    if ch != " ":
        result += ch
print(result)

Output

onetwothree

Where you add the new piece decides the order. Adding at the front reverses the string:

word = "stressed"
backwards = ""
for ch in word:
    backwards = ch + backwards
print(backwards)

Output

desserts
Pass ch backwards after
1 s s
2 t ts
3 r rts
4 e erts
... ... ...
8 d desserts

(You already know the shortcut, word[::-1]. The loop shows what that shortcut does.)

Keeping the best so far

Which character of a word comes last in the alphabet?

word = "python"
latest = word[0]
for ch in word:
    if ch > latest:
        latest = ch
print(latest)

Output

y

The "best so far" starts as the first character, not as some made-up value. That way it is always a real item from the data.

The promise from Chapter 9: a secret message

Chapter 9 shifted a single letter along the alphabet. With a loop you can encode a whole message:

message = "meet me at noon"
shift = 3
secret = ""
for ch in message:
    if ch.isalpha():
        position = ord(ch) - ord("a")
        secret += chr(ord("a") + (position + shift) % 26)
    else:
        secret += ch
print(secret)

Output

phhw ph dw qrrq

Each letter is moved three places on, wrapping round at z. Anything that is not a letter (here, the spaces) is copied unchanged. To decode, run the same loop with a shift of -3.

Quick check

What does this build? out = "" then for ch in "abc": with the block out = out + ch + "-"

Show the answer

Answer: "a-b-c-". Note the extra hyphen at the end: a separator added after every item leaves one too many. "-".join("abc") from Chapter 9 avoids that.

Practice 14.4

Predict the output

What does it print?

code = "b2c40"
result = ""
count = 0
for ch in code:
    if ch.isdigit():
        result += ch
        count += 1
print(result)
print(count)

Fill in the blank

Fill in the stop value so that the loop adds every number from 1 to n, with n included.

n = 6
total = 0
for number in range(1, ):
    total += number
print(total)

The finished program prints:

Target

21

Fix the bug

This program should print the product of all the numbers from 1 to the number the user types. For 5 it should print 120, but it always prints 0. Fix it.

With the reply 5, the program prints the lines below. Your program must print exactly these lines.

Example run

120

Write code

Count one letter. Ask for a sentence, then ask for one letter. Use a loop to count how many times that letter is in the sentence. Capital and small letters count as the same letter. Print the count.

With the replies Tokyo to Toronto then t, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Count: 4

Write code

Add the digits. Ask for a line of text. Add up every digit that is in the text and print the sum. For Room 12, floor 34 the digits are 1, 2, 3 and 4. If the text has no digit, print 0.

With the reply Room 12, floor 34, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Sum of digits: 10

14.5 Looping by position

Sometimes you need to know where each item is, not only what it is. Then loop over the indexes. range(len(word)) produces exactly the valid indexes of word:

word = "code"
for i in range(len(word)):
    print(i, word[i])

Output

0 c
1 o
2 d
3 e

You need positions when you want to:

  • print or use the position itself;
  • look at neighbours, such as word[i] and word[i + 1];
  • walk two sequences in step, using the same i for both;
  • visit only some positions, such as every second one.

Here is a neighbour example: does a word contain a double letter?

word = "balloon"
for i in range(len(word) - 1):
    if word[i] == word[i + 1]:
        print("Double letter:", word[i] * 2)

Output

Double letter: ll
Double letter: oo

The range is len(word) - 1, not len(word). The block looks at word[i + 1], so i must stop one short of the last index. Otherwise the final pass would reach past the end and raise an IndexError. Whenever a loop looks ahead by one, shorten the range by one.

Do not use the index when you do not need it

Beginners who have just learned range(len(...)) tend to use it everywhere:

for i in range(len(word)):      # works, but it is the long way round
    print(word[i])

for letter in word:             # the Python way
    print(letter)

If the block only ever uses word[i] and never i on its own, loop over the string directly. It is shorter, clearer and cannot go out of range.

When you want both the position and the item, the built-in enumerate hands you the two together → Chapter 36:

for i, letter in enumerate("code"):
    print(i, letter)

Output

0 c
1 o
2 d
3 e

Practice 14.5

Predict the output

What does it print?

word = "planet"
for i in range(0, len(word), 2):
    print(i, word[i])

Fix the bug

This program should count the places where a letter is the same as the next letter. For balloon it should print Pairs: 2. Now it crashes on the last pass. Fix it.

With the reply balloon, the program prints the lines below. Your program must print exactly these lines.

Example run

Pairs: 2

Multiple choice

The loop compares each character with the character at the same distance from the other end. What does the program print?

word = "medium"
same = 0
for i in range(len(word)):
    if word[i] == word[len(word) - 1 - i]:
        same += 1
print(same)
Choose one answer

14.6 The loop variable

Four facts about the loop variable clear up most confusion.

1. It is assigned afresh on every pass. Changing it inside the block does not affect the loop:

for i in range(3):
    print("start of pass:", i)
    i = 100
    print("after change:", i)

Output

start of pass: 0
after change: 100
start of pass: 1
after change: 100
start of pass: 2
after change: 100

In a while loop, changing the counter changes how many passes there are. In a for loop it does not. At the top of each pass, Python overwrites the loop variable with the next item, whatever you did to it. You cannot skip ahead or stay in place by changing i.

2. It holds a value, not a connection. The loop variable is just another label on the current item. Assigning to it moves the label and does nothing to the sequence.

3. It survives the loop. After the loop ends, the variable still exists, holding the last item:

for i in range(5):
    pass
print(i)

Output

4

This is different from while. After while i < 5, the counter is 5, one step past the limit. After for i in range(5), it is 4, the last value that was actually produced.

4. If the loop runs zero times, it is never created. for i in range(0) followed by print(i) raises a NameError (unless i already existed). It is the same trap as the variable assigned inside an if in Chapter 11.

Practice 14.6

Predict the output

What does it print?

for i in range(3):
    i = i * 10
    print(i)
print("Later:", i)

Multiple choice

What does this program print?

for i in range(2, 10, 3):
    pass
print(i)
Choose one answer

Fix the bug

This program should add the numbers 1 to 4 and print 10. It prints a different number. Fix it.

The program prints the lines below. Your program must print exactly these lines.

Example run

10

14.7 break and continue in a for loop

Both work as they do in while.

break leaves the loop at once. The remaining items are never visited. This finds the first space in a string:

text = "hello world"
for i in range(len(text)):
    if text[i] == " ":
        print("First space at index", i)
        break

Output

First space at index 5

continue skips the rest of the current pass and moves on to the next item:

for n in range(1, 11):
    if n % 3 == 0:
        continue
    print(n, end=" ")
print()

Output

1 2 4 5 7 8 10

Here is a pleasant difference from Chapter 13. In a while loop, a continue placed before the update caused an infinite loop. In a for loop that cannot happen: moving to the next item is done by the loop itself, not by a line in the block that might be skipped.

A for loop can also have an else block, which runs when the loop finishes without a break. That is the natural way to say "I looked at everything and did not find it", and it is covered in the next chapter → Chapter 15.

Practice 14.7

Predict the output

What does it print?

for ch in "window":
    if ch == "d":
        break
    print(ch, end="")
print()
for ch in "window":
    if ch == "w":
        continue
    print(ch, end="")
print()

Fill in the blank

Fill in the keyword so that the program prints only the odd numbers from 1 to 7.

for n in range(1, 8):
    if n % 2 == 0:
        
    print(n, end=" ")
print()

The finished program prints:

Target

1 3 5 7

Put the lines in order

Put the lines in order. The program prints the first digit that is in the text, and then stops looking.

The program in the right order prints:

Target

First digit: 7
  1. if ch.isdigit():
  2. print("First digit:", ch)
  3. for ch in text:
  4. break
  5. text = "Gate 7B, row 12"

14.8 Classic problems

A multiplication table

number = int(input("Table for: "))
for i in range(1, 11):
    print(f"{number} x {i} = {number * i}")

Output

Table for: 8
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
8 x 10 = 80

FizzBuzz

A famous small test from job interviews. For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise:

for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz", end=" ")
    elif n % 3 == 0:
        print("Fizz", end=" ")
    elif n % 5 == 0:
        print("Buzz", end=" ")
    else:
        print(n, end=" ")
print()

Output

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

The order of the chain is the lesson from Chapter 11: "both" must be tested first, or every multiple of 15 would be caught by the % 3 test and never reach it.

Is it a prime number?

A prime is a whole number above 1 that can be divided exactly only by 1 and itself. To test n, try every possible divisor from 2 upwards and look for one that divides it exactly:

n = int(input("A whole number above 1: "))
is_prime = True
for divisor in range(2, n):
    if n % divisor == 0:
        print(f"{n} = {divisor} x {n // divisor}")
        is_prime = False
        break
print("Prime:", is_prime)

Output

A whole number above 1: 91
91 = 7 x 13
Prime: False

This uses a flag, as in Chapter 13. The program assumes the number is prime until it finds evidence against it, and break stops the search at the first divisor, because one is enough. For n = 2, range(2, 2) is empty, the block never runs, and the flag correctly stays True.

A simple bar chart

String repetition from Chapter 7 turns numbers into pictures:

for size in range(1, 6):
    print(f"{size} " + "#" * size)

Output

1 #
2 ##
3 ###
4 ####
5 #####

Chapter 7 drew this triangle with five separate print calls and promised a shorter way. Here it is.

Practice 14.8

Multiple choice

In this chain the test for 3 comes first. What does the program print?

n = 15
if n % 3 == 0:
    print("Fizz")
elif n % 5 == 0:
    print("Buzz")
elif n % 15 == 0:
    print("FizzBuzz")
else:
    print(n)
Choose one answer

Fill in the blank

Fill in the blank so that the program draws a triangle: one # on the first line, two on the second and three on the third.

for size in range(1, 4):
    print("#" * )

The finished program prints:

Target

#
##
###

Write code

Countdown. Ask for a positive whole number. Print the numbers from that number down to 1 on one line, with a space between them. Then print Go! on the next line.

With the reply 5, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

5 4 3 2 1
Go!

14.9 Common mistakes

The mistake What you see The fix
Expecting range(5) to include 5 0 1 2 3 4 Use range(1, 6) for 1 to 5
Expecting range(1, n) to include n The last value is missing range(1, n + 1)
for i in 5: TypeError: 'int' object is not iterable for i in range(5):
for i in len(word): The same TypeError for i in range(len(word)):
Counting down without a step: range(5, 0) The loop does not run at all range(5, 0, -1)
A float in range TypeError: 'float' object cannot be interpreted as an integer Loop over integers and calculate the float
Looking ahead with word[i + 1] over the full range IndexError on the last pass range(len(word) - 1)
Changing i to skip items No effect Use continue, or a step in range
Forgetting the colon or the in SyntaxError for item in sequence:
The accumulator created inside the loop It resets on every pass Create it before the loop
Using the loop variable after an empty loop NameError Do not rely on it, or set it first
range(len(...)) when the index is not needed Longer, more fragile code Loop over the items directly

14.10 Putting it together

14.11 How for and range work inside Python

+ Practice

Questions with a Check button are checked on this page. Use the hints when you are stuck: the last step always shows the answer. The other questions show the book's answer, so that you can compare.

Questions

Check yourself

In for ch in "dog":, what is ch on each pass? How many passes are there?

Show the answer

"d", then "o", then "g". Three passes, one per character.

Check yourself

What numbers does range(4) produce? Why is 4 not among them?

Show the answer

0, 1, 2, 3. The stop value is never included, so that range(n) gives exactly n numbers and matches the valid indexes of a sequence of length n.

Check yourself

Write a range call that produces 10, 8, 6, 4, 2.

Show the answer

range(10, 0, -2).

Check yourself

What is the difference between range(5) and list(range(5))?

Show the answer

range(5) is a lazy range object that produces numbers when asked. list(range(5)) collects them into the list [0, 1, 2, 3, 4].

Check yourself

When is for the better choice, and when is while? Give one example of each.

Show the answer

for when the items or the number of passes are known at the start, such as every character of a string. while when the loop continues until something happens, such as asking until the input is valid.

Check yourself

Why does for i in range(1, n): not add up all the numbers from 1 to n?

Show the answer

range(1, n) stops at n - 1. To include n, the stop must be n + 1.

Check yourself

In a loop that compares text[i] with text[i + 1], what should the range be, and why?

Show the answer

range(len(text) - 1). On the last pass i + 1 must still be a valid index, so i must stop one before the final index.

Check yourself

What happens if you assign a new value to the loop variable inside a for block?

Show the answer

Nothing changes about the loop. At the start of the next pass, Python assigns the next item to the variable, overwriting your value.

Check yourself

What is the value of i after for i in range(3): pass? What about after i = 0 and while i < 3: i += 1?

Show the answer

After the for: 2, the last value produced. After the while: 3, the first value that failed the condition.

Check yourself

Why can continue cause an infinite loop in while but not in for?

Show the answer

In while, moving on depends on an update line in the block, which continue may skip. In for, the loop itself fetches the next item, so it always advances.

Predict the output

Predict the output

for i in range(2, 11, 3):
    print(i, end=" ")
print()
for i in range(3, 0, -1):
    print(i, end=" ")
print()
print(list(range(4, 1)), len(range(5, 20, 5)))

Predict the output

word = "level"
count = 0
for ch in word:
    if ch == "l":
        count += 1
    else:
        count += 10
print(count)

Predict the output

result = ""
for ch in "abc":
    result = ch + result + ch
print(result)

Predict the output

total = 0
for i in range(1, 8):
    if i % 2 == 0:
        continue
    if i > 5:
        break
    total += i
print(total, i)

Predict the output

s = "hello"
for i in range(len(s)):
    if i % 2 == 0:
        print(s[i].upper(), end="")
    else:
        print(s[i], end="")
print()

Fix the bug

Fix the bug

This should print the numbers 1 to 5. It prints 0 to 4.

The program prints the lines below. Your program must print exactly these lines.

Example run

1
2
3
4
5

Fix the bug

This crashes.

Print each letter on its own line.

The program prints the lines below. Your program must print exactly these lines.

Example run

p
y
t
h
o
n

Fix the bug

This should count down from 5 to 1. It prints nothing.

Print each number on its own line.

The program prints the lines below. Your program must print exactly these lines.

Example run

5
4
3
2
1

Fix the bug

This should print each pair of neighbouring letters. It crashes on the last pass.

Print each pair on its own line.

The program prints the lines below. Your program must print exactly these lines.

Example run

ch
ha
ai
in

Fix the bug

This should print how many digits are in the text, which is 4. It prints 1.

The program prints the lines below. Your program must print exactly these lines.

Example run

4

Fix the bug

This should print only the first vowel in the word. It prints all of them.

The program prints the lines below. Your program must print exactly these lines.

Example run

First vowel: e

Coding problems

Write code · Easy

Squares. Print the squares of the numbers from 1 to 10 on one line.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

1 4 9 16 25 36 49 64 81 100

Write code · Easy

Spell it out. Ask for a word and print its letters separated by hyphens, in capitals, such as P-Y-T-H-O-N, using a loop. Avoid a hyphen at the end.

Print one line only: the letters in capitals with a hyphen between them.

With the reply python, the program prints the lines below. Your program must print exactly these lines.

Example run

P-Y-T-H-O-N

Write code · Easy

Sum of the evens. Print the sum of all even numbers from 2 to 100, using a range with a step.

The program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

2550

Write code · Medium

Count the kinds. Ask for a sentence and print how many letters, digits, spaces and other characters it contains.

Print the four counts in this order: letters, digits, spaces, others.

With the reply Flight 815 lands at 4:30!, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Letters: 13, digits: 6, spaces: 4, others: 2

Write code · Medium

Factorial table. Print the factorial of every number from 1 to 10, one per line, such as 5! = 120. Use a single loop: each factorial is the previous one multiplied by the next number.

Print ten lines in exactly this form: 5! = 120.

The program prints the lines below. Your program must print exactly these lines.

Example run

1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
10! = 3628800

Write code · Medium

Divisors. Ask for a positive whole number and print all its divisors on one line, and then how many there are.

Print the divisors first, on one line, from the smallest to the largest. Then print how many there are.

With the reply 36, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

1 2 3 4 6 9 12 18 36
Number of divisors: 9

Write code · Medium

Decode. The message wkh fdnh lv d olh was encoded with the method in section 14.4, using a shift of 3. Write a loop to decode it.

Print one line only: the decoded message.

The program prints the lines below. Your program must print exactly these lines.

Example run

the cake is a lie

Write code · Hard

Longest run. Ask for a string and print the length of the longest run of the same character in a row. For aabbbbcc the answer is 4.

With the reply aabbbbcc, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Longest run: 4

Write code · Hard

Binary to decimal. Ask for a binary number as text, such as 1011, and convert it to decimal with a loop, without using int(text, 2).

With the reply 1011, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

11

Write code · Hard

Fibonacci. In the Fibonacci sequence, each number is the sum of the two before it: 0, 1, 1, 2, 3, 5, 8, 13... Ask how many numbers to print, and print that many.

Print the numbers on one line, starting with 0.

With the reply 10, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

0 1 1 2 3 5 8 13 21 34

Chapter project: Step counter report

Project

A report for a step counter. Leo writes down how many steps he walks each day. Write a program that:

  1. asks for the number of days (a whole number, at least 1)
  2. asks for the steps of each day, one question per day, using a for loop and range

Then print three lines, in this order:

  • the total number of steps
  • the number of the best day (day 1 is the first day; if two days share the highest count, the earlier day wins)
  • how many days reached the target of 8000 steps or more

Plan before you write code: you need one accumulator for the sum, a "best so far" with its day number, and one counter.

With the replies 3 then 5000 then 9200 then 8000, the program prints the lines below. Your labels can be different. The numbers must be the same, in the same order.

Example run

Total steps: 22200
Best day: 2
Days on target: 2