Python Casting

Python Casting refers to converting a variable from one data type to another. In Python, this is usually done using built-in functions. Unlike some other programming languages, Python does not do implicit type conversion often, so casting is commonly done explicitly.

Converts to an integer – int()

The int() function converts a number or string into an integer type by:

  • Removing the decimal part if it’s a float
  • Parsing a numeric string
  • Returning an error if the value is not convertible
# int() with float
a = int(3.9)
print("From float 3.9 to int:", a)  # Output: 3

# int() with numeric string
b = int("15")
print("From string '15' to int:", b)  # Output: 15

# int() with boolean values
c = int(True)
d = int(False)
print("From boolean True to int:", c)   # Output: 1
print("From boolean False to int:", d)  # Output: 0

# int() with user input (simulate input as string)
user_input = "42"
e = int(user_input)
print("From user input string '42' to int:", e)  # Output: 42

# int() with invalid string (uncomment to see error)
# f = int("hello")  # This will raise ValueError
# print(f)

Do it