Printing Numbers
So far, we have only stored text in variables. Now, we will store numbers in them and print them.
age = 18
print(age) # prints: 18
print("I am " + age + " years old") # causes an error
Why does the third line cause an error when we have concatenated text in this way? Because the computer doesn't know whether we want to concatenate text or add numbers.
To concatenate numbers with text, we must first convert them to text. We do this using the str()
function as follows:
age = 18
print("I am " + str(age) + " years old.")
# prints: I am 18 years old.
If we put a number inside the parentheses of the str function, it is converted to text. Thus, no error occurs and we can print the number along with other text.
Instructions
On the first line, create a variable price
with a value of 150
.
Fix the second line using the str()
function to avoid an error.
Start programming for free
8/10