Type Casting

Type Casting in Python: In programming, we often need to convert data from one type to another (e.g., turning a string of digits into an actual number).

Concept Explanation

In programming, we often need to convert data from one type to another (e.g., turning a string of digits into an actual number). This process is known as Type Casting (or Type Conversion).

Python is "strongly typed," which means it won't allow you to perform operations that don't make sense for certain types—like adding the number 5 to the text "Hello". However, because it is also "dynamically typed," it provides easy built-in functions to force data into a new format so you can process it exactly how you need.


Syntax or Core Structure

The Big Three Casting Functions

  • int(): Constructs an integer from a literal, a float (rounds down), or a string.
  • float(): Constructs a float from a literal, an integer, or a string.
  • str(): Constructs a string from a wide variety of data types, including numbers.
# To Integer
x = int(1)   # 1
y = int(2.8) # 2 (Notice it truncates, doesn't round!)
z = int("3") # 3

# To Float
a = float(1)     # 1.0
b = float("3")   # 3.0
c = float("4.2") # 4.2

# To String
s = str(100)     # "100"
p = str(3.14)    # "3.14"

Code Example #1 (Basic)

A very common use case is converting user input (which is always a string) into a number so you can perform calculations.

# User enters '10'
age_string = input("How many years old are you? ")

# This would fail: age_string + 1
# This works:
age_number = int(age_string)
next_year = age_number + 1

print(f"Next year, you will be ${next_year} years old.")

Code Example #2 (Intermediate)

Sometimes you have coordinates as strings and you need to ensure they are high-precision floating point numbers before calculating distances.

raw_lat = "34.0522"
raw_lon = "-118.2437"

# Casting to float
latitude = float(raw_lat)
longitude = float(raw_lon)

print("Coordinates processed:")
print(f"Lat: ${latitude}, Lon: ${longitude}")
print(f"Type check: ${type(latitude)}")

Real World Example

Imagine you are building a data importer that reads a CSV file. The "price" column comes in as a string like "19.99". You need to calculate the total revenue.

# Simulating data from a text file
price_str = "19.99"
quantity_str = "5"

# We must cast BOTH to perform arithmetic
price = float(price_str)
quantity = int(quantity_str)

total_revenue = price * quantity

# Now we cast back to String if we want to concatenate manually
print("Total Revenue: $${" + str(total_revenue) + "}")

Common Mistakes

  1. Implicit Truncation: When casting a float to an int (int(9.99)), Python does not round to the nearest number (10). It simply chops off everything after the decimal, resulting in 9. If you need to round, use the round() function instead.
  2. Invalid String Formatting: Trying to cast a non-numeric string to an int (int("Hello")) will cause a ValueError. You can only cast strings that look like numbers.
  3. Double Casting: Trying to cast a string like "19.99" directly to an int (int("19.99")) will crash. You must first cast it to a float, then to an int: int(float("19.99")).

Best Practices

  • Explicit Conversion: While Python does some "implicit" conversion (like 1 + 2.0 resulting in 3.0), it's best to explicitly cast your variables when you know exactly what type you need. This makes your code safer and easier to debug.
  • Handling Decimals: When dealing with money, always cast to float (or use the Decimal library for high precision) rather than int to avoid losing cents.

Practice Exercises

  1. Truncation Test: Take the number 15.95 and cast it to an integer. Print the result and observe if Python rounded it or truncated it.
  2. Input Math: Ask the user for their birth year. Cast it to an integer, subtract it from the current year, and print the result as part of a sentence using str() concatenation (not f-strings!).
  3. The Multi-Step Fix: Try to run int("12.5"). When it fails, fix the code so it successfully extracts the whole number 12 from that string.
  4. Boolean Casting: What happens when you cast int(True) and int(False)? Write a script to find out.