What type is it?
Every value has a type. type() tells you which one:
print(type(42))
print(type(3.5))
print(type("hello"))
print(type(True))Output
<class 'int'> <class 'float'> <class 'str'> <class 'bool'>
| Type | Means | Example |
|---|---|---|
int | whole number | 42 |
float | decimal number | 3.5 |
str | text (string) | "hello" |
bool | True or False | True |
Changing types
Sometimes you need to turn one type into another. This is called type conversion:
int()– make a whole numberfloat()– make a decimal numberstr()– make text
text_number = "25"
real_number = int(text_number)
print(real_number + 5)
price = float("9.99")
print(price)
age = 30
print("I am " + str(age) + " years old")Output
30 9.99 I am 30 years old
In the last line we needed str(age) because you can't join text and a number with +:
age = 30
print("I am " + age)Output (Python stops with an error)
TypeError: can only concatenate str (not "int") to str
That red message is a TypeError: Python is telling you the types don't fit together.
Common mistake:
int("hello")doesn't work, becausehelloisn't a number.int("3.7")doesn't work either – usefloat()for decimals.
Tip:
int()on a float simply chops off the decimal part:int(3.9)is3.