Notes

Type Casting in Python [ English ]

< Prev Next >

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      # int
y = 2.5     # float

result = x + y
print(result)
print(type(result))

Output

12.5
<class 'float'>

Explanation

2.3 Key Points

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

Function Description
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 = 100
y = str(x)

print(y)
print(type(y))

Output

100
<class 'str'>

4.4 Converting to Boolean

print(bool(1))   # True
print(bool(0))   # False
print(bool(""))  # False

5. Type Casting in User Input

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

Explanation

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

8. Practical Example

num1 = input("Enter first number: ")
num2 = input("Enter second number: ")

sum = int(num1) + int(num2)

print("Sum =", sum)

9. Summary

< Prev Next >