Type Conversion in Python: Complete Guide
Type conversion (also called casting) is the process of converting a variable from one data type to another. This is essential in Python because many operations require specific types—you cannot add a string and an integer without first converting one of them. Learning to convert between int, float, str, and bool is a fundamental skill that you'll use constantly in real Python programs.
Key Takeaways
- Type conversion transforms one data type into another using built-in functions like
int(),float(),str(), andbool() - Implicit casting happens automatically when Python converts types (e.g., int to float in arithmetic)
- Explicit casting requires manual function calls:
int(3.14)→3,str(42)→"42" - Truthy/falsy values affect boolean conversion: empty strings, 0, empty lists, and
Noneare falsy - Use type conversion to concatenate strings with numbers, perform calculations across types, and validate input data
What is Type Conversion (Casting)?
Type conversion (or casting) is the mechanism by which Python allows you to change a variable's data type to another. Python supports two primary forms of type conversion:
-
Implicit Type Casting — Python automatically converts one data type to another during operations. For example, when you add an integer to a float, Python promotes the integer to a float before performing the addition.
-
Explicit Type Casting — You manually invoke built-in conversion functions:
int(),float(),str(), andbool(). This gives you precise control over when and how conversion occurs.
Why does this matter? Consider building a web application where user input arrives as strings. To validate age ranges, you must convert that string input to an integer. Without type conversion, your program cannot perform arithmetic or comparisons correctly.
How Do You Convert Between Number Types?
Converting between integers and floats is one of the most common conversions you'll perform. Python provides two functions for this: int() truncates decimals, while float() adds decimal notation.
# Type conversion between numbers
my_float = 3.14
my_integer = int(my_float) # Converts to 3 (decimal part removed)
print(f"3.14 converted to int: {my_integer}") # Output: 3.14 converted to int: 3
my_integer = 10
my_float = float(my_integer) # Converts to 10.0
print(f"10 converted to float: {my_float}") # Output: 10 converted to float: 10.0
# Converting string numbers to int/float
price_string = "19.99"
price_float = float(price_string) # Converts "19.99" to 19.99
print(f"Price as float: {price_float}") # Output: Price as float: 19.99
Key point: The int() function truncates (cuts off) the decimal portion; it does not round. If you convert 3.99 to an integer, you get 3, not 4.
How Do You Convert Other Data Types to Strings?
Converting values to strings is essential for displaying data to users and concatenating variables with text. The str() function accepts any Python object and returns its string representation.
# Converting different types to strings
age = 30
score = 95.5
is_active = True
empty_list = []
message = "I am " + str(age) + " years old."
print(message) # Output: I am 30 years old.
result = f"Final score: {str(score)}"
print(result) # Output: Final score: 95.5
# Even complex objects can be converted
print(str(is_active)) # Output: True
print(str(empty_list)) # Output: []
This is particularly useful when building dynamic messages, logging output, or preparing data for APIs that expect string parameters.
How Do You Convert Values to Booleans?
The bool() function evaluates any value as either True or False. Understanding Python's truthy/falsy rules is crucial for writing correct conditional logic.
# Truthy vs Falsy conversion
print(bool(0)) # Output: False (zero is falsy)
print(bool(1)) # Output: True (non-zero is truthy)
print(bool(-5)) # Output: True (negative numbers are truthy)
print(bool(3.14)) # Output: True (non-zero floats are truthy)
print(bool("")) # Output: False (empty string is falsy)
print(bool("Hello")) # Output: True (non-empty string is truthy)
print(bool(" ")) # Output: True (even single space is truthy)
print(bool([])) # Output: False (empty list is falsy)
print(bool([1, 2, 3])) # Output: True (non-empty list is truthy)
print(bool(None)) # Output: False (None is always falsy)
Practical rule: Empty containers (strings, lists, tuples) and zero values are falsy; everything else is typically truthy. This behavior is why you can write concise code like if user_input: to check whether a string contains data.
Complete Type Conversion Reference Table
| Source Type | Target | Function | Example | Result |
|---|---|---|---|---|
| Float | Integer | int() | int(3.99) | 3 |
| Integer | Float | float() | float(10) | 10.0 |
| String | Integer | int() | int("42") | 42 |
| String | Float | float() | float("3.14") | 3.14 |
| Any | String | str() | str(True) | "True" |
| Any | Boolean | bool() | bool(0) | False |
Real-World Example: User Input Validation
Here's a practical scenario where type conversion is essential:
# Real-world: collecting user age and calculating birth year
user_input = input("Enter your age: ") # Always returns a string!
# Convert string to integer
age = int(user_input)
# Perform arithmetic
birth_year = 2026 - age
print(f"If you are {age} years old, you were born around {birth_year}.")
# Error handling example (production code should do this)
try:
age = int(input("Enter your age: "))
if age < 0 or age > 150:
print("Please enter a valid age.")
else:
print(f"You are {age} years old.")
except ValueError:
print("That's not a valid number!")
This demonstrates why type conversion matters: user input is always a string, but arithmetic requires numbers.
What Happens if Type Conversion Fails?
Attempting to convert an invalid value raises a ValueError. For example, int("hello") fails because the string "hello" does not represent a number:
# This will raise a ValueError
try:
result = int("abc")
except ValueError as e:
print(f"Conversion failed: {e}")
# Output: Conversion failed: invalid literal for int() with base 10: 'abc'
Always validate input before conversion in production code, or wrap conversions in try/except blocks.
Frequently Asked Questions
What is the difference between implicit and explicit type conversion?
Implicit conversion happens automatically. When you add an integer and a float, Python converts the integer to a float so both operands match: 2 + 3.5 becomes 2.0 + 3.5 = 5.5. Explicit conversion requires you to call a function: int(3.9) → 3. Explicit is safer because you control exactly when conversion occurs.
Can you convert any string to an integer?
No. The string must represent a valid number. int("42") works, but int("hello") raises a ValueError. Strings with whitespace can be converted: int(" 123 ") → 123, but any non-numeric characters cause failure. Always validate strings before converting to integers in production applications.
Why does bool(1) return True but bool(0) return False?
Python treats 0 as falsy (representing "nothing" or "off") and any non-zero number as truthy (representing "something" or "on"). This aligns with how zero and non-zero values appear in conditional logic: if x: is equivalent to if bool(x):. This convention comes from C and Unix traditions where 0 signals failure and non-zero signals success.
Is type conversion the same as rounding?
No. int(3.9) returns 3 (truncation), while round(3.9) returns 4 (rounding). Type conversion to integer always truncates toward zero, discarding the decimal part. Use round() when you need proper rounding behavior.
How do you convert a list to a string?
Use str() to convert the entire list: str([1, 2, 3]) → "[1, 2, 3]". If you want a custom format, iterate through the list and join elements: ", ".join([str(x) for x in [1, 2, 3]]) → "1, 2, 3". For more complex formatting, consider using json.dumps() to serialize lists to JSON strings.
Conclusion
Type conversion is a cornerstone of Python programming. You now understand how to transform between integers, floats, strings, and booleans using int(), float(), str(), and bool(). You've learned the distinction between implicit conversion (automatic) and explicit conversion (manual), and you've seen real examples of when and why conversion matters.
As you progress, you'll use type conversion constantly: validating user input, preparing data for APIs, formatting output, and ensuring operations have the correct types. Master these fundamentals now, and you'll write more robust and flexible Python code.