Returning values

Functions, lesson 2 of 6

🧩 Functions, lesson 2 of 6

Returning values

Send results back with return, and avoid the print-vs-return trap.

10 min

2 exercises

2 quizzes

0/4 solved

Getting Python ready… examples can run in a moment.

return sends a value back to whoever called the function. The call itself then becomes that value, so you can store it, print it or use it in a calculation. return also ends the function immediately.

Example

Add tax

Change the tax rate to 1.08 and run it again.

print shows, return gives back. A function that only prints hands back nothing, which in Python is the special value None.

Example

The None surprise

double_print shows 10 on screen, but a ends up as None.

Quiz

What does this print?

Example

Letter grades (early return)

Each return exits right away, so no elif is needed. Add a "D" for scores of 60 and up.

Example

Return two values

Returning a, b actually returns a tuple, which you can unpack.

Quiz

What does this print?

Exercise

Temperature converter

Write two functions that return (not print) the converted temperature:

  • c_to_f(celsius): Fahrenheit is celsius * 9 / 5 + 32
  • f_to_c(fahrenheit): Celsius is (fahrenheit - 32) * 5 / 9
Exercise

Leap year checker

Write is_leap(year) that returns True for leap years and False otherwise. The rule:

  • divisible by 4 → leap year,
  • except years divisible by 100 → not leap,
  • except years divisible by 400 → leap after all.

So 2024 and 2000 are leap years; 2023 and 1900 are not.