Text and Numbers
Every value in Python has a type. So far, you've used three types:
- whole numbers, such as
25or-3. Python calls themint, from integer. - decimal numbers, such as
1.5or3.0. Python calls themfloat, from floating point. - text, such as
"Hello". Programmers call it a string, as in a string of characters, and Python calls itstr.
That's why text needs quotes and numbers don't: 25 is a number, but "25" is text made of the characters 2 and 5. In the output, you can't tell them apart: print(25) and print("25") both print 25. But the type decides what an operator does. For example, + adds two numbers, but joins two strings:
print(5 + 3)
print("5" + "3")This prints:
8
53And what about a string and a number? Python can't know whether you want to add numbers or join text, and it doesn't guess. It stops with an error:
age = 25
print("I am " + age + " years old.")This prints:
Traceback (most recent call last):
File "<exec>", line 2, in <module>
TypeError: can only concatenate str (not "int") to strThe last line says what went wrong: a TypeError, an error of types. Python can only concatenate (join) a str to a str, not an int. The line above it says where it happened: line 2. You'll learn more about error messages later in this lesson.
To fix it, convert the value to the type you need. Python has a function for each type:
str()turns a value into a string:str(25)is"25".int()turns a string into a whole number:int("25")is25.float()turns a string into a decimal number:float("2.5")is2.5.
age = 25
print("I am " + str(age) + " years old.")
print(int("5") + 3)
print(float("2.5") + 1)This prints:
I am 25 years old.
8
3.5Numbers often come as text, for example when someone types them into a form or when they are read from a file. Before you calculate with them, convert them with int() or float(). If you forget, you get a TypeError again, and when the number comes first, as in 25 + "5", its description is different: unsupported operand type(s) for +: 'int' and 'str'. It means that + can't work with an int and a str.
When you separate values with commas, you don't need str(): print("I am", age, "years old.") works with any type. And in the next exercise, you'll learn an even easier way to put numbers into text.
Instructions
- 1
The program ends with an error. Run it and read the last line of the error message. Then fix the last line with
str(), so that the program printsScore: 120. - 2
The bonus is stored as text:
"30"is in quotes. Leave it as it is, and on a new line, printNew score:and the score with the bonus added, separated by a comma. Convert the bonus to a number first, withint(bonus). The program should print:Score: 120 New score: 150