Skip to content
Laviyx Learn

Try

Python course menu

Python Type Conversion: int(), float(), str(), bool() and Casting

Learn how to convert between types in Python: int, float, str, bool, list and tuple conversions, implicit vs explicit conversion, truthy and falsy values, and how to handle conversion errors.

Beginner6 min readUpdated
On this page

Data often arrives in the wrong type. Numbers typed by a user, read from a file, or received from a website all arrive as text. Type conversion (also called casting) turns a value of one type into another so you can work with it.

Why conversion is needed#

Python
age = "21"
print(age + 1)
Output
TypeError: can only concatenate str (not "int") to str

"21" is text that happens to contain digits. Python will not guess what you mean, so you must convert it.

Converting with int(), float() and str()#

The type names double as conversion functions:

Python
print(int("42") + 8)        # text -> whole number
print(float("3.75"))        # text -> decimal number
print(str(100) + " points") # number -> text
print(int(9.99))            # decimal -> whole number (cuts off decimals)
print(round(9.99))          # rounding instead
print(float(7))             # whole number -> decimal
Output
50
3.75
100 points
9
10
7.0

int() also ignores surrounding spaces, and can read other number bases:

Python
print(int(" 42 "))
print(int("101", 2))   # binary
print(int("ff", 16))   # hexadecimal
Output
42
5
255

When conversion fails#

Text must actually look like the target type:

Python
print(int("3.5"))
Output
ValueError: invalid literal for int() with base 10: '3.5'

"3.5" is not a whole number. Convert in two steps:

Python
print(int(float("3.5")))
Output
3

You will learn to handle failures gracefully with try / except in Exceptions.

Implicit conversion#

Sometimes Python converts for you, when no information can be lost:

Python
print(3 + 4.5)
print(type(3 + 4.5))
print(True + 2)
Output
7.5
<class 'float'>
3

Mixing int and float gives a float. True and False behave as 1 and 0 in arithmetic. Python never converts text to numbers implicitly; that always needs int() or float().

bool(): truthy and falsy values#

bool() converts anything to True or False. Empty and zero values are falsy; almost everything else is truthy:

Python
print(bool(0), bool(1), bool(""), bool("hi"),
      bool([]), bool([0]), bool(None))
Output
False True False True False True False
FalsyTruthy
0, 0.0any other number
"" (empty string)any non-empty string, even "0" or " "
[], (), {}, set()any non-empty collection, even [0]
None, FalseTrue

This matters in if statements: if name: means "if name is not empty".

Converting collections#

Python
print(list("abc"))
print(tuple([1, 2, 3]))
print(set([1, 1, 2]))
print(str([1, 2]))
Output
['a', 'b', 'c']
(1, 2, 3)
{1, 2}
[1, 2]

set() removes duplicates, a common trick you will meet in Sets.

Common mistakes#

Practice#

Practice exercise

A shopping list stores prices as text: prices = ["120", "75.5", "300"]. Write a program that adds them up and prints Total: 495.50.

Show hint

Some prices have decimals, so convert each one with float() inside a loop, then format with :.2f.

Show solution
Python
prices = ["120", "75.5", "300"]
total = 0
for p in prices:
    total += float(p)

print(f"Total: {total:.2f}")
Output
Total: 495.50

Using int() would fail on "75.5", which is why float() is the right choice here.

Key takeaway#

Finished this lesson?