Python Arena
Step 3 of 5

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)
Python stops with
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print("Your score: " + score)
          ~~~~~~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "int") to str

To 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))
Output
Your score: 42

Commas

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)
Output
Your score: 42
Level 3 of 10

The 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))
Output
Order # 42
Order #42

Staying 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")
Output
Loading... done

Whatever 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.

Your task

Challenge 1 of 3

Fill in the blank so the program prints the line below. points holds an integer, so it can't be joined to a string as it is.

Points: 60

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

Change the program so that it prints the whole countdown on one line, with a space between the parts, as shown below. Keep the four print commands.

3... 2... 1... Go!