Python Arena
Step 5 of 5

Building strings in a loop

A helper variable doesn't have to hold a number. A string can grow in a loop too: start with the empty string "" and add to it with +=, which joins strings just as + does:

stars = ""
count = 0
while True:
    stars += "*"
    count += 1
    if count == 5:
        break
print(stars)
Output
*****

Each iteration adds one * to the end of stars, and the whole string is printed once, after the loop.

Collecting input

In the same way, a program can collect what the user types:

guests = ""
while True:
    name = input("Guest (done to finish): ")
    if name == "done":
        break
    guests += name
print("Guests: " + guests)
Input
Ada
Alan
Grace
done
Output
Guest (done to finish): Ada
Guest (done to finish): Alan
Guest (done to finish): Grace
Guest (done to finish): done
Guests: AdaAlanGrace

Almost: += joins the strings exactly as they are, so the names run together. They need a comma and a space between them, but not before the first name, and not after the last one either. So add the separator in front of each name, except the first:

guests = ""
while True:
    name = input("Guest (done to finish): ")
    if name == "done":
        break
    if guests == "":
        guests = name
    else:
        guests += ", " + name
print("Guests: " + guests)
Input
Ada
Alan
Grace
done
Output
Guest (done to finish): Ada
Guest (done to finish): Alan
Guest (done to finish): Grace
Guest (done to finish): done
Guests: Ada, Alan, Grace

guests == "" is true only for the first name, while nothing has been added yet.

Numbers into the string

+ joins only strings, so a number must be converted with str before it's added:

In the Python interpreter
>>> row = ""
>>> row += str(1) + " "
>>> row += str(2) + " "
>>> row
'1 2 '

Without str, Python stops with the TypeError you saw earlier: can only concatenate str (not "int") to str.

Your task

Challenge 1 of 3

Write a program that asks for a number and prints a countdown from it on one line, followed by Liftoff!:

Count down from: 5
5 4 3 2 1 Liftoff!

Challenge 2

Write a program that asks for items for a shopping list until the user types done, and then prints them on one line, separated by commas. There's no comma after the last item. If the user typed no items at all, it prints The list is empty.

Item: milk
Item: bread
Item: eggs
Item: done
Shopping list: milk, bread, eggs

Challenge 3

Write a program that asks for a height and draws a staircase of # characters: the first row has one, and each row has one more than the row before.

Height: 4
#
##
###
####