Checking and Changing Types

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'>
TypeMeansExample
intwhole number42
floatdecimal number3.5
strtext (string)"hello"
boolTrue or FalseTrue

Changing types

Sometimes you need to turn one type into another. This is called type conversion:

  • int() – make a whole number
  • float() – make a decimal number
  • str() – 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, because hello isn't a number. int("3.7") doesn't work either – use float() for decimals.

Tip: int() on a float simply chops off the decimal part: int(3.9) is 3.

HOME LEARN COMMUNITY DASHBOARD