Type Conversion / Casting in Python

At some point, nearly every Python program needs to turn one data type into another — a string typed by a user into a number you can do math with, or a number into a string you can display. That's python type conversion, and this article covers how it works, both automatically and manually, along with the errors it commonly produces.

What is Type Conversion?

Type conversion means changing a value from one data type to another — turning a string "5" into the integer 5, or an integer 5 into the float 5.0.

Python handles this in two distinct ways:

  • Implicit conversion — Python does it automatically, behind the scenes, when it's safe to do so.

  • Explicit conversion (casting) — you deliberately convert a value yourself, using a built-in function.

Why it matters

Get type conversion wrong, or skip it when it's needed, and you'll run into one of Python's most common early errors: a TypeError from trying to combine two incompatible types, like adding a number to a string. Understanding when Python converts automatically — and when you need to do it yourself — heads off a lot of confusion.

Implicit Type Conversion

Implicit conversion happens automatically whenever Python can combine two types without losing information or guessing your intent.

The "promote to the larger type" rule

The clearest example is mixing integers and floats. Python automatically converts the integer to a float so the operation can proceed without losing precision:

result = 5 + 2.5
print(result)          # 7.5
print(type(result))    # <class 'float'>

The 5 was implicitly treated as 5.0 for the purposes of this calculation. Python follows a consistent rule here: when combining two numeric types, it "promotes" the result to whichever type can represent both values accurately — int to float, but never the other way around automatically, since converting a float to an int would silently throw away the decimal portion.

count = 3
average_score = 88.5

total = count + average_score
print(total)          # 91.5
print(type(total))    # <class 'float'>

This only works between compatible numeric types. Python won't implicitly convert a string and a number for you — that requires explicit conversion, covered next.

Explicit Type Conversion (Casting)

Explicit conversion — often called casting — is when you deliberately convert a value using one of Python's built-in constructor functions.

The core casting functions
int()       # convert to integer
float()     # convert to float
str()       # convert to string
bool()      # convert to Boolean
complex()   # convert to complex number
String to int

This is the single most common casting operation in beginner code, usually applied to user input:

age_input = "25"
age = int(age_input)
print(age + 5)   # 30
Float to int — truncation, not rounding

This trips people up often enough to call out explicitly: converting a float to an int with int() truncates the decimal portion — it does not round.

print(int(9.8))    # 9  — not 10
print(int(9.1))    # 9
print(int(-9.8))   # -9 — truncates toward zero, not "down"

If you actually want rounding behavior, use Python's built-in round() function instead:

print(round(9.8))   # 10
Number to string, for concatenation

Strings and numbers can't be combined with + directly — you have to convert the number to a string first:

age = 30
message = "You are " + str(age) + " years old"
print(message)

(Note: an f-string, as covered in the earlier article on strings, handles this more cleanly — f"You are {age} years old" — but explicit str() conversion is worth understanding on its own, since you'll still need it in non-f-string contexts.)

Casting bool to and from int

Since bool is technically a subclass of int in Python, casting between them is direct and predictable:

print(int(True))     # 1
print(int(False))    # 0
print(bool(1))        # True
print(bool(0))        # False
print(bool(-5))       # True — any nonzero number casts to True

Common Conversion Errors and How to Handle Them

ValueError from non-numeric strings

Trying to convert a string that isn't actually a valid number raises a ValueError:

int("hello")
# ValueError: invalid literal for int() with base 10: 'hello'

int("3.14")
# ValueError: invalid literal for int() with base 10: '3.14'

That second example surprises some beginners — "3.14" looks numeric, but int() can't parse a decimal point directly. You'd need to go through float() first: int(float("3.14")).

TypeError from combining incompatible types

If you skip conversion entirely and try to combine incompatible types directly, Python raises a TypeError instead:

age = 30
print("Age: " + age)
# TypeError: can only concatenate str (not "int") to str

The fix is the explicit conversion covered above: "Age: " + str(age).

Safely handling conversions with try/except

Because a python casting error like ValueError will crash your program if left unhandled, it's good practice to wrap risky conversions — especially anything coming from user input — in a try/except block:

user_input = input("Enter your age: ")

try:
    age = int(user_input)
    print(f"In 10 years, you'll be {age + 10}")
except ValueError:
    print("That doesn't look like a valid number.")

This way, a mistyped or unexpected input produces a friendly message instead of an unhandled crash.

Real-World Use Cases

Converting user input to numbers

This is the most common practical scenario for type conversion. The input() function always returns a string, no matter what the user types — so any calculation involving that input requires explicit conversion first:

price_input = input("Enter the price: ")
price = float(price_input)   # float, since prices often include decimals

tax = price * 0.08
print(f"Tax: {tax:.2f}")
Formatting numbers as strings for display

The reverse case is just as common — converting a computed number into a string so it can be combined with other text for output:

total_items = 5
message = "You have " + str(total_items) + " items in your cart"
print(message)

As mentioned earlier, f-strings handle this implicitly and are generally the cleaner choice in modern code, but the underlying concept — number to string — is the same either way.

Casting with collections

Type conversion isn't limited to numbers and strings — Python's collection types support casting too, which is worth knowing even at this early stage:

my_list = list((1, 2, 3))     # tuple to list
my_tuple = tuple([1, 2, 3])   # list to tuple
my_set = set([1, 2, 2, 3])    # list to set — automatically removes duplicates

These will make more sense once you've covered lists, tuples, and sets in detail later in this series, but it's useful to know the same casting pattern — calling the target type as a function — applies well beyond just numbers and strings.

Best practice: validate before casting

Any time you're converting data that comes from outside your program — user input, a file, an API response — treat it as untrustworthy until proven otherwise. Wrap conversions in try/except, check for expected formats before casting, and never assume external data will be exactly the type or shape you expect. This single habit prevents a large share of the crashes beginner programs run into.