In Python (programming language), type casting refers to converting one data type into another data type. This is useful when you need to perform operations between different types of data.
For example, converting a string "10" into an integer 10.
π Why Type Casting is Used
Type casting is commonly used when:
- Taking input from users
- Performing mathematical calculations
- Converting data formats
Example:
age = int("25")
print(age)
Here the string "25" is converted into an integer.
π Common Type Casting Functions
Python provides built-in functions for type conversion.
| Function | Description |
|---|---|
int() | Converts value to integer |
float() | Converts value to floating-point number |
str() | Converts value to string |
bool() | Converts value to boolean |
π’ Convert to Integer
Use int() to convert values into integers.
Example:
x = int(5.8)
print(x)
Output:
5
Example with string:
num = int("10")
print(num)
π£ Convert to Float
Use float() to convert values into decimal numbers.
Example:
x = float(5)
print(x)
Output:
5.0
Example:
num = float("10.5")
print(num)
π€ Convert to String
Use str() to convert numbers into strings.
Example:
x = str(100)
print(x)
Example:
age = 25
text = str(age)
print("Age is " + text)
βοΈ Convert to Boolean
Use bool() to convert values into True or False.
Example:
print(bool(1))
print(bool(0))
Output:
True
False
π§ͺ Example Program
age = "20"age_number = int(age)print(age_number + 5)
Output:
25
β Key Points
- Type casting converts one data type to another.
- Python provides built-in functions like
int(),float(),str(), andbool(). - It is often used when working with user input or calculations.