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)
*****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)
Ada
Alan
Grace
doneGuest (done to finish): Ada
Guest (done to finish): Alan
Guest (done to finish): Grace
Guest (done to finish): done
Guests: AdaAlanGraceAlmost: += 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)
Ada
Alan
Grace
doneGuest (done to finish): Ada
Guest (done to finish): Alan
Guest (done to finish): Grace
Guest (done to finish): done
Guests: Ada, Alan, Graceguests == "" 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:
>>> 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.