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)
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)
|....|....|....|....|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}")
Even numbers: 2, 4, 6, 8, 10Every 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.