Introduction
In real-world Python programs, you constantly move data between different types: numbers, strings, and booleans. This lesson focuses on type conversion and casting—how Python changes data types automatically (implicit conversion) and how you change them deliberately (explicit conversion). You’ll learn to:
- Distinguish implicit vs. explicit type conversion
- Use
int(),float(),str(), andbool()for casting - Predict automatic type promotion in mixed expressions
- Safely convert user input from strings to numbers or booleans
- Diagnose and fix
TypeErrorissues related to incompatible conversions
Implicit vs. Explicit Type Conversion
Implicit Type Conversion (Automatic)
Python sometimes converts values automatically when needed. This is called implicit type conversion or type promotion.
Python mainly does this in numeric expressions where it promotes a smaller/less precise type to a more general one to avoid data loss.
x = 5 # int
y = 2.0 # float
result = x + y # int + float
print(result)
print(type(result))
# Output:
7.0
<class 'float'>
Explanation:
xisint,yisfloat.- Python automatically converts
xtofloat, then adds. - The result is a
float(7.0), not anint.
Explicit Type Conversion (Casting)
When you deliberately change the type of a value, you perform explicit type conversion, also called casting.
You’ll use built-in functions:
int()– convert to integerfloat()– convert to floating-point numberstr()– convert to stringbool()– convert to boolean
age_str = "30"
age = int(age_str) # '30' -> 30
price_str = "19.99"
price = float(price_str) # '19.99' -> 19.99
is_member = True
label = str(is_member) # True -> 'True'
count = 0
is_empty = bool(count) # 0 -> False
print(age, type(age))
print(price, type(price))
print(label, type(label))
print(is_empty, type(is_empty))
# Output:
30 <class 'int'>
19.99 <class 'float'>
True <class 'str'>
False <class 'bool'>
Using int(), float(), str(), and bool()
Converting to int()
int() works well with:
- Integer-like strings (
"10","-3") - Floats (truncates toward zero)
print(int("42")) # valid
print(int(3.99)) # 3
# print(int("3.14")) # would raise ValueError
# Output:
42
3
Converting to float()
float() can handle:
- Float-like strings (
"3.14","-0.5") - Integers
print(float("3.14")) # 3.14
print(float(10)) # 10.0
# Output:
3.14
10.0
Converting to str()
str() is very flexible; it converts almost any object to a human-readable string.
num = 10
price = 4.5
flag = False
print(str(num)) # '10'
print(str(price)) # '4.5'
print(str(flag)) # 'False'
# Output:
10
4.5
False
Converting to bool()
bool() follows Python’s truthiness rules:
False,0,0.0,''(empty string),None, and empty collections areFalse- Almost everything else is
True
print(bool(0)) # False
print(bool(1)) # True
print(bool("")) # False
print(bool("hello")) # True
# Output:
False
True
False
True
Automatic Conversion in Mixed-Type Expressions
Python mostly promotes int to float in mixed numeric operations:
a = 10 # int
b = 3.5 # float
c = a * b # int * float
print(c, type(c))
# Output:
35.0 <class 'float'>
Numeric promotion rules you should be able to predict:
int+float→floatint/int→float(true division)
Python does not automatically convert between numbers and strings in expressions:
x = 5
text = "7"
# result = x + text # This will raise TypeError
result = x + int(text) # Correct: convert text to int
print(result)
# Output:
12
Handling User Input with Type Conversion
Recall that input() always returns a string. To perform arithmetic or boolean logic, you must convert it.
Example: Numeric Input
user_age_str = input("Enter your age: ")
# Convert to int for calculations
user_age = int(user_age_str)
years_to_100 = 100 - user_age
print(f"You will be 100 in {years_to_100} years.")
# Example Output (user types 25):
Enter your age: 25
You will be 100 in 75 years.
Example: Boolean-like Input
Users often type yes/no, true/false, or y/n. You need to interpret these as booleans manually:
answer = input("Do you agree? (yes/no): ").strip().lower()
is_agree = answer in ("yes", "y", "true", "1")
print("Agreement status:", is_agree)
# Example Output (user types "Yes"):
Do you agree? (yes/no): Yes
Agreement status: True
Explanation:
- We normalize the input with
.strip().lower(). - We then check membership in a tuple of truthy words.
- The result is a proper
bool(TrueorFalse).
Common TypeError Issues and How to Fix Them
Most TypeError problems in beginners’ code come from mixing incompatible types. Learn to recognize and fix them quickly.
1. Concatenating Strings and Numbers
score = 10
# print("Score: " + score) # TypeError
print("Score: " + str(score)) # Fix 1: convert number to string
print(f"Score: {score}") # Fix 2: use f-strings
# Output:
Score: 10
Score: 10
2. Adding Numbers and Numeric Strings
x = 5
y = "7"
# print(x + y) # TypeError: unsupported operand types
# Fix: convert string to int or float first
sum_int = x + int(y)
sum_float = float(x) + float(y)
print(sum_int)
print(sum_float)
# Output:
12
12.0
3. Invalid Literal for int() or float()
value = "10kg"
# This will fail:
# weight = int(value) # ValueError: invalid literal for int()
# Safer approach with simple validation
numeric_part = "".join(ch for ch in value if ch.isdigit())
if numeric_part:
weight = int(numeric_part)
print("Weight:", weight)
else:
print("No numeric value found")
# Output:
Weight: 10
Key idea: Only convert strings that are valid numeric literals; otherwise, you’ll get a ValueError at runtime.
Summary / Key Takeaways
In this lesson on Type Conversion and Casting, you have learned:
- Implicit vs. Explicit Conversion: Python automatically promotes numeric types (e.g.,
inttofloat) in mixed expressions, while explicit casting uses functions likeint()andfloat()to control types deliberately. - Core Casting Functions:
int(),float(),str(), andbool()are the primary tools for converting between basic types, each with specific rules and limitations. - Mixed-Type Expressions: In arithmetic, mixing
intandfloatyields afloat, but Python will not automatically mix strings and numbers, which would raiseTypeError. - User Input Handling: Values from
input()are always strings and must be converted to numeric or boolean types before performing calculations or logical checks. - Boolean Interpretation of Strings:
bool()on non-empty strings always returnsTrue; to interpret"yes"/"no"style input correctly, you must implement your own mapping logic. - Preventing TypeError: Most
TypeErrorissues around conversion come from combining strings with numbers without proper casting, which you can fix by converting either the string to a number or the number to a string. - Valid Numeric Literals: Converting strings to numbers requires that the string be a valid numeric literal; otherwise, Python raises
ValueError, so validation or cleanup of input is often necessary. - Predictable Type Behavior: Being able to predict resulting types in expressions and conversions helps you design safer code and debug runtime errors more efficiently.
