Rocket is adding up the crew list. He types "5" + "5" into the shell, expecting a team of ten. The shell answers with 55.
"Fifty-five crew members?" he says. "We only have chairs for ten!"
Raven points at the quote marks on the screen. "What do you notice?" she asks. "Those fives are inside quotes. Python thinks they are text, not numbers."
Nova hums and draws two boxes in the air: one labeled numbers, one labeled text. "Would you like a hint?" she asks. "Every value has a type. The type decides what plus means."
Rocket deletes the quote marks, presses Enter, and gets 10. Then he asks the shell what type each value is.
| Type | Name in Python | Examples |
|---|---|---|
| Whole number | int | 42, 0, -7 |
| Decimal number | float | 3.5, 0.25, 100.0 |
| Text (a string) | str | "Nova", "42", "" |
| True or false | bool | True, False |
The type() function tells you the type of any value. Plus adds numbers, but it joins strings end to end.
>>> type(42)
<class 'int'>
>>> type(3.5)
<class 'float'>
>>> type("42")
<class 'str'>
>>> type(True)
<class 'bool'>
>>> "5" + "5"
'55'
>>> 5 + 5
10 You already know / divides and keeps the decimal. Two more signs are useful. // divides and drops the decimal part. % gives the remainder.
For example, 130 seconds is 130 // 60 minutes, which is 2, and 130 % 60 seconds left over, which is 10.
>>> 7 / 2 3.5 >>> 7 // 2 3 >>> 7 % 2 1
The int() and float() functions turn strings into numbers. The str() function goes the other way, turning a number into a string.
Dividing with / always makes a float, even when the answer is a whole number.
>>> int("7") + 3
10
>>> str(7) + "3"
'73'
>>> type(10 / 2)
<class 'float'>
>>> 200 // 60
3
>>> 200 % 60
20 | Statement | True or false? |
|---|---|
| "8" + "2" gives 10. | ? |
| int("8") + int("2") gives 10. | ? |
| 9 // 2 gives 4. | ? |
| 9 % 2 gives 4.5. | ? |
Types explain a lot of surprises. Tomorrow your programs will ask the user a question, and types will matter right away.