Computer Applications
Aashna has written following code :
a = 5
b = '5'
c = "5"
d = 5.0
(a) What are the data types of a, b, c, d ?
(b) Are a, b, c, d storing exactly the same values ? Why/why not ?
(c) What will be the output of following code based on values of a, b, c and d ?
print a == b
print b == c
print a == d
(d) Discuss the reasons behind the output of part (c).
Python Funda
1 Like
Answer
(a) The data types are as follows:
| a | int |
| b | String |
| c | String |
| d | float |
(b) No, a, b, c, and d are not storing exactly the same values. While the values of b and c look like integers (numerical 5), they are enclosed within quotes, making them strings. On the other hand, a is an integer number, and d is a floating-point number with a decimal point.
So, although they all represent the number 5, they are stored as different data types.
(c) The output of the following code will be :
False
True
True
(d) The reasons behind the output of part c are as follows:
1. print a == b
This comparison checks if the value of a is equal to the value of b. Even though the values of a and b are both 5, they are not of the same data type (int vs. str). Python strictly checks for both value and type equality in this case, so the comparison evaluates to False.
2. print b == c
This comparison checks if the value of b is equal to the value of c. Since both b and c are strings with the same content ("5"), the comparison evaluates to True.
3. print a == d
This comparison checks if the value of a is equal to the value of d. Although they have different data types (int vs. float), their numerical values are the same (both represent 5). Python performs type coercion in this case and considers them equal, so the comparison evaluates to True.
Answered By
1 Like
Related Questions
What is meant by a floating-point literal in Python ? How many ways can a floating literal be represented into ?
What are the two Boolean literals in Python ?
What kind of program elements are these: 'a', 4.38925, "a", main( ) ?
Anant has written following expressions in Python 2.7 :
a = - 4 % 1.5 b = - 4 // 1.5 c = 4.0 / 5 d = 4 / 5(a) Find out the values stored by a, b, c and d.
(b) What are the datatypes of a, b, c and d ?
(c) Why are the values of c and d not the same.