Casting in Python
Casting is required when you want to change data from one data type to another data type. Casting can also be called as Type conversion. There will numerous situations you might need to change or cast your value based on the requirement.
Check the below example to understand the need for casting.
number_a = 1 number_b = "2" print(number_a+number_b)
This will return the below error.
Traceback (most recent call last): File "stdin", line 1, in module; TypeError: unsupported operand type(s) for +: 'int' and 'str'
The above error is due to the reason that we are trying to add an ‘int’ with a ‘string’ which is expected to give an error. Casting used to avoid such issues.
Let’s take one more example:
If I have a variable called ‘avg_sal’ whose value is a decimal/float like below. If I need to convert to the nearest whole number then we have to use casting.
avg_sal = 9887.2 avg_sal = int(9887.2) #This will return 9887
Convert a string to an integer:
three = "3" print(three) three_cast = int(three) print(three_cast)
There are two types of casting:
- Implicit conversion
- Explicit conversion
Python can handle a certain situation where it can cast data type based on the operation. This kind of casting is called an implicit conversion.
number_a = 1 number_b = 1.5 add_numbers = number_a+number_b print(add_numbers)
Above example despite two numbers are of different data types, the addition operation gave the result as a floating-point number. This is because python allows converting lower data type to higher data type conversion.
You can also handle the conversion of data type explicitly. Let’s take the first example again. We are trying to add a number with a string.
number_a = 1 number_b = "2" add_numbers = number_a + int(number_b) print(add_numbers)
Careful consideration is required while doing casting, as it might lead to loss of data.
In this blog, you learned about Casting in Python. Follow here more information regarding Python.