Unit 2 · Python mode... Activate! · Lesson 18 of 57
Nothing to See Here
Nothing to see here
So the first line said 5, and the second line said... None?
Here's what happened, line by line:
add_and_print(2, 3)runs, and theprintinside it shows5on the screen. So far so good!- But the function never used
return, so nothing got teleported back. - So
totalgot... nothing. And in Python, "nothing" has a name:None. print(total)shows you that nothing.None.
The 5 went to the screen, but it never came back to the code.
print vs return
Here's the whole lesson in two lines:
printshows a value to you, on the screen. The code never gets it.returnsends a value back to the code, behind the scenes. You never see it (unless you print it).
It's kind of like DoorDash! print is the restaurant texting you a picture of your burger. Cool, you can see it, but you're still hungry. return is the driver actually handing you the bag. Now you can eat it, share it, or save it for later.
If Alex was a DoorDash driver, he'd send the picture then eat it himself
Most of the time, you want return. Your functions should hand back their answers, and then you decide what to do with them.
Amer wants a function that doubles numbers. (He's trying to double his savings. It's not working.)
- Make a function called
doublethat takes one number and returns it times 2. (*means times!) - On the last line, print
double(21).
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.