Python Variables and Data Types · Lesson 8 of 149

Python Type Conversion

What you will learn

  • The four conversion functions: int(), float(), str(), bool()
  • What int() does to decimals (it cuts, it does not round)
  • What happens when the text is not a valid number
  • The conversions Python makes automatically
  • Converting to collections, and text in other number bases

1. Why convert?

Lesson 2.2 showed that a TypeError appears when types do not fit: "Age: " + 25 fails. Type conversion (also called casting) changes a value from one type to another so that the operation works.

Each type has a function with the same name:

Function Makes Example Result
int(x) a whole number int("42") 42
float(x) a decimal number float("3.14") 3.14
str(x) text str(3.5) "3.5"
bool(x) True or False bool(2) True
print(int("42"), float("3.14"), float(2), str(3.5), str(True), str(None))

Output:

42 3.14 2.0 3.5 True None

Converting does not change the original. It gives you a new value that you can store or use straight away.

Quick check: what does `float(2)` give?

2.0. A whole number becomes a decimal number.

2. int(): cuts, not rounds

int() on a decimal removes the decimal part. It always cuts towards zero:

print(int(3.9), int(-3.9))
print(round(3.9))
3 -3
4

To round to the nearest whole number, use round(). Lesson 3.3 covers round fully.

3. Converting text to numbers

Text that looks like a number can be converted:

print(int(" 42 "), float(" 2.5 "), int("+7"), int("-7"), int("007"))
42 2.5 7 -7 7

Spaces around the number are allowed, and a leading + or - works. But text that is not exactly a number raises a ValueError:

int("abc")
int("3.5")
int("1,000")
int("")
ValueError: invalid literal for int() with base 10: 'abc'
ValueError: invalid literal for int() with base 10: '3.5'
ValueError: invalid literal for int() with base 10: '1,000'
ValueError: invalid literal for int() with base 10: ''

Each line above fails when it runs. Notice that:

  • int("3.5") fails, because "3.5" is not a whole number. To get 3, convert in two steps: int(float("3.5")).
  • A comma in "1,000", a space inside the number ("4 2") and empty text all fail.
  • float("abc") fails too, with a similar message: could not convert string to float: 'abc'.

Other types can also fail. int(None) and int([1]) give a TypeError saying the value is not a string, a bytes-like object or a real number.

Checking before converting

.isdigit() is a text method that says whether the text is made only of digits:

print("42".isdigit(), "-5".isdigit(), "3.5".isdigit(), "".isdigit())
True False False False

It is good for a quick check of plain whole numbers, but it rejects negatives and decimals. A more flexible way is to try the conversion and catch the error. That uses try and except, covered in chapter 14. Here is a preview:

text = "abc"
try:
    number = int(text)
except ValueError:
    print("Please type a whole number")
Please type a whole number

4. Automatic conversion

Python sometimes converts for you, when the result is clear:

print(1 + 2.5, True + 1, 2 * 3.0, 10 / 2)
3.5 2 6.0 5.0
  • An int mixed with a float becomes a float.
  • A bool counts as 0 or 1 in arithmetic (lesson 2.3).
  • / always gives a float.

Python does not convert between text and numbers on its own. That is why "10" + 5 fails.

5. Converting to str and bool

str() works on any value and shows how it prints. It never fails:

print(str(10) + "5", int("10") + 5)
105 15

The same pieces give different answers, depending on which side you convert.

bool() follows the truthiness rules from lesson 2.3:

print(bool(0), bool(2), bool("0"), bool(""), bool("False"))
False True True False True

Careful: bool("0") and bool("False") are True, because any text that is not empty is true.

6. Converting to collections

The collection types can also be built from other values. A closer look comes in later chapters:

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

set([1, 1, 2]) shows {1, 2}: a set keeps each value once (chapter 10).

7. Text in other number bases

int() can read text written in another number system if you give the base as a second value:

print(int("101", 2), int("ff", 16), int("12", 8))
5 255 10

Here "101" is read in base 2 (binary), "ff" in base 16 (hexadecimal) and "12" in base 8 (octal). Chapter 3 returns to number bases.

Worked example: totalling prices typed as text

A program has two prices as text: "12.50" and "7.25". Find the total and show it in a sentence.

Step What you do Result
1 Convert each text with float() 12.5 and 7.25
2 Add them 19.75
3 Put the number in an f-string "Total: 19.75"
a = "12.50"
b = "7.25"
total = float(a) + float(b)
print(f"Total: {total}")
Total: 19.75

Without float(...), a + b would join the text into "12.507.25".

Common mistakes

  • Expecting int() to round. int(3.9) is 3. Use round(3.9) to get 4.
  • Calling int("3.5"). Text with a decimal point needs float first, or int(float("3.5")).
  • Forgetting that conversion makes a new value. Writing int(x) alone on a line does not change x; store the result: x = int(x).
  • Converting the wrong side. In "Age: " + int(25) the number is already a number; the text side is fine. Convert the number to text instead: "Age: " + str(25).
  • Expecting bool("False") to be False. Any non-empty text is true.

Key takeaways

  • int(), float(), str() and bool() make a new value of that type.
  • int() on a decimal cuts it; round() rounds.
  • Text that is not exactly a number gives a ValueError; check first, or use try and except.
  • Python converts automatically between numbers (int with float), but never between text and numbers.
  • bool("0") and bool("False") are True: only empty text is false.

Practice

1. What does int("25") + int("5") give? And "25" + "5"?

Show answer

30, then "255". The first adds numbers; the second joins text.

2. What do int(7.9) and int(-7.9) give?

Show answer

7 and -7. int() cuts the decimal part towards zero.

3. Why does int("2.5") fail, and how do you get 2 from it?

Show answer

"2.5" is not a whole number as text, so you get a ValueError. Use int(float("2.5")), which gives 2.

4. Fix the line so it shows Age: 30: print("Age: " + 30).

Show answer

print("Age: " + str(30)) or print(f"Age: {30}").

5. What do bool(""), bool(" ") and bool(0.0) give?

Show answer

False, True, False. Empty text and zero are false; a single space is not empty.

6. Write the line that reads the binary text "1000" as a number, and give the result.

Show answer

int("1000", 2) gives 8. (Binary 1000 means one eight and no smaller parts.)