Type casting in Python refers to converting one data type to another. Python provides two types of type casting: implicit and explicit type casting.

1. Implicit Type Casting (Automatic Type Conversion):

Implicit type casting is done automatically by Python when a smaller data type is assigned to a larger data type (for example, converting an integer to a float). This conversion is safe because no data is lost in the process.

Example:

  • # Integer to float (implicit conversion)

  • x = 5      # int

  • y = 2.5    # float


  • result = x + y   # Python automatically converts x (int) to float

  • print(result)    # Output: 7.5


In this example, x is an integer, but when added to the float y, Python implicitly converts x to a float before performing the addition.

2. Explicit Type Casting (Manual Type Conversion):

Explicit type casting, or manual type conversion, is done by the programmer using built-in functions. This is necessary when you want to explicitly convert one type into another.

Common Type Conversion Functions:

  • int() – Converts a value to an integer.

  • float() – Converts a value to a float.

  • str() – Converts a value to a string.

  • bool() – Converts a value to a boolean.

Examples of Explicit Type Casting:

Converting to Integer:
  • # Convert float to integer (loss of decimal part)

  • x = 7.8

  • y = int(x)

  • print(y)   # Output: 7


Converting to Float:
  • # Convert integer to float

  • x = 5

  • y = float(x)

  • print(y)   # Output: 5.0


Converting to String:
  • # Convert integer to string

  • x = 100

  • y = str(x)

  • print(y)   # Output: '100'

  • print(type(y))  # Output: <class 'str'>


Converting to Boolean:
  • # Convert different values to boolean

  • x = 0

  • y = bool(x)  # False because 0 is considered "Falsy"

  • print(y)     # Output: False


  • z = 5

  • w = bool(z)  # True because non-zero numbers are considered "Truthy"

  • print(w)     # Output: True


Example: Type Casting in Operations

  • # Converting user input (which is a string) to integer

  • age = input("Enter your age: ")  # User input as string

  • age = int(age)  # Convert to integer

  • print("Your age is:", age)


In the above example, the input() function returns a string, but we use int() to explicitly convert it to an integer before using it.

Key Points:

  • Implicit Type Casting is automatic and happens when a smaller data type is assigned to a larger one (e.g., int to float).

  • Explicit Type Casting is done using functions like int(), float(), str(), and bool() to manually convert data types.

  • Explicit casting is needed when converting types that are not compatible by default.

Let me know if you need more examples or further clarification! 😊