Python Fundamentals — Question 17
Back to all questionsQuestion 17
Consider below given two sets of codes, which are nearly identical, along with their execution in Python shell. Notice that first code-fragment after taking input gives error, while second code-fragment does not produce error. Can you tell why ?
(a)
>>> print(num = float(input("value1:")) )
value1:67
TypeError: 'num' is an invalid keyword argument for this function
(b)
>>> print(float(input("valuel:")) )
value1:67
67.0
In part a, the value entered by the user is converted to a float type and passed to the print function by assigning it to a variable named num. It means that we are passing an argument named num to the print function. But print function doesn't accept any argument named num. Hence, we get this error telling us that num is an invalid argument for print function.
In part b, we are converting the value entered by the user to a float type and directly passing it to the print function. Hence, it works correctly and the value gets printed.