Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

Return Ends the Function

return does two things at once: it gives a value back, and it ends the function immediately. The rest of the function doesn't run:

def add(a, b):
    return a + b
    print("This line never runs.")

print(add(2, 3))

This prints:

5

The line after return never runs, because the function ended one line earlier.

This is handy together with conditions. The following function describes the weather based on the temperature:

def describe_weather(degrees):
    if degrees < 0:
        return "freezing"
    if degrees < 20:
        return "cool"
    return "warm"

print(describe_weather(-5))
print(describe_weather(12))
print(describe_weather(25))

This prints:

freezing
cool
warm

Let's follow the three calls:

  • describe_weather(-5): -5 < 0 is True, so the function returns "freezing" and ends. The second condition is never checked.
  • describe_weather(12): the first condition is False and the second one is True, so the function returns "cool".
  • describe_weather(25): neither condition is True, so the function gets all the way to the last line and returns "warm".

We didn't need any elif or else: once a return runs, the rest of the function is skipped anyway. (With elif and else, the function would work the same.) But the order of the conditions matters, because the first return that runs wins. If the function checked degrees < 20 first, it would return "cool" for -5, since -5 is less than 20 too.

Instructions

  1. 1

    The function ticket_price returns the price of a zoo ticket for a visitor of the given age. For now, it returns 10 for everyone. Above the line return 10, add conditions: children under 6 go free (0), and visitors under 18 pay 5. The program then prints 0, 5 and 10.

  2. 2

    Seniors aged 65 and over pay 5 too. Add a condition for them to the function, and at the end of the program, print ticket_price(70).

Back

7/10

  1. 1. Defining Functions
  2. 2. Calling Functions
  3. 3. Parameters and Arguments
  4. 4. Default Parameter Values
  5. 5. Returning Values
  6. 6. Print or Return?
  7. 7. Return Ends the Function
  8. 8. Local Variables
  9. 9. Functions and Lists
  10. 10. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.