Python Casting
Learn how to convert between different data types in Python
🔄 Type Casting in Python
Type casting converts values between different data types. Python provides simple built-in functions like int(), float(), str(), and bool() for type conversion.
w = int("42") # String to integer: 42
x = float("3.14") # String to float: 3.14
y = str(100) # Integer to string: "100"
z = bool(1) # Returns True
int()
Integer
float()
Float
str()
String
What is Type Casting?
Type casting (or type conversion) is the process of converting a value from one data type to another. Python provides built-in functions to perform these conversions.
🔄 Why Use Casting?
- Convert user input (always strings) to numbers
- Prepare data for mathematical operations
- Format output for display
- Ensure compatibility between different data types
Main Casting Functions
int()
Converts to integer
Integer Conversion
int("42") # Returns 42
float()
Converts to floating point
Float Conversion
float("3.14") # Returns 3.14
str()
Converts to string
String Conversion
str(42) # Returns "42"
bool()
Converts to boolean
Boolean Conversion
bool(1) # Returns True
Converting to Integer
int() Function Examples
# Converting string to integer
text = "123"
number = int(text)
print(f"Converting '{text}' to {number}")
# Converting float to integer
price = 9.99
whole_number = int(price) # Removes decimal part
print(f"Converting {price} to {whole_number}")
# Converting boolean to integer
result = int(True) # Gives 1
print(f"True converts to {result}")
result = int(False) # Gives 0
print(f"False converts to {result}")
Converting to Float
float() Function Examples
# Basic float conversions
text = "3.14" # A string number
number = float(text) # Convert to float: 3.14
print(f"Converting '{text}' to {number}")
whole = 5 # A whole number
decimal = float(whole) # Convert to float: 5.0
print(f"Converting {whole} to {decimal}")
# Simple calculations with floats
price = float("10.99") # Store price as float
quantity = 3
total = price * quantity
print(f"Total cost: ${total}")
Simple Grade Calculator
# Simple grade calculator
print("Grade Calculator")
# Get two test scores
test1 = float(input("Enter first test score: "))
test2 = float(input("Enter second test score: "))
# Calculate average
average = (test1 + test2) / 2
print(f"Your average is: {average}")
# Show letter grade
if average >= 90:
print("You got an A!")
elif average >= 80:
print("You got a B!")
elif average >= 70:
print("You got a C!")
else:
print("You need to study more!")
Converting to String
str() Function Examples
# Basic string conversion examples
number = 42
text = str(number) # Convert number to string
print(f"Number {number} becomes string '{text}'")
price = 9.99
price_text = str(price) # Convert decimal to string
print(f"Price {price} becomes string '{price_text}'")
# Combining text with numbers
name = "Alice"
age = 25
message = "Hello " + name + ", you are " + str(age)
print(message)
# Easy way using f-strings
message = f"Hello {name}, you are {age}"
print(message)
Simple Shopping List
# Simple shopping list with prices
print("=== Shopping List ===")
# Items and prices
apple_price = 0.50
banana_price = 0.30
milk_price = 2.99
# Calculate total
total = apple_price + banana_price + milk_price
# Print shopping list
print("Apple: $" + str(apple_price))
print("Banana: $" + str(banana_price))
print("Milk: $" + str(milk_price))
print("-----------------")
print("Total: $" + str(total))
Converting to Boolean
bool() Function Examples
# Converting numbers to booleans
print("=== Numbers to Boolean ===")
print(f"bool(0): {bool(0)}") # False
print(f"bool(1): {bool(1)}") # True
print(f"bool(-1): {bool(-1)}") # True
print(f"bool(42): {bool(42)}") # True
print(f"bool(0.0): {bool(0.0)}") # False
print(f"bool(3.14): {bool(3.14)}") # True
# Converting strings to booleans
print("\n=== Strings to Boolean ===")
print(f"bool(''): {bool('')}") # False (empty string)
print(f"bool('Hello'): {bool('Hello')}") # True
print(f"bool('False'): {bool('False')}") # True (non-empty string!)
print(f"bool('0'): {bool('0')}") # True (non-empty string!)
# Converting collections to booleans
print("\n=== Collections to Boolean ===")
print(f"bool([]): {bool([])}") # False (empty list)
print(f"bool([1, 2, 3]): {bool([1, 2, 3])}") # True
print(f"bool({}): {bool({})}") # False (empty dict)
print(f"bool({{'a': 1}}): {bool({'a': 1})}") # True
# None to boolean
print(f"\nbool(None): {bool(None)}") # False
Simple Registration Form
# Simple registration form
print("=== Simple Registration Form ===")
# Get user input
name = input("Enter your name: ")
age = input("Enter your age: ")
# Check if name is empty
if name == "":
print("Name cannot be empty!")
else:
# Try to convert age to number
try:
age_num = int(age)
if age_num < 1 or age_num > 120:
print("Please enter a valid age between 1 and 120")
else:
print(f"\nRegistration successful!")
print(f"Welcome {name}!")
print(f"You are {age_num} years old")
except:
print("Please enter a valid number for age")
Casting Errors and How to Handle Them
Common Casting Errors
print("=== String to Number Errors ===")
# String to int error
try:
num = int("hello")
except ValueError:
print("Can't convert 'hello' to number")
# String to float error
try:
num = float("abc")
except ValueError:
print("Can't convert 'abc' to decimal")
print("=== Empty Value Errors ===")
# Empty string error
try:
num = int("")
except ValueError:
print("Can't convert empty value")
# None value error
try:
num = int(None)
except TypeError:
print("Can't convert None")
print("=== Safe Conversions ===")
def safe_convert(value, type_func, default):
try:
return type_func(value)
except (ValueError, TypeError):
return default
# Test safe conversions
print(safe_convert("123", int, 0)) # 123
print(safe_convert("hello", int, 0)) # 0
print(safe_convert("3.14", float, 0.0)) # 3.14
Simple Collection Casting
Basic List Casting
# Converting string to list
text = "Hello"
char_list = list(text)
print(f"String to list: '{text}' → {char_list}")
# Converting numbers to list
numbers = [1, 2, 3]
print(f"Numbers list: {numbers}")
# Converting strings to numbers list
text_numbers = ["1", "2", "3"]
numbers = [int(x) for x in text_numbers]
print(f"Text numbers to real numbers: {text_numbers} → {numbers}")
Simple Set Example
# Remove duplicates using set
numbers = [1, 2, 2, 3, 3, 3]
unique = list(set(numbers))
print(f"Original list: {numbers}")
print(f"List without duplicates: {unique}")
Simple Casting Examples
Student Information
# Simple program to process student information
def process_student_info():
# Get student information
name = input("Enter student name: ")
age = input("Enter student age: ")
grade = input("Enter grade (0-100): ")
try:
# Convert age to integer
age = int(age)
# Convert grade to float
grade = float(grade)
# Check if student passed (grade >= 60)
passed = bool(grade >= 60)
# Print student information
print("\n=== Student Information ===")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Grade: {grade}")
print(f"Passed: {passed}")
except ValueError:
print("Please enter valid numbers for age and grade")
# Run the program
process_student_info()
Practice Exercise
Temperature Converter
Let's practice type casting by creating a simple temperature converter:
# Simple temperature converter
print("Temperature Converter")
print("Convert Celsius to Fahrenheit")
# Get temperature in Celsius
celsius = input("Enter temperature in Celsius: ")
try:
# Convert input string to float
celsius = float(celsius)
# Calculate Fahrenheit
fahrenheit = (celsius * 9/5) + 32
# Show result
print(f"{celsius}°C is equal to {fahrenheit}°F")
except ValueError:
print("Please enter a valid number!")
What to Learn:
- Converting string input to number using float()
- Basic error handling with try/except
- String formatting with f-strings
Hint:
- Always use try-except blocks for casting user input
- Provide clear error messages for invalid input
- Use appropriate number of decimal places in output
- Test with various input types (integers, floats, invalid strings)