Python Python Tutorial File Handling NumPy Tutorial NumPy Random NumPy ufunc Pandas Tutorial Pandas Cleaning Data Pandas Correlations Pandas Plotting SciPy Tutorial



Python Casting

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.

Built-in Casting Functions

Python provides the following built-in functions for casting:

  • int(): converts a number or a string containing a number to an integer
  • float(): converts a number or a string containing a number to a floating-point number
  • str(): converts an object to a string
  • bool(): converts a value to a Boolean (True or False)

Examples

Let's look at some examples of how to use these casting functions:

int()

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

float()

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

str()

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'

bool()

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

Conclusion

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().

References

Activity