Should my function use print or return?

Saharshjain, make sure to use the </> icon to post your code properly formatted, so that we can read it easily, and it is actually Python code. I need to guess a bit about the indentation. Is this it?

def mult_x_add_y(number, x, y):
    print(number*x + y)
result = mult_x_add_y(1, 3, 1)
print(result)

Let us follow the code. The Python interpreter goes down the left-most indentation level.
First it sees the function declaration def mult_x_add_y():. It puts the function in memory, keeping the function name for reference.

Next, it gets to the line result = mult_x_add_y(1, 3, 1) That is an assignment statement (because it has the assignment operator, =). Every assignment statement says, "first, evaluate the expression on the right, then assign the returned value to the variable on the left.

So, the expression on the right is the original function, along with the arguments (1, 3, 1). The function is called, and it is executed: It has one line, print(number*x + y) and we know because of the order of the arguments that number = 1, x = 3, and y = 1. The expression within the print() function parentheses evaluates to 4, so you see 4 printed on your screen.

Now, here is the key: The function has executed, and the next step is to assign its returned value to the variable result. What is the returned value?

==> There is no returned value specified for this function, and in Python, if a function has no return value specifies, it returns None.

So the value None is assigned to the variable result.

The next (and final) line is print(result). When this is executed, None is printed, onscreen, as you see.

Bottom line:

  • We print() values that we want to see onscreen
  • We return values that Python needs to use, possibly to assign to a variable, or pass to another function.
44 Likes