Type Conversion

Turning text into numbers and back, what converts silently, and what raises rather than guessing.

conversion.py

conversion.py Python 3
Output

                    

conversion_care.py

conversion_care.py Python 3
Output

                    

Worth knowing

The type names are the conversions: int(), float(), str(), list().
int("3.9") raises; int(3.9) truncates toward zero.
round(2.5) is 2, not 3 - it rounds to the nearest even on a tie.
bool("0") is True. Any non-empty string is.

Type Conversion: A Practical Guide

Python does not convert types behind your back. You ask, using the type name as a function, and it either succeeds or raises — it will not guess.

The constructors

int("42")    float("3.14")    str(42)    list("abc")    bool("")

Each type's name doubles as its conversion. That is why there is nothing to memorise beyond the types themselves.

Text in, text out

Anything read from a user, a file or a network arrives as text. "10" + "10" is "1010", and no error is raised, because concatenating strings is a perfectly sensible thing to do. Converting is on you:

int(text) + int(text)

This is the single most common source of confusion for beginners, and it is not really about conversion — it is about noticing that input is always a string.

int() is strict about strings and loose about floats

int("3.9")  # ValueError
int(3.9)    # 3

From a string, int refuses anything that is not a whole number, because guessing which way to go would be a decision it has no business making. From a float, it truncates toward zero — int(-3.9) is -3, not -4. If you want nearest, say round.

It does tolerate surrounding whitespace, which is convenient when parsing scruffy input.

round() does not round half up

round(2.5)  # 2
round(3.5)  # 4

On an exact tie, Python rounds to the nearest even number. This is deliberate: always rounding halves up biases a long run of numbers upward. It surprises people once, and it is correct.

Floats are not decimals

0.1 + 0.2 == 0.3  # False

Binary floating point cannot represent 0.1 exactly, so the sum is a hair off. This is not a Python quirk; it is how floats work everywhere. Compare with a tolerance, round before comparing, or use decimal.Decimal for money.

Converting safely

Do not check first — try, and handle the failure:

try:
    return int(text)
except (ValueError, TypeError):
    return default

ValueError covers bad text and TypeError covers None. Testing text.isdigit() first looks tidier and gets negative numbers and whitespace wrong.

bool() is broader than it looks

bool("0") is True, because the string is not empty. Falsy values are: 0, 0.0, "", [], {}, set(), None and False. Everything else is truthy, including "False".

Check yourself

0 of 3

Answer without scrolling back up.

  1. What does `int("3.9")` do?

  2. `round(2.5)` returns what?

  3. `bool("0")` is:

Cheat sheet

Type Conversion

Python does not convert types behind your back. You ask, using the type name as a function, and it either succeeds or raises — it will not guess.

PYTHON · vizlearn.in/python/type_conversion.html

About the author

Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.