Chapter 1: The Basics / Lesson 7

Type Conversion

5 min ยท The Basics

Type Conversion

Type conversion (also called type casting) is the process of converting a value from one data type to another. Python provides built-in functions that allow you to explicitly convert between different types.

This is especially important when working with user input (which is always a string) or when you need to perform operations that require specific types.

Basic Type Conversions

Python provides several conversion functions. Here are the most common ones:

conversion.py
# String to Integer age_str = "25" age = int(age_str) # 25 (integer) print(age, type(age)) # 25 <class 'int'> # String to Float price_str = "19.99" price = float(price_str) # 19.99 (float) print(price, type(price)) # 19.99 <class 'float'> # Number to String num = 42 text = str(num) # "42" (string) print(text, type(text)) # 42 <class 'str'> # Float to Integer (truncates, doesn't round) x = 3.7 y = int(x) # 3 (drops decimal part) z = 3.9 w = int(z) # 3 (still 3, not 4!)

Common Conversion Functions

Here are the most frequently used conversion functions with examples:

  • int(x) โ€” Convert to integer (removes decimal part)
  • float(x) โ€” Convert to floating-point number
  • str(x) โ€” Convert to string representation
  • bool(x) โ€” Convert to boolean (True/False)
  • list(x) โ€” Convert iterable to list
  • tuple(x) โ€” Convert iterable to tuple

String to Number Conversions

Converting strings to numbers is common when dealing with user input or reading from files:

string_to_number.py
# String to integer num_str = "42" num = int(num_str) print(num + 8) # 50 (can now do math) # String to float price_str = "19.99" price = float(price_str) print(price * 2) # 39.98 # Converting numbers with different bases binary = "1010" decimal = int(binary, 2) # Convert binary to decimal print(decimal) # 10 hexadecimal = "FF" decimal2 = int(hexadecimal, 16) # Convert hex to decimal print(decimal2) # 255

Number to String Conversions

Converting numbers to strings is useful for displaying values or formatting output:

number_to_string.py
# Integer to string age = 25 age_str = str(age) print("I am " + age_str + " years old") # Float to string pi = 3.14159 pi_str = str(pi) print("Pi is " + pi_str) # Using f-strings (better way - automatic conversion) age = 25 print(f"I am {age} years old") # Automatic conversion!

Boolean Conversions

Python has specific rules for what evaluates to True and False:

boolean_conversion.py
# Numbers to boolean print(bool(0)) # False print(bool(1)) # True print(bool(42)) # True (any non-zero number) print(bool(-5)) # True # Strings to boolean print(bool("")) # False (empty string) print(bool("Hello")) # True (non-empty string) # None to boolean print(bool(None)) # False # Common pattern: check if value exists name = "" if bool(name): print("Name provided") else: print("No name")

Error Handling with Conversions

Converting invalid values will raise errors. It's important to handle these cases:

conversion_errors.py
# These will cause errors: # int("hello") # ValueError: invalid literal # int("12.5") # ValueError: invalid literal (use float first) # float("abc") # ValueError: could not convert # Safe conversion pattern user_input = "25" try: age = int(user_input) print(f"Age: {age}") except ValueError: print("Invalid number!") # Convert float string to int (two steps) price_str = "19.99" price_float = float(price_str) # First to float price_int = int(price_float) # Then to int print(price_int) # 19

Implicit vs Explicit Conversion

Python sometimes converts types automatically (implicit), but explicit conversion is clearer:

implicit_explicit.py
# Implicit conversion (automatic) result = 10 + 5.5 # int + float = float print(result) # 15.5 (float) # Explicit conversion (recommended for clarity) num1 = int(10) num2 = float(5) result = num1 + num2 # More explicit # String concatenation requires explicit conversion age = 25 # message = "I am " + age # ERROR! Can't concatenate str + int message = "I am " + str(age) # Correct: explicit conversion print(message)

โš ๏ธ Common Conversion Errors

โ€ข int("12.5") will fail - must use float("12.5") first, then int()

โ€ข int("hello") will fail - string must contain valid number

โ€ข Converting None to int/float will fail

โ€ข Always validate or use try/except when converting user input!

Practical Example: Safe Input Conversion

Here's a pattern for safely converting user input:

safe_conversion.py
# Safe conversion with validation user_age = "25" if user_age.isdigit(): # Check if all characters are digits age = int(user_age) print(f"You are {age} years old") else: print("Please enter a valid number") # For floats, check differently price_input = "19.99" try: price = float(price_input) print(f"Price: ${price}") except ValueError: print("Invalid price format")
๐ŸŽ‰

Lesson Complete!

Great work! Continue to the next lesson.

main.py
๐Ÿ“ค Output
Click "Run" to execute...