MWZ

MINDWAREZONE

Type Casting in python

Similar to type conversion, type casting is explicitly specifying the data type of a value or variable using constructor functions like int()float(), or str().  

Type casting in Python means converting one data type into another data type. It is useful when you need to perform operations that require a specific type of data.

Why Use Type Casting?

Sometimes data is stored in a format that is not suitable for the operation you want to perform. Type casting helps convert the data into the required type.

Example:

str1 = "7"

str2 = "3.142"

str3 = "13"

num1 = 29

num2 = 6.67
            
print(int(str1))

print(float(str2))

print(float(str3))

print(str(num1))

print(str(num2))
            

Output:

7
3.142
13.0
29
6.67
            

Common Type Casting Functions

Python provides several built-in functions for type conversion:

Function Description
int() Converts a value to an integer
float() Converts a value to a floating-point number
str() Converts a value to a string
bool() Converts a value to a boolean
list() Converts a value to a list
tuple() Converts a value to a tuple
set() Converts a value to a set
dict() Converts a value to a dictionary