techmore.in

python - Type Casting

What is Type Casting?

Type casting is the process of converting the data type of a value into another data type. This is essential when data from different sources must be handled together or operations require uniform types.

Why Type Casting?

  • To convert user input (always string) to numbers for calculations
  • To ensure data integrity when combining different data types
  • To meet API or system requirements expecting specific types
  • To avoid type errors at runtime

How to Do Type Casting?

Python provides built-in functions for casting:

Common Type Casting Functions

  • int() - Converts to integer
  • float() - Converts to float
  • str() - Converts to string
  • bool() - Converts to boolean
  • list(), tuple(), set() - Converts between collection types

Examples

sh
# Convert string to int x = int("42") # Convert float to int (truncates decimal part) y = int(3.99) # Convert int to string z = str(100) # Convert list to set my_set = set([1, 2, 3, 3])

Pros of Type Casting

  • Helps avoid runtime errors
  • Makes your code flexible for user inputs
  • Enables compatibility with libraries/APIs

Cons of Type Casting

  • Improper casting may cause ValueError or TypeError
  • May lead to data loss (e.g., float to int)
  • Can make code less readable if overused

Best Practices

  • Always validate before casting
  • Use try-except blocks when working with user input
  • Avoid unnecessary casting