Type conversion (also called type casting) is the process of changing one data type into another. In Python, you often need to convert between different data types to perform operations or display data in the desired format.
There are two types of type conversion:
- Implicit Conversion - Python automatically converts types
- Explicit Conversion - You manually convert types using built-in functions
example:
# Implicit conversion - Python does this automatically
num1 = 10 # integer
num2 = 3.5 # float
result = num1 + num2 # Python converts 10 to 10.0
print(result) # 13.5 (float)
print(type(result)) # <class 'float'>
Python automatically converts data types when it's safe to do so, usually to prevent data loss.
# Integer + Float = Float
a = 5 # int
b = 2.5 # float
sum_result = a + b # 7.5 (float)
# Integer + Boolean = Integer
x = 10 # int
y = True # bool (True = 1)
result = x + y # 11 (int)
# Float + Boolean = Float
p = 3.14 # float
q = False # bool (False = 0)
result = p + q # 3.14 (float)
print(f"5 + 2.5 = {sum_result} ({type(sum_result)})")
print(f"10 + True = {x + y} ({type(x + y)})")
print(f"3.14 + False = {p + q} ({type(p + q)})")
# These will cause errors - no implicit conversion
# "10" + 5 # Error: can't add string and integer
# "Hello" + 123 # Error: can't add string and integer
# [1, 2] + "3" # Error: can't add list and string
# String concatenation requires all strings
name = "Alex"
age = 25
# message = "I am " + name + " and I'm " + age # Error!
message = "I am " + name + " and I'm " + str(age) # Correct
print(message)
Python provides built-in functions to explicitly convert between data types.
# String to integer
age_str = "25"
age_int = int(age_str)
print(f"String: {age_str} ({type(age_str)})")
print(f"Integer: {age_int} ({type(age_int)})")
# Float to integer (truncates decimal part)
price = 19.99
price_int = int(price)
print(f"Float: {price} -> Integer: {price_int}")
# Boolean to integer
print(f"int(True) = {int(True)}") # 1
print(f"int(False) = {int(False)}") # 0
# Converting from different number bases
binary_str = "1010"
octal_str = "17"
hex_str = "FF"
print(f"Binary '1010' to int: {int(binary_str, 2)}") # 10
print(f"Octal '17' to int: {int(octal_str, 8)}") # 15
print(f"Hex 'FF' to int: {int(hex_str, 16)}") # 255
# String to float
temperature_str = "98.6"
temperature_float = float(temperature_str)
print(f"Temperature: {temperature_float}°F")
# Integer to float
count = 42
count_float = float(count)
print(f"Integer: {count} -> Float: {count_float}")
# Boolean to float
print(f"float(True) = {float(True)}") # 1.0
print(f"float(False) = {float(False)}") # 0.0
# Scientific notation
scientific = "1.5e3" # 1.5 × 10³
number = float(scientific)
print(f"Scientific notation: {scientific} = {number}") # 1500.0
# Number to string
age = 28
score = 95.5
is_active = True
age_str = str(age)
score_str = str(score)
active_str = str(is_active)
print(f"Age: '{age_str}' (type: {type(age_str)})")
print(f"Score: '{score_str}' (type: {type(score_str)})")
print(f"Active: '{active_str}' (type: {type(active_str)})")
# Useful for concatenation
name = "Sarah"
age = 30
message = "Hello, I'm " + name + " and I'm " + str(age) + " years old."
print(message)
# Numbers to boolean
print(f"bool(0) = {bool(0)}") # False
print(f"bool(1) = {bool(1)}") # True
print(f"bool(-5) = {bool(-5)}") # True
print(f"bool(0.0) = {bool(0.0)}") # False
print(f"bool(3.14) = {bool(3.14)}") # True
# Strings to boolean
print(f"bool('') = {bool('')}") # False (empty string)
print(f"bool('Hello') = {bool('Hello')}") # True
print(f"bool('0') = {bool('0')}") # True (non-empty string)
print(f"bool('False') = {bool('False')}") # True (non-empty string)
# Other types to boolean
print(f"bool([]) = {bool([])}") # False (empty list)
print(f"bool([1,2]) = {bool([1,2])}") # True (non-empty list)
print(f"bool(None) = {bool(None)}") # False
Since input()
always returns a string, conversion is frequently needed:
# Basic conversion with error handling
def get_integer_input(prompt):
while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("Please enter a valid integer.")
def get_float_input(prompt):
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("Please enter a valid number.")
# Usage
age = get_integer_input("Enter your age: ")
height = get_float_input("Enter your height (in feet): ")
print(f"Age: {age}, Height: {height}")
# Getting multiple numbers from one input
numbers_str = input("Enter three numbers separated by spaces: ")
try:
num1, num2, num3 = map(int, numbers_str.split())
print(f"Numbers: {num1}, {num2}, {num3}")
print(f"Sum: {num1 + num2 + num3}")
except ValueError:
print("Please enter exactly three valid integers.")
# Getting comma-separated values
data_str = input("Enter name, age, score (comma-separated): ")
try:
parts = data_str.split(",")
name = parts[0].strip()
age = int(parts[1].strip())
score = float(parts[2].strip())
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Score: {score}")
except (ValueError, IndexError):
print("Please enter data in the correct format.")
# String to list
text = "Hello"
char_list = list(text)
print(f"String to list: {char_list}") # ['H', 'e', 'l', 'l', 'o']
# List to string
numbers = [1, 2, 3, 4, 5]
numbers_str = str(numbers)
print(f"List to string: {numbers_str}") # "[1, 2, 3, 4, 5]"
# Join list elements into string
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(f"Joined string: {sentence}") # "Python is awesome"
# Converting list of strings to numbers
str_numbers = ["10", "20", "30", "40"]
int_numbers = [int(x) for x in str_numbers]
# or: int_numbers = list(map(int, str_numbers))
print(f"String list: {str_numbers}")
print(f"Integer list: {int_numbers}")
# Convert multiple values at once
string_numbers = ["1", "2", "3", "4", "5"]
# Convert all to integers
integers = list(map(int, string_numbers))
print(f"Integers: {integers}")
# Convert all to floats
floats = list(map(float, string_numbers))
print(f"Floats: {floats}")
# Convert numbers to strings
numbers = [10, 20, 30, 40, 50]
strings = list(map(str, numbers))
print(f"Strings: {strings}")
# Example: Calculator that handles different input types
def smart_calculator():
print("=== Smart Calculator ===")
# Get first number
num1_input = input("Enter first number: ")
try:
# Try integer first, then float
if '.' in num1_input:
num1 = float(num1_input)
else:
num1 = int(num1_input)
except ValueError:
print("Invalid first number")
return
# Get operator
operator = input("Enter operator (+, -, *, /): ")
# Get second number
num2_input = input("Enter second number: ")
try:
if '.' in num2_input:
num2 = float(num2_input)
else:
num2 = int(num2_input)
except ValueError:
print("Invalid second number")
return
# Perform calculation
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
if num2 != 0:
result = num1 / num2
else:
print("Error: Division by zero!")
return
else:
print("Invalid operator!")
return
print(f"Result: {num1} {operator} {num2} = {result}")
print(f"Result type: {type(result)}")
smart_calculator()
# These will raise ValueError
try:
# Cannot convert non-numeric string to number
invalid_int = int("hello")
except ValueError as e:
print(f"Error: {e}")
try:
# Cannot convert empty string to number
empty_int = int("")
except ValueError as e:
print(f"Error: {e}")
try:
# Cannot convert string with spaces to number
spaced_int = int("1 2 3")
except ValueError as e:
print(f"Error: {e}")
# Safe conversion function
def safe_int_convert(value, default=0):
try:
return int(value)
except ValueError:
return default
print(f"safe_int_convert('123'): {safe_int_convert('123')}") # 123
print(f"safe_int_convert('abc'): {safe_int_convert('abc')}") # 0
print(f"safe_int_convert('xyz', -1): {safe_int_convert('xyz', -1)}") # -1
# Python handles big integers automatically, but floats have limits
import sys
print(f"Maximum float value: {sys.float_info.max}")
# This works fine - Python handles big integers
big_int = 10 ** 100
print(f"Big integer: {big_int}")
# But converting very large numbers to float may cause overflow
try:
huge_number = 10 ** 400
huge_float = float(huge_number) # May raise OverflowError
except OverflowError:
print("Number too large to convert to float")
def process_student_data():
"""Process student data from various input formats"""
# Simulating data from different sources
raw_data = [
"Alice,85,92,78", # CSV format
"Bob 90 88 95", # Space-separated
"Charlie|87|91|83" # Pipe-separated
]
students = []
for data in raw_data:
try:
# Determine separator
if ',' in data:
parts = data.split(',')
elif '|' in data:
parts = data.split('|')
else:
parts = data.split()
# Extract and convert data
name = parts[0].strip()
scores = [float(score.strip()) for score in parts[1:]]
average = sum(scores) / len(scores)
students.append({
'name': name,
'scores': scores,
'average': average
})
except (ValueError, IndexError) as e:
print(f"Error processing data '{data}': {e}")
# Display results
print("=== Student Report ===")
for student in students:
print(f"Name: {student['name']}")
print(f"Scores: {student['scores']}")
print(f"Average: {student['average']:.1f}")
print("-" * 30)
process_student_data()
def temperature_converter():
"""Convert temperatures between different scales"""
print("=== Temperature Converter ===")
print("1. Celsius to Fahrenheit")
print("2. Fahrenheit to Celsius")
print("3. Celsius to Kelvin")
print("4. Kelvin to Celsius")
choice = input("Choose conversion (1-4): ")
try:
temp_input = input("Enter temperature: ")
temperature = float(temp_input)
if choice == '1':
# Celsius to Fahrenheit: F = (C × 9/5) + 32
result = (temperature * 9/5) + 32
print(f"{temperature}°C = {result:.1f}°F")
elif choice == '2':
# Fahrenheit to Celsius: C = (F - 32) × 5/9
result = (temperature - 32) * 5/9
print(f"{temperature}°F = {result:.1f}°C")
elif choice == '3':
# Celsius to Kelvin: K = C + 273.15
result = temperature + 273.15
print(f"{temperature}°C = {result:.1f}K")
elif choice == '4':
# Kelvin to Celsius: C = K - 273.15
result = temperature - 273.15
print(f"{temperature}K = {result:.1f}°C")
else:
print("Invalid choice!")
except ValueError:
print("Please enter a valid temperature!")
temperature_converter()
def number_base_converter():
"""Convert numbers between different bases"""
print("=== Number Base Converter ===")
print("1. Decimal to Binary")
print("2. Decimal to Hexadecimal")
print("3. Binary to Decimal")
print("4. Hexadecimal to Decimal")
choice = input("Choose conversion (1-4): ")
try:
if choice == '1':
decimal = int(input("Enter decimal number: "))
binary = bin(decimal)[2:] # Remove '0b' prefix
print(f"Decimal {decimal} = Binary {binary}")
elif choice == '2':
decimal = int(input("Enter decimal number: "))
hexadecimal = hex(decimal)[2:].upper() # Remove '0x' prefix
print(f"Decimal {decimal} = Hexadecimal {hexadecimal}")
elif choice == '3':
binary = input("Enter binary number: ")
decimal = int(binary, 2) # Base 2
print(f"Binary {binary} = Decimal {decimal}")
elif choice == '4':
hexadecimal = input("Enter hexadecimal number: ")
decimal = int(hexadecimal, 16) # Base 16
print(f"Hexadecimal {hexadecimal} = Decimal {decimal}")
else:
print("Invalid choice!")
except ValueError:
print("Please enter a valid number for the chosen base!")
number_base_converter()
def get_positive_number(prompt):
"""Get a positive number from user with validation"""
while True:
try:
value = float(input(prompt))
if value > 0:
return value
else:
print("Please enter a positive number.")
except ValueError:
print("Please enter a valid number.")
# Usage
price = get_positive_number("Enter product price: $")
print(f"Price: ${price:.2f}")
def convert_grade(grade_str):
"""Convert grade string to number with helpful errors"""
try:
grade = float(grade_str)
if 0 <= grade <= 100:
return grade
else:
raise ValueError("Grade must be between 0 and 100")
except ValueError as e:
if "could not convert" in str(e):
raise ValueError(f"'{grade_str}' is not a valid number")
else:
raise e
# Usage with error handling
try:
grade = convert_grade("85.5")
print(f"Grade: {grade}")
except ValueError as e:
print(f"Error: {e}")
# Choose the right conversion for your needs
user_input = "123"
# For calculations, use int() or float()
number = int(user_input)
# For display purposes, keep as string or use str()
display_value = user_input
# For true/false logic, use bool() carefully
is_valid = bool(user_input) # Non-empty string is True
print(f"Number: {number}")
print(f"Display: {display_value}")
print(f"Is valid: {is_valid}")
Type conversion is essential for working with different data types in Python:
Key Points:
- Implicit conversion happens automatically when safe
- Explicit conversion uses functions like int()
, float()
, str()
, bool()
- Always handle ValueError when converting user input
- Use appropriate conversion based on your needs
- Validate converted data to ensure it meets your requirements
Common Conversion Functions:
- int()
- Convert to integer
- float()
- Convert to floating-point number
- str()
- Convert to string
- bool()
- Convert to boolean
- list()
- Convert to list
- map()
- Apply conversion to multiple values
Best Practices:
- Always validate user input before conversion
- Provide clear error messages for invalid input
- Use try-except blocks for safe conversion
- Choose the appropriate data type for your use case
- Test your conversion logic with various inputs
Understanding type conversion thoroughly will help you handle data effectively and create robust programs that can work with different types of input!