Type Casting

Type casting in Python means converting one data type into another data type. Sometimes in programming, you need to change the type of a variable to perform specific operations. Python provides built in functions that allow you to convert data types easily.

Type casting is commonly used when working with numbers, strings, and Boolean values.

WHY TYPE CASTING IS IMPORTANT

Different operations require specific data types. For example, you cannot add a number and a string directly. Type casting allows you to convert data into the correct format so calculations and operations can be performed without errors.

COMMON TYPE CASTING FUNCTIONS

Python provides several built in functions for type conversion:

int() converts a value into an integer
float() converts a value into a floating point number
str() converts a value into a string
bool() converts a value into a Boolean

CONVERTING TO INTEGER

You can convert a float or string into an integer using the int() function.

Example:

x = 10.8
y = int(x)

The value of y will be 10 because decimals are removed.

Example with string:

num = “25”
number = int(num)

Now number becomes an integer.

CONVERTING TO FLOAT

Use the float() function to convert integers or strings into decimal numbers.

Example:

x = 10
y = float(x)

The value of y will be 10.0

Example with string:

price = “99.5”
new_price = float(price)

CONVERTING TO STRING

Use the str() function to convert numbers into text.

Example:

age = 25
text_age = str(age)

Now text_age is a string.

This is useful when combining numbers with text.

Example:

age = 20
print(“My age is ” + str(age))

CONVERTING TO BOOLEAN

The bool() function converts values into True or False.

Example:

print(bool(1))
Output will be True

print(bool(0))
Output will be False

Empty values such as empty string or zero return False. Most other values return True.

IMPLICIT AND EXPLICIT TYPE CASTING

Implicit type casting happens automatically when Python converts smaller data types into larger ones.

Example:

x = 10
y = 2.5
result = x + y

Python automatically converts x into a float.

Explicit type casting is done manually using functions like int(), float(), or str().

CONCLUSION

Type casting helps ensure compatibility between different data types in your program. It prevents errors and allows smooth data processing. Understanding type casting is essential for performing calculations, handling user input, and building efficient Python applications.

Home » PYTHON FUNDAMENTALS (PYF) > Variables and Data Types > Type Casting