Combining values when printing
A program often prints text and a number on the same line. Joining them with + seems natural, but it doesn't work:
score = 7 * 6
print("Your score: " + score)
Traceback (most recent call last):
File "main.py", line 2, in <module>
print("Your score: " + score)
~~~~~~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "int") to strTo concatenate is to join strings. + can join a string to a string, but not an integer to a string. Python won't guess whether you meant to add or to join, so it stops.
Turning a number into a string with str
str converts a value into a string: str(42) is the string "42". Commands like str and print, which take a value in parentheses and do something with it, are called functions. And a string joins happily with another string:
score = 7 * 6
print("Your score: " + str(score))
Your score: 42Commas
The other way is the one from the previous module: commas. print accepts values of any type separated by commas and puts a space between each two:
score = 7 * 6
level = 3
print("Your score:", score)
print("Level", level, "of", 10)
Your score: 42
Level 3 of 10The automatic spaces are handy, but sometimes they get in the way. Then joining with str gives you full control:
number = 42
print("Order #", number)
print("Order #" + str(number))
Order # 42
Order #42Staying on the same line with end
Every print ends its line, so the next print starts on a new one. You can change that. Inside the parentheses, end="" tells print to end with an empty string instead of a line break, so the next print carries on where this one stopped:
print("Loading", end="")
print("...", end="")
print(" done")
Loading... doneWhatever string you give to end is printed in place of the line break: with end=" ", the line ends with a space and the next print continues after it.