Data types: int, float, str and bool
🌍 In real life. At home, different things are kept in different ways: rice is weighed in kilograms (it can be 2.5 kg), eggs are counted whole (you can't buy 2.5 eggs), a shopping list is written as words, and a light switch is simply on or off. What you can do with each depends on what kind of thing it is: you can add up kilograms, but you can't add up words.
Python sorts values the same way, into types.
The idea in one sentence: every value has a type, and the type decides what Python can do with it.
Its words:
int: a whole number, like7,-3,2024float: a number with a decimal point, like3.5or0.1str: text in quotes, like"hello"bool: a yes/no answer,TrueorFalsetype(value): tells you a value's type
Step by step, how Python picks the type of what you write:
- Quotes around it? It's a
str, even"7". TrueorFalse? It's abool.- A number with a decimal point? It's a
float. - A whole number? It's an
int.
print(type(7))
print(type(3.5))
print(type("hi"))
print(type(True))How Python uses the type. The same symbol can do different jobs for different types. + adds two numbers, but joins two strings: 7 + 1 is 8, while "7" + "1" is "71". Mixing them, "7" + 1, is an error, because Python won't guess whether you meant maths or joining.
A float is stored as a very close approximation, so 0.1 + 0.2 prints 0.30000000000000004. That's normal for computers, not a bug in your code.
A bool is the answer to a yes/no question. Comparing two values gives you one:
>greater than,<less than==equal to (two=signs!)!=not equal to
print(7 + 1)
print("7" + "1")
print(type("7"))print(5 > 3)
print(2 == 2)
print(10 < 4)
print("cat" != "dog")height = 1.62
is_student = True
print(type(height), type(is_student))Mistakes and edge cases.
- Mixing text and numbers.
"7" + 1givesTypeError: can only concatenate str (not "int") to str. - Small t in true.
print(true)givesNameError: name 'true' is not defined.TrueandFalsestart with a capital letter. - = instead of ==.
=puts a value in a box;==asks "are these equal?". - A comma instead of a decimal point.
3,5isn't three and a half: it's two values, 3 and 5. Write3.5. - Expecting exact decimals.
0.1 + 0.2 == 0.3isFalse, because floats are approximations.
Quiz
This should print the two ages added up, 25, but it stops with a TypeError. Which line is wrong?
age = 12 sister_age = "13" total = age + sister_age print(total)What is the type of
"42"?- int
- str
- float
- bool
What does this print?
print(type(2.0))What does this print?
print("3" + "4")What does this print?
print(8 == 8)Which one is a bool?
- "True"
- True
- 1.0
Coding tasks
Make four variables:
countholding the int10priceholding the float2.5wordholding the str"python"doneholding the boolTrue
aandbare given. Print whether they are equal. The output should be a bool.