Loading...
Loading...
00:00:00

Type Casting in Python

In Python 3, type casting is the process of converting one data type to another data type. This is useful when you need to work with values of different data types, and you want to ensure that the values are compatible with the operations you want to perform.

You can use the following functions to perform type casting in Python:

  • int(x): Converts x to an integer.
  • float(x): Converts x to a floating-point decimal.
  • complex(x): Converts x to a complex number.
  • str(x): Converts x to a string.
  • bool(x): Converts x to a boolean value (True or False).

Here's an example:

x = 42
y = float(x)
z = str(y)

print(x, type(x))
print(y, type(y))
print(z, type(z))

In this example, the integer value 42 is first converted to a floating-point decimal using float(x), then converted to a string using str(y). The resulting values and their data types are printed to the standard output.

NOTE: It's important to note that not all values can be converted to all data types. For example, you can't convert the string "hello" to an integer using int("hello"), because the string doesn't represent a valid integer. In such cases, a ValueError will be raised.