variable.
number_int = 10 number_float = 2.567 result = number_int * number_float print(result) print(type(result))
What should be the data type of “result”? Python uses implicit typecasting to determine the data type of the variable “result”. Here, we are multiplying one integer with a float. The result will be converted into float automatically. So, the above program will print the following output:
25.67 <class 'float'>
What is explicit typecasting?
In the case of explicit typecasting, a programmer needs to do the typecasting explicitly. For example, let’s say there is one boolean variable “flag”. So, the flag can contain either True or False. Let’s say later we want to convert the value of the flag to 0 or 1. We can do so easily using explicit typecasting in the following way:
flag = True number = int(flag) print(number) print(type(number))
The output will be:
1 <class 'int'>
Here, we are converting a boolean value into an integer using int(flag).
Similarly, let’s say we have a variable c that contains a character. We want to add an integer with the character and then print the new character. Here also we will need explicit typecasting.
c = 'a' n = 3 new_c = chr(ord(c) + n) print(new_c)
Here, we are using ord(c) to get the Unicode code of the character ‘a’. In other words, the ord(‘a’) function returns the integer that represents the character ‘a’. So, here, we are first getting the integer representation of the character contained in the variable c. Then, we are adding an integer number to it. And then, we are using explicit typecasting to convert the resultant integer into a character and print the character. The output of the above program will be:
d








































0 Comments