Data types in Python: int, float, str, and bool
Every value in Python has a type, and the type decides what you can do with it. A surprising share of bugs come down to one question: is this a number, or text that looks like one?
The big idea
A value's type (int, float, str, or bool) determines which operations make sense and what they produce.
See it in code
Four types cover most of what a beginner writes. type() tells you which one a value is:
print(type(38))
print(type(0.38))
print(type("TEE-SAGE-M"))
print(type(True))<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
38 is a whole number (int), 0.38 has a decimal point (float), anything in quotes is text (str), and True/False are booleans (bool).
Operators can change the type. / always produces a float, // keeps whole numbers whole, and int() converts by chopping off the decimal:
print(38 / 100)
print(1000 // 24)
print(int(520.83))0.38 41 520
int(520.83) is 520, not 521. It truncates; it never rounds. For a break-even count that matters: 520 tees would leave you just short.
Data read from a file or typed by a user arrives as text. Here are the fields of one order line, before and after converting:
quantity = "2"
price = "38.00"
print(quantity * 2)
print(int(quantity) * 2)
print(int(quantity) * float(price))22 4 76.0
Multiplying text repeats it, so "2" * 2 is "22". Convert first: int() for whole numbers, float() for anything with a decimal point.
Type questions follow you everywhere. A DNA sequence is a str, a price series is a list of floats, and whether an order qualifies for free shipping is a bool.
Try it yourself
Print type(38 / 2) and type(38 // 2). Both divide evenly, yet one is a float and the other an int. Then try float("38.00") == 38 and explain the result.
The common mistake
Comparing across types. "38" == 38 is False, with no error to warn you, so a check that should pass silently fails. Convert the text first, then compare.
What it unlocks
Numbers feed operators, booleans drive conditionals, and text has a toolkit of its own in string methods.