Search⌘ K
AI Features

Type Conversion and Casting

Understand Python's strict data typing by mastering implicit and explicit type conversions. Learn to safely cast strings, numbers, and booleans to work seamlessly together in your programs and avoid common errors.

Python is strict about data types. It will not allow us to add a string of text to a number, nor will it intuitively know how to treat the word "True" as a boolean logic value. To make different types of data work together, we must perform Python type conversion or "cast" them into compatible forms. Mastering this allows us to bridge the gap between user input (which often arrives as text) and the logic we need to perform (which usually requires numbers or booleans).

Implicit conversion (coercion)

In certain obvious situations, Python handles the conversion for us. This is called implicit conversion or coercion. The most common scenario involves integers and floats. If we perform arithmetic mixing an integer (whole number) and a float (decimal), Python automatically promotes the integer to a float to prevent data loss.

We do not need to write extra code for this; Python ensures the result preserves the decimal precision.

Python 3.14.0
# Mixing integers and floats
integer_score = 50
bonus_multiplier = 1.5
# Python promotes integer_score to a float for the calculation
total_score = integer_score * bonus_multiplier
print(total_score)
print(type(total_score))
  • Line 2: We define integer_score as an int.

  • Line 3: We define bonus_multiplier as a float.

  • Line 6: When multiplying, Python temporarily treats 50 as 50.0. The result, 75.0, is stored as a float.

  • Lines 8–9: We verify that the final result is indeed a float. This is a great way to learn how to check data type in python using the type() function to confirm Python’s automatic changes.

Explicit conversion (casting)

When the conversion is not obvious, like adding text to a number, Python raises a TypeError.

Python
# This raises a TypeError
print("Score: " + 100)

To solve this, we perform explicit conversion, also known as casting. We use Python's built-in constructor functions to manually transform data: str(), int(), float(), and bool().

Converting to strings

A common operation is combining numbers with text for display. Since we cannot mathematically add a number to a string, we must first cast the number to a string using str().

Python 3.14.0
user_id = 4096
# We convert the integer to a string to concatenate it
message = "User ID: " + str(user_id)
print(message)
print(type(message))
  • Line 1: user_id starts as an integer.

  • Line 3: str(user_id) creates a new string "4096". This can now be safely joined with "User ID: ".

  • Line 5: The output is a single string: "User ID: 4096".

Converting to numbers

When reading data from files or user input, numbers often arrive as strings (e.g., "100" instead of 100). We cannot perform math on text. We must cast these strings into numbers; specifically, knowing how to convert string to int() in python is essential for whole numbers, while float() is used for decimals.

Python 3.14.0
price_tag = "19.99"
qty_string = "5"
# Converting strings to numbers for math
price = float(price_tag)
quantity = int(qty_string)
total = price * quantity
print(total)
  • Lines 1–2: The variables are defined as strings (note the quotes).

  • Line 5: We pass "19.99" into float(), converting it to the number 19.99.

  • Line 6: We pass "5" into int(), converting it to the integer 5.

  • Line 8: The calculation proceeds mathematically, printing 99.95.

Data loss: Floats to integers

Converting a float to an integer using int() does not round the number. It truncates it. This means Python simply discards the decimal part, effectively rounding down toward zero. For example, 9.99 will be truncated to 9.

If we need mathematical rounding, we should use the round() function instead. However, casting is often used when we specifically want to discard the remainder data.

Python 3.14.0
exact_value = 9.99
truncated = int(exact_value) # int() chops off the decimal
rounded = round(exact_value) # round() finds the nearest whole number
print(truncated)
print(rounded)
  • Line 3: int(9.99) ignores the .99 entirely and returns 9.

  • Line 4: round(9.99) evaluates the value and returns 10.

The "Round half to even" rule

It is important to note that Python's round() function uses a strategy called round half to even (or Banker's Rounding). If a number is exactly halfway between two integers (like 2.5), Python rounds to the nearest even number, not always up. This reduces statistical bias when adding up many rounded numbers.

Python
# Banker's rounding examples
print("Round 2.5:", round(2.5))
print("Round 3.5:", round(3.5))
  • Line 2: 2.5 rounds down to 2 (the nearest even number).

  • Line 3: 3.5 rounds up to 4 (the nearest even number).

The boolean cast

In Python, every value (not just booleans) has an inherent "truth" to it. This concept is known as truthy and falsy. When we convert non-boolean data types into booleans using the bool() function, Python applies specific rules:

  1. Falsy: Values that represent "emptiness" or "nothing" convert to False. This includes the number 0, the float 0.0, empty strings "", and the special object None.

  2. Truthy: Almost everything else converts to True. This includes any non-zero number (even negatives) and any string with at least one character.

This behavior allows us to check for data presence very concisely.

Python 3.14.0
# Numbers
print(f"0 is: {bool(0)}")
print(f"100 is: {bool(100)}")
# Strings
print(f"Empty string is: {bool('')}")
print(f"Space string is: {bool(' ')}") # Note the space inside
print(f"Text string is: {bool('Python')}")
# None
print(f"None is: {bool(None)}")
  • Line 2: The integer 0 is falsy.

  • Line 3: The integer 100 is non-zero, so it is truthy.

  • Line 6: An empty string "" has length 0, so it is falsy.

  • Line 7: A string containing a single space ' ' is not empty (length 1), so it is truthy.

  • Line 8: bool('Python') evaluates to True. In Python, any non-empty string is considered "truthy," meaning it counts as True in a boolean context. Since the string 'Python' contains characters, it is not empty, and therefore, the result is True.

  • Line 11: None represents the absence of value and is always falsy.

Common pitfalls: Mixed type

  • Casting is not magic. The source data must be valid for the target type, as Python data types have strict rules about what information they can hold. If we try to cast a string that doesn't look like a number into an integer, Python will stop execution with a ValueError. For example:

Python
bad_data = "100 USD" # This string contains non-numeric characters
conversion = int(bad_data) # This line causes a crash
  • Line 1: The string contains letters ("USD").

  • Line 3: Python cannot translate "USD" into a digit.

  • Another common mistake is confusing the string "False" with the boolean False. Because "False" is a non-empty string, Python considers it truthy. This can lead to dangerous bugs in which a program interprets the text "False" as confirmation to proceed.

Python 3.14.0
status_boolean = False
status_string = "False"
print(f"Boolean False is: {bool(status_boolean)}")
print(f"String 'False' is: {bool(status_string)}")
  • Line 4: We convert the actual boolean False, which remains False.

  • Line 5: We convert the string "False". Since it is not empty, it evaluates to True.

We effectively control how our data is represented in memory. By mastering str(), int(), float(), and bool(), we ensure that our variables interact correctly. Whether we are preparing numbers for a calculation or formatting results for a user message, these tools allow us to bridge the boundaries between data types explicitly and safely.