🎓 A1Learner
🔍

Python Output Variables

Printing a variable shows the value stored in that variable. Commas in print() show several values in one line.

Print with commas

Commas can mix text and numbers safely.

name = "Sam"
age = 11
print("Name:", name, "Age:", age)

Join strings with +

The + sign joins two strings into one.

first = "Py"
second = "thon"
print(first + second)

Text plus a number fails

A string and a number cannot join with +.

name = "Sam"
age = 11
print(name + age)

Fix it with str()

Turn the number into text first.

name = "Sam"
age = 11
print(name + " is " + str(age))

Example

player_name = "Ria"
level = 5
team = "Foxes"
print(player_name + " | Level: " + str(level) + " | Team: " + team)

Key points

  • Use commas in print to show several values in one line
  • Printing a variable shows the value stored in that variable.
  • Commas add a space between the values for you
  • Use + to join strings end to end
  • TypeError: an error when values have types that do not fit
  • Use str() to turn a number into text for joining

In this example, player_name stores text. The level stores a number. The team stores text again. The print line joins the text pieces with +. It turns level into text with str() first. So the line prints as one player card.

Note

+ adds no space between strings.

Add a space inside a string when you need one.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Python Playground

Exercise

Which line prints Sam is 11 without an error?