Setting a variable to print?

Could you tell me why this causes an error:

def lots_of_math (a, b, c, d):
first = print (a + b)
second = print (c - d)
third = print (first * second)
return third % a

I don’t really see the problem here but I do get the error message:

“Traceback (most recent call last):
File “script.py”, line 9, in
print(lots_of_math(1, 2, 3, 4))
File “script.py”, line 6, in lots_of_math
third = print (first * second)
TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘NoneType’”

First first: To post code, please use the </> icon in the menu bar that appears at the top of the text box when you open it to type.

Doesn’t this look better?

def lots_of_math (a, b, c, d):
    first = print (a + b)
    second = print (c - d)
    third = print (first * second)
    return third % a

“Traceback (most recent call last):
File “script.py”, line 9, in 
print(lots_of_math(1, 2, 3, 4))
File “script.py”, line 6, in lots_of_math
third = print (first * second)
TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘NoneType’”

Second “first”: Your variables first and second are the return values from print(), which is a function that does the following:

  1. Evaluates the expression within its parentheses
  2. Sends the resulting value as a string to the default i/o device, usually your screen
  3. Returns the value None.

In other words, print() prints a value, but returns None, so when you code
first = print (a + b)

print() evaluates the expression a + b, prints that value to the screen, and then returns None, which is the value assigned to the variable first. Likewise with second. You cannot do None * None, hence the error message

TypeError: unsupported operand type(s) for *: ‘NoneType’ and ‘NoneType’”