Why 5 + 5 can be 55
A user types 5 and 5 into your calculator. Your program shows 55. It should show 10.
The reason is the data type. A data type is the kind of value. What a user types with input() is always text. Text joins together. It does not add. To add, you must change the text into numbers.
Key words
| Word | What it means | Example |
|---|---|---|
| Type conversion | Changing a value from one data type to another. | text "5" to number 5 |
| Data type | The kind of value. | integer, string |
| Integer | A whole number. | 5 |
| Float | A number with a decimal point. | 2.5 |
| String | Text inside quote marks. | "5" |
| Boolean | True or False. | True |
| Function | A named piece of code that does one job. | int() |
| Concatenation | Joining strings together with +. | "5" + "5" is "55" |
The cells students fill in are left blank in this preview.
Try it: text or numbers?
print("5" + "5")
print(5 + 5)
print(int("5") + int("5"))
# The first joins text. The second adds numbers.
# The third changes text to numbers first.
Four conversion functions
Python gives you four functions to change type. Each one takes a value and gives back the same value in a new type.
int() makes a whole number. float() makes a number with a decimal point. str() makes text. bool() makes True or False.
Worked example: what each one gives
| Code | Result | Type of result |
|---|---|---|
| int("7") | 7 | Integer |
| int(4.9) | 4 (it cuts off the decimal part, it does not round) | Integer |
| float(3) | 3.0 | Float |
| float("2.5") | 2.5 | Float |
| str(12) | "12" | String |
| bool(0) | False | Boolean |
| bool(5) | True (any number except 0 is True) | Boolean |
| bool("hello") | True | Boolean |
| bool("") | False (empty text) | Boolean |
The cells students fill in are left blank in this preview.
Try it: use all four
age_text = "15"
age = int(age_text)
print(age + 1)
price = float("2.50")
print(price * 3)
score = 7
print("Score: " + str(score))
print(bool(0))
print(bool(5))
# Try int("hello") and see the error.
Not every conversion works
data-callouts.warning.label
int("hello") stops the program with a ValueError. Python cannot turn the word hello into a number. int("2.5") also fails, because 2.5 has a decimal point. Data from a user can be wrong, so check it first.
Which conversion fits?
Have a go
Which conversion fits?
5 questionsYour answers are marked here and are not kept. A college account keeps every student’s marks.