Description: This in-class question demonstrates the differences between Print and Return statements in function construction in Python.
Instructor: Dr. Ana Bell
The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To make a donation or view additional materials from hundreds of MIT courses, visit MIT OpenCourseWare at ocw.mit.edu.
ANA BELL: I have two functions here. One is add, and one is multiply. The add function returns the sum of x plus y. And the multiply function just prints the value of x times y, but doesn't return the value. Instead, it's going to implicitly return none because we don't have any return statement inside mult.
So there are four lines here. And the question was how many total lines of output will show up if you run the code? OK, so how many lines in the console show up? So when I do first add 1, 2, it's going to go inside this function here and say-- it says x is 1, y is 2, and return 3. So I'm replacing this line with 3. But notice I'm never printing it out. So this line of code will not print out anything.
Instead, the next line is if I print add 2 plus 3, then I'm going to get 5. And I'm going to print that out. So that's one thing I'm printing out. The next line says multiply 3 and 4. So I'm going to go inside my mult function and say, x is 3, y is 4. So I'm going to print 12 because 3 times 4 is 12. So that's another thing that gets printed out.
And I'm not doing anything with the output-- or sorry, I'm not doing anything with the return from mult. So that line is done. And the last one is the trickiest and it says print mult 4 and 5. So first I'm going to go in here. X is 4, y is 5. And I'm printing 20. So that's another print. And the return of this function is going to be none, right? And the main thing here is I'm going to print at the return of this function. So I'm also going to print out none. So that's another one. So in total, I'm going to have four different things printed out, the last one being this none.