What is Python Casting with Examples

In Python, casting refers to converting one data type into another. This is useful when you want to perform operations that require data in a specific format. Python provides built-in functions like int(), float(), and str() for casting.

Types of Casting in Python

Python supports two types of casting:

  1. Implicit Casting – Python automatically converts data types.
  2. Explicit Casting – You manually convert data types using built-in functions.

1. Implicit Casting

In implicit casting, Python automatically converts one data type into another without losing information.

Example: Implicit Casting:

x = 10   # Integer
y = 3.5  # Float

result = x + y  # Python converts x to float automatically
print("Result:", result)
print("Type of result:", type(result))

Output:

Result: 13.5  
Type of result: <class 'float'>  

Explanation:
Here, Python automatically converts the integer x to a float to match the data type of y.

2. Explicit Casting

Explicit casting is done using built-in functions to convert data types:

  • int() – Converts a value to an integer
  • float() – Converts a value to a floating-point number
  • str() – Converts a value to a string

Example 1: Integer to Float

x = 5  # Integer
y = float(x)  # Convert to float
print("Converted value:", y)
print("Type of y:", type(y))

Output:

Converted value: 5.0  
Type of y: <class 'float'>  

Example 2: Float to Integer

x = 9.8  # Float
y = int(x)  # Convert to integer (truncates the decimal part)
print("Converted value:", y)
print("Type of y:", type(y))

Output:

Converted value: 9  
Type of y: <class 'int'>  

Example 3: Integer to String

x = 100  # Integer
y = str(x)  # Convert to string
print("Converted value:", y)
print("Type of y:", type(y))

Output:

Converted value: 100  
Type of y: <class 'str'>  

Example 4: String to Integer

x = "50"  # String
y = int(x)  # Convert to integer
print("Converted value:", y)
print("Type of y:", type(y))

Output:

Converted value: 50  
Type of y: <class 'int'>  

3. Common Use Cases of Python Casting

  1. Taking input from users and converting it to the required type
age = int(input("Enter your age: "))
print("You are", age, "years old.")

Formatting numbers for calculations

price = "49.99"  # String
discounted_price = float(price) * 0.9  # Convert to float for calculation
print("Discounted price:", discounted_price)

Casting in Python is a powerful tool that ensures your data is in the right format for your operations. Understanding when to use implicit and explicit casting helps prevent errors and makes your code more efficient.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *