Sometimes a value exists as one data type but you need it as another — a number typed into a form arrives as text, but you need to do math with it. Converting a value from one type to another is called type conversion (or type casting), and Python supports it in two ways: automatically, behind the scenes, or explicitly, when you ask for it.

Implicit Type Conversion

Implicit conversion happens automatically, without you writing any extra code. Python does this when combining compatible numeric types, promoting the "smaller" type to the "larger" one to avoid losing precision:

whole_number = 5
decimal_number = 2.5

result = whole_number + decimal_number
print(result)
print(type(result))

Output:

7.5
<class 'float'>

Python automatically converted the int to a float before adding, since a float can represent everything an int can, with no data lost. This only works between compatible numeric types — Python will not implicitly convert a string to a number.

Explicit Type Conversion

Explicit conversion is when you deliberately convert a value using one of Python's built-in conversion functions: int(), float(), str(), and bool() are the most common.

# String to number
age_text = "25"
age_number = int(age_text)
print(age_number + 5)

# Number to string
score = 90
message = "Your score is " + str(score)
print(message)

# Number to bool
print(bool(0))    # False
print(bool(42))   # True — any non-zero number is True

Output:

30
Your score is 90
False
True

Converting a number to a string is especially common when printing output — Python won't let you directly add a string and a number together with +, so wrapping the number in str() first is a very common pattern.

Common Conversion Errors

Explicit conversion can fail at runtime if the value doesn't actually represent that type. This is one of the most common errors beginners run into, especially when converting user input straight from input():

text = "abc"
number = int(text)  # this line will raise an error

Output:

ValueError: invalid literal for int() with base 10: 'abc'

Because "abc" isn't a valid number, Python raises a ValueError rather than guessing. When converting values that might not always be well-formed (like real user input), it's good practice to wrap the conversion in a try/except block so your program can handle bad input gracefully instead of crashing.

Understanding how values move between types sets you up well for the next topic — writing code that documents itself, covered in Python comments and docstrings.