Ticker

6/recent/ticker-posts

Python Casting

Python Casting: Converting Data Types in Python

Casting in Python refers to converting one data type into another. Python provides implicit and explicit casting methods to help manage data of different types.

1. Implicit Type Casting

Python automatically converts smaller data types to larger ones when needed. This is called implicit casting.

# Implicit Type Casting
num_int = 10      # Integer
num_float = 5.5   # Float

# Adding integer and float
result = num_int + num_float  

print("Result:", result)       # Output: 15.5
print("Type:", type(result))   # Output: <class 'float'>

2. Explicit Type Casting

Explicit casting is when you manually convert a variable using built-in functions like int(), float(), and str().

Example 1: Float to Integer

# Explicit Type Casting: Float to Integer
num_float = 7.8
num_int = int(num_float)   # Using int()

print("Float:", num_float)      # Output: 7.8
print("Integer:", num_int)      # Output: 7

Example 2: String to Integer

# Explicit Type Casting: String to Integer
num_str = "123"    # String
num_int = int(num_str)   # Using int()

print("String:", num_str)      # Output: 123
print("Integer:", num_int + 5) # Output: 128

Example 3: Integer to String

# Explicit Type Casting: Integer to String
num = 100       # Integer
num_str = str(num)  # Using str()

print("Number:", num)          # Output: 100
print("String:", num_str + " apples")  # Output: 100 apples

3. Real-Life Example: Processing User Input

User inputs are strings by default. To perform calculations, they must be converted to integers or floats.

# Taking user input and casting it to integer
age_str = input("Enter your age: ")   # Input is a string
age = int(age_str)                   # Cast to integer

print("Your age after 5 years:", age + 5)

Common Errors in Casting

  • ValueError: Occurs when casting incompatible types.
  • # This will cause ValueError
    num = int("hello")
  • TypeError: Happens when performing invalid operations between types.
  • # This will cause TypeError
    result = "10" + 5
Code copied to clipboard!

Post a Comment

0 Comments