Skip to content
Type Conversion
step 1/7

Reading — step 1 of 7

Learn

~2 min readGetting Started

Every value in Python has a type. Sometimes you need to change a value from one type to another — most often when reading user input (which comes in as a string) and using it as a number.

The classic beginner bug

python

input() always returns a string, even if the user typed digits. "25" + 1 makes no sense to Python — strings concatenate, ints add. Python raises a TypeError rather than guess what you meant.

The fix is explicit conversion:

python

The four conversion functions you need

python

What can be converted to what

  • str → int works only if the string is a clean integer: int("42") ✓, int("3.14") ✗ ValueError, int("hi") ✗ ValueError.
  • str → float is more forgiving: float("3.14") ✓, float("42") ✓ (returns 42.0).
  • float → int truncates toward zero: int(3.7) is 3, int(-3.7) is -3 (not -4!). To round properly, use round() first: int(round(3.7)).
  • anything → str always works: str(True)"True", str(None)"None".

Truthy and falsy

Python treats some values as "falsy" — they evaluate to False in a boolean context. Everything else is "truthy."

Falsy values:

  • False, None, 0, 0.0, "" (empty string), [] (empty list), {} (empty dict)

Truthy: everything else.

This lets you write idiomatic Python:

python

Common conversion mistakes

  • Forgetting to convert input: n = input(); print(n + 1) → TypeError.
  • Converting unparseable text: int("3.14") → ValueError. Use float() first if you might have a decimal.
  • Assuming int() rounds: int(2.9) is 2, not 3. Use round(2.9) for proper rounding.
  • Comparing types directly: "5" == 5 is False — they're different types! Convert first.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Type Conversion — Python Fundamentals