Python is a dynamically typed programming language, which means that the data type of a variable is determined automatically at runtime. However, sometimes it is necessary to convert the data type of a variable to another type. This process is called type conversion or casting.
        Python provides built-in functions to convert one data type to another. In this blog, we will discuss the basics of type conversion and casting in Python.

Data Type Conversion


    Type conversion is the process of converting one data type to another. Python provides the following built-in functions for type conversion:

int(): This function converts a string or a floating-point number to an integer.

a = "10"
b = float(5.5)
c = int(a)
d = int(b)
print(c) # Output: 10
print(d) # Output: 5


float(): This function converts an integer or a string to a floating-point number. Example:

a = 10
b = "5.5"
c = float(a)
d = float(b)
print(c) # Output: 10.0
print(d) # Output: 5.5

str(): This function converts any data type to a string.

a = 10
b = 5.5
c = str(a)
d = str(b)
print(c) # Output: '10'
print(d) # Output: '5.5'

bool(): This function converts any data type to a Boolean value.

a = 10
b = "hello"
c = ""
d = bool(a)
e = bool(b)
f = bool(c)
print(d) # Output: True
print(e) # Output: True
print(f) # Output: False

Type Casting 

        Type casting is the explicit conversion of a variable from one data type to another. Python allows type casting by specifying the data type in parentheses before the value or variable to be converted.

Example:

a = "10"
b = float(5.5)
c = int(a)
d = int(b)
e = str(10)
f = bool(5)
print(c) # Output: 10
print(d) # Output: 5
print(e) # Output: '10'
print(f) # Output: True

In the above example, we have used type casting to convert the data types of variables.

Conclusion 
        In this blog, we have discussed the basics of type conversion and casting in Python. Python provides built-in functions for type conversion and allows type casting by specifying the data type in parentheses before the value or variable to be converted. Understanding type conversion and casting is important for working with different data types and for performing various operations in Python.

Read Next Chapter Click Here ->  Conditional statements: if, else, elif