Python Type Casting (Type Conversion)


In Python, sometimes we need to convert one data type into another. This process is called Type Casting or Type Conversion.

For example, converting a number into a string or a string into a number.


🔹 What is Type Casting?

Type casting means converting one data type into another using built-in functions.

Example:

x = 10
y = str(x)

print(y)
print(type(y))

Output:

10
<class 'str'>

🔹 Common Type Casting Functions

1. int() → Converts to Integer

x = "20"
y = int(x)

print(y)
print(type(y))

2. float() → Converts to Float

x = "10.5"
y = float(x)

print(y)

3. str() → Converts to String

x = 100
y = str(x)

print(y)

🔹 Real-Life Example

Suppose you take input from a user. By default, input is always a string.

age = input("Enter your age: ")
age = int(age)

print(age + 5)

Without conversion, Python will give an error when adding numbers.


🔹 Important Note

Not all conversions are possible.

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

Always ensure the value is compatible before converting.


🔹 Why Type Casting is Important?

  • Helps in calculations
  • Prevents errors
  • Makes data usable in different formats

✅ Conclusion

Type casting allows you to convert data into the required format. It is a very important concept when working with user input and calculations.

In the next article, we will learn about Operators in Python.

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال