Vinay Garg Assistant Professor

Lesson 6: Type conversion in Python

Type conversion changes a value from one type to another so it can be used. int(), float(), str() and bool() cover almost every case, and each one has a rule worth knowing before it fails.

A code window showing age = int("44") and print(float(age))

In short

  • `int()`, `float()`, `str()` and `bool()` convert a value to another type.
  • `int("42")` works; `int("4.5")` raises ValueError because the text is not a whole number.
  • `int(9.99)` cuts the decimal part off (9). `round(9.99)` gives 10.
  • `bool(0)`, `bool("")` and `bool(None)` are False. Almost every other value is True.

4

conversion functions: int, float, str, bool

Python docs

0

automatic conversions between str and int in Python

Python docs

What type conversion is

Type conversion (also called casting) means changing a value from one type to another. Python will not silently turn text into a number for you, so when a value arrives as text and you need to do maths, you convert it yourself.

Four functions cover nearly everything: int(), float(), str() and bool().

The program

# convert.py — moving a value from one type to another

number_text = "42"
print(number_text + "1")        # 421: text joined to text
print(int(number_text) + 1)     # 43: converted first, then added

price = 99.95
print(int(price))               # 99: decimal part is cut off
print(round(price))             # 100: rounded to nearest

age = 44
print(float(age))               # 44.0
print(str(age) + " years")      # 44 years

print(bool(0), bool(1))         # False True
print(bool(""), bool("hi"))     # False True

age_text = "44"
next_year = int(age_text) + 1
print("Next year you will be", next_year)

How it works, step by step

  1. number_text + "1" joins two pieces of text, so the answer is "421". The quotes matter.
  2. int(number_text) reads the text and produces the number 42. Only then does + 1 do arithmetic.
  3. int(price) throws away everything after the decimal point. It does not round, so 99.95 becomes 99, not 100.
  4. round(price) rounds to the nearest whole number, which is 100.
  5. float(age) adds a decimal point: 44 becomes 44.0.
  6. str(age) turns a number into text so it can be joined to " years".
  7. bool() asks "is there anything here?" Zero, empty text and None give False; everything else gives True.

What it prints

421
43
99
100
44.0
44 years
False True
False True
Next year you will be 45

When a conversion fails

int("4.5") raises ValueError, because the text is not a whole number. Convert in two steps instead: int(float("4.5")). Text with letters in it, such as int("hello"), always fails — that is useful, because it stops a bad value instead of quietly turning it into something wrong.

Common mistakes

  • Assuming int() rounds. It cuts. Use round() when you want the nearest number.
  • Forgetting that input() returns text. input() + 1 fails; convert with int(input()).
  • Converting text with a stray space: int(" 42 ") actually works, but int("42,") does not. Clean data before converting.

Practice

Try these before moving on. Each one uses only what this lesson covered.

  1. Store `"15"` as text, convert it to a number and print the number plus 10.
  2. Convert 7 to a float and to a string, and print each with its type.
  3. Ask Python to convert `"hello"` to an int inside a `try` block and print the error message.
  4. Convert 3.99 to an int and to a rounded number, and print both.

Sources

Frequently asked questions

Why does int("4.5") give an error?

Because int() expects text that is a whole number. The dot makes it a decimal, so Python refuses to guess what you meant. Use int(float("4.5")) to convert in two steps.

What is the difference between int() and round()?

int() cuts the decimal part off, so int(9.99) is 9. round() gives the nearest whole number, so round(9.99) is 10. Neither is "better" — they answer different questions.

Why is bool("") False but bool("0") True?

bool() checks whether the value is empty. An empty string is empty, so it is False. The text "0" contains one character, so it is True — it is not the number zero.

Does Python convert types automatically?

Only in a few narrow cases, such as int plus float giving a float. It never turns text into a number on its own, which is why converting with int() or float() is a normal part of reading input.

Vinay Garg

Vinay Garg

Assistant Professor of Computer Science at Multani Mal Modi College, Patiala. Twenty-five years of teaching web programming, and a habit of building the things I teach about.