Skip to main content

Unit 2 · Python mode... Activate! · Lesson 17 of 57

Behind the Scenes

Behind the scenes

Okay, here's what happened.

return doesn't show anything on the screen. Ever.

Instead, it does the teleportation trick, but behind the scenes. When Python hits return, it takes the value and teleports it back to wherever the function was called.

So when Python runs this line:

add(2, 3)

the 5 gets teleported right back into that spot, and the line basically turns into:

5

Remember typing pi on a line all by itself in Magical Mayhem? Totally valid code, but Python didn't do anything with it, because you didn't tell it to do anything!

Same thing here. The 5 showed up, but nobody told Python to show it to you.

So how do we see it?

Tell Python what to do with it! Either print it directly:

print(add(2, 3))

or teleport it into a variable first, and print that:

answer = add(2, 3)
print(answer)

Both work! The second one is nice because now you have answer saved, and you can use it again later.

Make the program actually show the 5!

Don't touch the add function, just change the last line.

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.

Why not just print inside the function?

Good question! (I'm pretending you asked.)

If return is so sneaky, why not just put the print inside the function, so it always shows up?

Let's try it. Here's a function that prints instead of returning:

Run this one. Look closely at both lines in the console.

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.

Question

Answer it in the lesson and it is checked as soon as you send it. 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.