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.

FunctionDescription
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(), and bool().
  • It is often used when working with user input or calculations.