Type Conversion
Converting between int, float, str, and bool explicitly, and where implicit conversion sneaks in.
2 min read
Python is dynamically typed but not loosely typed — it won't silently combine a string and a number the way some languages do. You have to convert types explicitly, which is exactly the safety net that catches a whole category of bugs before they happen.
Explicit conversion
Python's built-in type functions double as converters:
age_text = "25"
age = int(age_text) # 25
price = float("19.99") # 19.99
count_text = str(42) # "42"Try this without converting first, and Python refuses:
"Age: " + 25
# TypeError: can only concatenate str (not "int") to strThat error is a feature, not a nuisance — it forces you to be explicit about what you meant instead of guessing.
age = 25
print("Age: " + str(age)) # "Age: 25"Conversion can fail
Not every string is a valid number:
int("hello")
# ValueError: invalid literal for int() with base 10: 'hello'This is exactly why input() — which always returns a string — needs careful handling before you treat the result as a number. A later lesson on try/except covers catching this kind of error gracefully instead of letting the program crash.
Converting to bool
Every value in Python has a "truthiness" — a bool it converts to in an if check, even without calling bool() explicitly:
bool(0) # False
bool(1) # True
bool("") # False -- empty string
bool("hi") # True -- non-empty string
bool([]) # False -- empty list
bool([1, 2]) # True -- non-empty list
bool(None) # FalseThe pattern: zero, empty strings, empty collections, and None are all "falsy"; nearly everything else is "truthy." This is why you'll often see if my_list: instead of if len(my_list) > 0: in Python code — both work, but the first is considered more idiomatic.
Implicit conversion (the one place Python does it automatically)
Python will automatically widen an int to a float in mixed arithmetic, since no precision is lost doing so:
result = 5 + 2.5 # 7.5, a floatThat's the only automatic conversion Python performs. Everything else — string to number, number to string, anything to bool for an explicit check — needs to be spelled out, which keeps type-related bugs visible in the code rather than hidden behind silent coercion.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.