NotesPythonGetting Started

Type Conversion

Explicitly converting between types with int(), str(), float(), and friends.

Python won't silently convert types for you in most cases — mixing a string and a number in + raises a TypeError. You convert explicitly using the type itself as a function.

age_text = "21"
age = int(age_text)         # str -> int
price = float("199.99")     # str -> float
count_text = str(42)        # int -> str
flag = bool(1)               # any type -> bool

Why this matters most with input()

input() always returns a string, even if the user types a number — a very common beginner bug is forgetting to convert it.

age = input("Enter your age: ")   # age is a string, e.g. "21"
next_year = int(age) + 1           # must convert before doing math

What counts as "truthy" when converting to bool

bool(x) is False for: 0, 0.0, "" (empty string), [], {}, set(), and None. Everything else is True.

print(bool(0), bool(""), bool([]), bool("no"), bool([1]))
# False False False True True

Conversion errors

Converting a non-numeric string with int() or float() raises ValueError — this is exactly the kind of thing you handle with a try/except (covered later in Exception Handling).

int("abc")   # ValueError: invalid literal for int() with base 10: 'abc'
Key points to remember
  • Python doesn't auto-convert types in operations like + — you convert explicitly with int(), str(), float(), bool().
  • input() always returns a str, even for numeric input — you must convert it before doing arithmetic.
  • bool(x) is False for 0, 0.0, '', [], {}, set(), and None; everything else is True.
  • int()/float() on a non-numeric string raises ValueError, not a silent 0.

Converting input() before doing math

Revision Flashcards

1 / 3

Tap a card to flip it and see the answer.