Python Arena
Step 4 of 4

Strings that grow round by round

In the last module you built strings in a loop: start with the empty string "", and add a piece in every round with +=. That works just as well in a loop with a condition. The pieces can be f-strings, which saves you the str() that a number would otherwise need:

countdown = ""
number = 5
while number > 0:
    countdown += f"{number}... "
    number -= 1
countdown += "Go!"
print(countdown)
Output
5... 4... 3... 2... 1... Go!

Why not print each piece right away? Because every print starts a new line, and here the whole countdown should be on one line. A string you've built can also wait: after the loop, the program can add more to it, as with Go! here, print it twice, or check it first.

Choosing the piece

Each round can decide what to add. This loop draws a ruler, with a | at every fifth position and a dot everywhere else:

ruler = ""
position = 0
while position <= 20:
    if position % 5 == 0:
        ruler += "|"
    else:
        ruler += "."
    position += 1
print(ruler)
Output
|....|....|....|....|

The loop runs 21 rounds, for the positions 0 to 20, and in each round the if picks the piece. % gives the remainder of a division, so position % 5 == 0 is true for 0, 5, 10, 15 and 20.

Separators: the first piece first

In the last module, an if kept a separator from being left over at the end: it added the separator only when the string wasn't empty any more. When you know the first piece before the loop starts, there's a simpler way. Put that piece in the string before the loop, and add every later piece with the separator in front of it:

evens = "2"
number = 4
while number <= 10:
    evens += f", {number}"
    number += 2
print(f"Even numbers: {evens}")
Output
Even numbers: 2, 4, 6, 8, 10

Every comma sits between two numbers, and the loop needs no if. Note how the start value of number is 4, not 2: the 2 is already in the string.

Your task

Challenge 1 of 3

The program draws a progress bar of 10 places: a # for every task done and a - for every task still to do. Fill in the line that adds a # to the bar.

Tasks done (out of 10): 4
[####------]

Challenge 2

Write a program that asks for a number and prints its first five multiples on one line, separated by a comma and a space, as below. Build the line in a loop.

Number: 7
Multiples of 7: 7, 14, 21, 28, 35

Challenge 3

Write a program that asks for prices with the prompt Price: until the user types 0. Then it prints all the prices as one sum, with the total at the end, as below. You can assume the first price isn't 0.

Price: 4
Price: 10
Price: 3
Price: 0
4 + 10 + 3 = 17