Question: On page 70 the author shows an example that illustrates using print() versus return. Use that example to explain in your own words, what NoneType

On page 70 the author shows an example that illustrates using print()On page 70 the author shows an example that illustrates using print() versus return. Use that example to explain in your own words, what NoneType means and why it appears in the error for that function.

CAUTION Statement return versus Function print(). A common mistake is to use the print() function instead of the return statement inside a function. Suppose we had defined our first function f() in this way: def f(x): print(x**2 + 1) It would seem that such an implementation of function f() works fine: >>> f(2) 5 However, when used in an expression, function f() will not work as expected: >>> 3 * f(2) + 1 5 Traceback (most recent call last): File '', line 1, in 3 * f (2) + 1 TypeError: unsupported operand type(s) for *: 'int' and 'NoneType' When evaluating f (2) in the expression 3 * f (2) + 1, the Python interpreter evaluates (i.e., executes) f (2), which prints the value 5. You can actually see this 5 in the line before the "Traceback" error line. Sof() prints the computed value, but it does not return it. This means that f (2) returns nothing and thus evaluates to nothing in an expression. Actually, Python has a name for the nothing" type: It is the 'NoneType' referred to in the error message shown. The error itself is caused by the attempt to multiply an integer value with "nothing." That said, it is perfectly OK to call print() inside a function, as long as the intent is to print rather than return a value

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!