Python Casting

Python Casting

Process of converting a variable from one data type to another.

Python casting refers to the process of converting a variable from one data type to another. In Python, there are several built-in functions that allow you to perform casting operations. Understanding how to cast variables is an essential part of writing Python programs.

1. Casting to Integer

To convert a variable to an integer data type, you can use the int() function. The int() function takes a string or a float as an argument and returns an integer value.

Examples:


x = 10.5
y = int(x)
print(y)

Output: 10


x = "15"
y = int(x)
print(y)

Output: 15

2. Casting to Float

To convert a variable to a floating-point data type, you can use the float() function. The float() function takes a string or an integer as an argument and returns a floating-point value.

Examples:


x = 10
y = float(x)
print(y)

Output: 10.0


x = "15.5"
y = float(x)
print(y)

Output: 15.5

3. Casting to String

To convert a variable to a string data type, you can use the str() function. The str() function takes an integer or a float as an argument and returns a string value.

Examples:

x = 10 
y = str(x) 
print(y)

Output: 10

x = 15.5
y = str(x)
print(y)

Output: 15.5

4. Casting to Boolean

To convert a variable to a boolean data type, you can use the bool() function. The bool() function takes a value as an argument and returns either True or False. In Python, the following values are considered False:

  • False
  • None Zero of any numeric type (0, 0.0, 0j)
  • Empty sequences and collections (string, list, tuple, dictionary, set, frozenset)
All other values are considered True.

Examples:

x = 0 
y = bool(x) 
print(y)

Output: False

x = "hello"
y = bool(x) 
print(y)

Output: True

In conclusion, Python casting is a powerful feature that allows you to convert variables from one data type to another. By using the int(), float(), str(), and bool() functions, you can easily cast variables in your Python code.

Did you find this article valuable?

Support Satyam Aaditya by becoming a sponsor. Any amount is appreciated!