Lessons
Courses

Type Casting in Python [ English ]

1. Introduction

Type casting in Python refers to the process of converting one data type into another. It is used when we need to perform operations between different data types or when we want a value in a specific format.

Python supports two types of type casting:

  1. Implicit Type Casting (Automatic)
  2. Explicit Type Casting (Manual)

2. Implicit Type Casting

2.1 Definition

Implicit type casting is automatically performed by Python when it converts one data type into another without user intervention.

Python usually converts smaller data types into larger data types to avoid data loss.

2.2 Example

x = 10 # inty = 2.5 # float result = x + yprint(result)print(type(result))

Output

12.5<class 'float'>

Explanation

  • Python converts x (int) into float automatically.
  • The result becomes a float.

2.3 Key Points

  • Done automatically by Python
  • Prevents data loss
  • Follows type hierarchy:int → float → complex

3. Explicit Type Casting

3.1 Definition

Explicit type casting is done manually by the programmer using built-in functions to convert data from one type to another.

3.2 Common Type Casting Functions

FunctionDescription
int()Converts value to integer
float()Converts value to float
str()Converts value to string
bool()Converts value to boolean

4. Examples of Explicit Type Casting

4.1 Converting to Integer

x = "10"y = int(x) print(y)print(type(y))

Output

10<class 'int'>

4.2 Converting to Float

x = "3.14"y = float(x) print(y)

Output

3.14

4.3 Converting to String

x = 100y = str(x) print(y)print(type(y))

Output

100<class 'str'>

4.4 Converting to Boolean

print(bool(1)) # Trueprint(bool(0)) # Falseprint(bool("")) # False

5. Type Casting in User Input

age = int(input("Enter age: "))print(age + 5)

Explanation

  • Input is converted from string to integer.

6. Type Casting with Collections

List Conversion

x = (1, 2, 3)y = list(x) print(y)

Tuple Conversion

x = [1, 2, 3]y = tuple(x)

Set Conversion

x = [1, 2, 2, 3]y = set(x) print(y)

7. Invalid Type Casting

x = "hello"y = int(x) # Error

Explanation

  • Cannot convert non-numeric string to integer.
  • Results in ValueError.

8. Practical Example

num1 = input("Enter first number: ")num2 = input("Enter second number: ") sum = int(num1) + int(num2) print("Sum =", sum)

9. Summary

  • Type casting is converting one data type to another.

  • Two types:

    • Implicit (automatic)
    • Explicit (manual)
  • Common functions: int(), float(), str(), bool()

  • Required when working with user input and mixed data types

  • Helps avoid errors and ensures correct operations