Lesson · Language Fundamentals
Type Conversion & Coercion
45 min readType Conversion & Coercion
Conversion is explicit in most Python code. This lesson separates conversion from coercion and shows why failed conversions are normal validation events rather than exceptional design mistakes.
Learning goals
- Tell conversion (explicit, in your code) from coercion (automatic, between numeric types).
- Convert text to numbers with
int()andfloat()at an input boundary, and reprompt from theValueErrorwhen the text is not a number. - Convert between collection types with
list(),tuple(), andset(), and say what each does to order and duplicates. - Predict which failure a conversion raises,
ValueErrorfor unparseable content orTypeErrorfor the wrong kind of object, and catch the right one. - Explain why
bool("False")isTrue, and what truth testing actually looks at.
Mental model
Conversion in Python is a constructor call: you ask a type to build a new object from an existing one, and the return value is what flows onward. Two distinctions carry the lesson: conversion is explicit while arithmetic coercion between int and float happens on its own, and every constructor has its own accepted inputs, so the exception raised tells you which contract was broken.
Core idea
All conversions are constructor calls with a contract: int("42") parses text, float(3) widens a number, list((1, 2)) rebuilds a sequence, and bool(x) applies truth testing. Because these are ordinary calls, the interesting questions are always the same: what input does this constructor accept, what does it return, and which exception marks input it cannot handle.
Explicit conversion
Explicit conversion calls a constructor or conversion function to request a new representation. The call documents intent and gives you a clear place to handle invalid data.
int(), float(), str(), bool()
These constructors request explicit conversions to core scalar types. Their accepted inputs and failure modes differ, so treat them as APIs rather than as generic casts.
list(), tuple(), set()
These constructors consume an iterable and build a new collection of the requested type. Converting between types changes mutability, ordering semantics, and duplicate handling.
Numeric coercion
Some mixed numeric operations choose a common representation automatically, such as combining integers and floats. Do not confuse this limited numeric coercion with arbitrary implicit string-to-number conversion.
Conversion failures
A failed conversion normally raises a specific exception, often ValueError or TypeError. Treat this as expected boundary behavior when input originates outside the program.
Truthiness conversion
bool(value) applies the same truth-testing protocol used by if and while. It does not parse textual meanings such as the string 'false', which is truthy because it is non-empty.
Walkthrough
int(raw)parses the string" 42 ": surrounding whitespace is allowed, the result is a newint, andrawitself is unchanged;float("19.95")likewise returns afloat.number + 1andprice * 2use the converted values with numeric literals; the first staysintwhile the second produces afloat, which allows the usual binary rounding in the printed digits.int("forty-two")raisesValueError, and theexceptblock readstype(exc).__name__as the string"ValueError". The failed call never assigned anything, since assignment completes only when the call returns.- Predict before running: the first two printed results, and which exception
int(None)raises instead ofValueError(it isTypeError, becauseNoneis not a string or number).
Experiments to try
- Run
int(" 42 "),int("42\n"),int("4_2"), andint("42.0"); collect which succeed and read theValueErrorfor the failures. - Call
str(42),repr(42), andf"{42}"; all three produce text, so state whyrepris the one meant to be unambiguous. - Convert
[1, 2, 2, 3]to asetand to atuple, print both, and explain what each conversion changed about order and duplicates. - Evaluate
bool("False"),bool(""),bool("0"), andbool(0.0), then write the rule that truth testing follows.
Common mistakes
- Expecting
int("42.0")to parse:int()accepts only whole-number text, so decimal strings go throughfloat()first, and the failure is aValueErrorrather than a silent truncation. - Catching the wrong exception:
int(None)raisesTypeError(wrong kind of object) whileint("abc")raisesValueError(right kind, unparseable content), so a handler that catches only one still crashes on the other. - Assuming conversions modify their input: these constructors build and return new objects, so
tuple(a_list)leavesa_lista list; the new type lives under the name you assign the result to. - Reading
bool("False")asFalse: truth testing looks at emptiness, not meaning, so every non-empty string isTrue; reading a textual boolean requires an explicit comparison.
Practice: Easy
- Run the worked example, then print
type(number)andtype(price); state which call produced each type. - Convert
"3.5"to a float and then to an int with two separate calls; note which conversion loses information and whatint(3.9)does with the fraction. - Evaluate
list("abc"),tuple("abc"), andset("abc")and describe what each returns for the same input.
Practice: Medium
- Write
parse_int(text)that returns anintorNoneusingtry/except ValueError; document what it does withNone,"12", and"12.0". - Build the same collection four ways: tuple to list, list to set, set to list, and string to list of characters; annotate which conversions preserve order and which drop duplicates.
- Compare
bool(x)withx == Trueforxin[0, 1, "", "x", None, []]; print both columns and explain where they disagree.
Practice: Hard
- Classify
1 + 2.0,True + 1, and"1" * 3as explicit conversion, automatic numeric coercion, or sequence repetition; explain why only one of them is coercion. - Build a conversion chart in code: for each constructor in the lesson, one accepted input and one rejected input, printing the exact exception name for each rejection.
- Write a two-paragraph note for a newer programmer explaining why
bool("False")isTrueand which parsing approach actually reads a textual boolean from user input.
Lesson checklist
- I can convert text, numbers, and collections with the right constructor and name the exception each can raise.
- I can tell conversion (explicit) from coercion (automatic numeric promotion) and show one example of each.
- I can explain what
bool()checks and whybool("False")isTrue. - I can say which conversions preserve order and which drop duplicates.
Remember
Conversion is explicit construction: pick the type, call it, and handle the `ValueError` or `TypeError` it documents when the input does not fit. Coercion is the small automatic promotion between numeric types, and the two never blur as long as you convert at the boundary and use `bool()` as a truth test rather than a parser.
Interview angles
What is the main purpose of **Explicit conversion**?+
Explicit conversion calls a constructor or conversion function to request a new representation. The call documents intent and gives you a clear place to handle invalid data.
What should you pay attention to when using **int(), float(), str(), bool()**?+
These constructors request explicit conversions to core scalar types. Their accepted inputs and failure modes differ, so treat them as APIs rather than as generic casts.
How does **list(), tuple(), set()** fit into this lesson?+
These constructors consume an iterable and build a new collection of the requested type. Converting between types changes mutability, ordering semantics, and duplicate handling.
Why does `int("42.0")` fail while `int(float("42.0"))` succeeds?+
int() parses whole-number text only, and the decimal point makes "42.0" unparseable, so it raises ValueError. Converting to float first builds the number 42.0, and int on that number truncates toward zero, which is a different and explicit operation.