Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 149 ยท Data Types

Type Conversion

Convert between Python types with int(), float(), str() and bool(). Learn implicit vs explicit conversion, rounding traps, and how to handle ValueError safely.

Data rarely arrives in the type you need. input() hands you text, a CSV file is full of strings, and a price might be stored as "19.99". Before you can add, compare or format these values properly, you have to convert them to the right type.

Python is strict about mixing types: it won't silently treat "5" as the number 5. That strictness prevents subtle bugs, but it means you need to know the conversion functions int(), float(), str() and bool(), what each one accepts, and what to do when a conversion fails.

Implicit conversion: what Python does for you

Python only converts automatically when no information can be lost and the meaning is obvious. Mixing an int and a float in arithmetic gives a float, and Booleans act as 0 and 1:

Python Automatic conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last line fails. Python refuses to guess whether you meant to join text ("Age: 30") or add numbers. You must say which one you want, by converting explicitly. That's what the rest of this lesson is about.

str(): anything to text

str() turns any value into a string. It's how you join numbers onto text with +, although f-strings (from String Formatting) usually do the job more neatly because they call str() for you.

Python Converting to strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

str() never fails for built-in types. Every value has a text form.

int(): text and decimals to whole numbers

int() builds a whole number. It accepts strings that contain an integer (spaces around it are fine) and it accepts floats, which it truncates toward zero rather than rounding:

Python int() in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that int("3.5") fails even though int(3.5) works. A string must look like a whole number. To convert "3.5" to an integer, go through float first: int(float("3.5")).

Warning: int() chops off the decimal part. int(2.9) is 2. When you mean "nearest whole number", use round(), which you met in Numbers. Python's round() sends exact halves to the nearest even number, so round(2.5) is 2.

float(): text and integers to decimals

float() accepts integers and strings that look like decimal numbers, including scientific notation and a few special words:

Python float() in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Remember that floats are approximations, as covered in Numbers. For money in real applications, the decimal module avoids rounding errors: Decimal("19.99") keeps the value exact.

bool() and other conversions

bool() follows the truthiness rules from Booleans and Truthiness: zero and empty values become False, everything else becomes True. That means bool("False") is True. To turn user text into a Boolean, compare the words instead.

Python also has conversion functions for collections, which you'll use often once you reach Data Structures:

Python
list("abc")            # ['a', 'b', 'c']
tuple([1, 2, 3])       # (1, 2, 3)
set([3, 1, 3, 2])      # {1, 2, 3} (duplicates removed)
dict([("a", 1)])       # {'a': 1}

And a few useful extras: chr(65) gives "A", ord("A") gives 65, and hex(255), bin(5) and oct(8) produce text in other bases.

Converting user input

input() always returns a string, so converting its result is one of the most common jobs in Python. Here a program reads two numbers and adds them:

Python Converting input

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Wrapping input() directly inside int() is the usual pattern. Change the Input box to twelve on the first line and run again: you'll get a ValueError and the program stops.

Handling conversion errors

Real users type unexpected things, so a robust program catches the ValueError and responds sensibly. The try/except statement does this. You'll study it fully in Exceptions and try/except; here's the essential shape:

Python Safe conversion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The function returns None for bad input, the "no value" marker from None. The loop keeps asking until it gets a valid answer or runs out of attempts. (for loops and break come later in for Loops.)

Tip: Catch ValueError specifically, not every exception. A bare except: would also hide unrelated bugs, such as a typo in a variable name.

Checking before converting

String methods like "42".isdigit() can test text before you convert it, as you saw in String Methods. They're handy for simple cases, but they miss negative numbers and decimals ("-4".isdigit() is False). Trying the conversion and catching ValueError handles every case correctly, which is why most Python code prefers it. This "try it and handle failure" style has a name in the Python world: easier to ask forgiveness than permission.

Conversion habits worth keeping

A few habits will save you from most conversion bugs:

  • Convert once, at the edge. Turn text into numbers right where it enters your program, as soon as input() or a file gives it to you. The rest of your code can then trust that age is an int instead of checking again and again.
  • Pick the type that matches the meaning. Counts, ages and quantities are int. Measurements and averages are float. Identifiers that happen to contain digits, such as phone numbers, ZIP codes or product codes, should stay str: int("007") loses the leading zeros, and you never do arithmetic on a phone number.
  • Clean before converting when needed. int() ignores surrounding whitespace, but not thousands separators or currency signs. Strip them first, as in float("$1,250.00".replace("$", "").replace(",", "")).
  • Convert back to text only for display. Keep values as numbers while you calculate, and format them with an f-string at the very end. Converting to text too early leads to "10" + "5" giving "105".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does int(7.8) return?

    int() truncates toward zero, so it drops the .8. Use round(7.8) to get 8.
  2. 2. Which conversion raises a ValueError?

    A string passed to int() must look like a whole number. Use int(float("2.5")) if you need to go from that text to an integer.
  3. 3. Why does "Total: " + 5 fail?

    Python refuses to guess whether you meant addition or joining text. Convert explicitly with str(5) or use an f-string.
  4. 4. What is bool("0")?

    Any non-empty string is truthy, including "0" and "False".
  5. 5. Which exception should you catch when converting user text with int()?

    int() raises ValueError when the text isn't a valid integer.

Summary

  • Python converts implicitly only in safe cases, such as int + float; mixing str and numbers needs an explicit conversion.
  • str() works on any value; f-strings call it for you.
  • int() accepts whole-number text and truncates floats toward zero; use round() to round.
  • float() accepts decimal text, scientific notation, "inf" and "nan".
  • bool() follows truthiness, so bool("False") is True.
  • Invalid text raises ValueError; catch it with try/except to handle bad input gracefully.

Next: Arithmetic Operators, a closer look at Python's math operators and the order they run in.