Python is a dynamically typed language, which means that the data type of a variable is determined at runtime. However, sometimes it is necessary to convert one data type to another. This process is called casting. Python provides several built-in functions for casting, which we will discuss in this article.
Python provides the following built-in functions for casting:
int()
: converts a number or a string containing a number to an integerfloat()
: converts a number or a string containing a number to a floating-point numberstr()
: converts an object to a stringbool()
: converts a value to a Boolean (True or False)Let's look at some examples of how to use these casting functions:
The int()
function can be used to convert a number or a string containing a number to an integer:
>>> x = 5.6
>>> y = "10"
>>> z = int(x)
>>> w = int(y)
>>> print(z)
5
>>> print(w)
10
The float()
function can be used to convert a number or a string containing a number to a floating-point number:
>>> x = 5
>>> y = "3.14"
>>> z = float(x)
>>> w = float(y)
>>> print(z)
5.0
>>> print(w)
3.14
The str()
function can be used to convert an object to a string:
>>> x = 5
>>> y = 3.14
>>> z = str(x)
>>> w = str(y)
>>> print(z)
'5'
>>> print(w)
'3.14'
The bool()
function can be used to convert a value to a Boolean (True or False):
>>> x = 5
>>> y = ""
>>> z = bool(x)
>>> w = bool(y)
>>> print(z)
True
>>> print(w)
False
Casting is an important concept in Python, as it allows us to convert one data type to another. Python provides several built-in functions for casting, including int()
, float()
, str()
, and bool()
.