liveBook · Manning

Return statement

As explained in A Pythonic Adventure: From Python basics to a working web app

A return statement exits a function and optionally supplies a result to its caller.

A return statement finishes a function and sends a value back to the code that called it. Variables created inside the function stay there, so returning a value lets the main program use it. section 3.0

A coffee-shop choice

A menu function turns the user’s number into an item, then returns that item: return answer. The main program stores the result with choice = menu(drinks, ...) and can print coffee, vanilla, or another selection. section 3.0

def menu(choices, title, prompt):
    print(title)
    print("--------------------------------")
    i = 1
    for c in choices:
        print(i, c)
        i = i + 1
    choice = input(prompt)
    answer = choices[int(choice) - 1]
 
    return answer

See the complete menu function: it reads input, converts the selection, retrieves the chosen list item, and returns answer. section 3.0

Returning the wrong value can produce a misleading result. Returning {} gives the caller an empty dictionary; returning order passes back the customer’s actual name and order data. section 7.0

YOUR TURN

  • Write a get_order() function, collect a customer’s name, return the order dictionary, and test the result in the main program. section 7.0

How A Pythonic Adventure: From Python basics to a working web app covers it

How deep it goes
Explains function scope and returned values through complete menu and order examples, without exploring return control flow beyond these cases.
Examples
Uses a coffee-shop menu that returns a chosen item and an order function that returns a customer dictionary.
What it assumes
Assumes basic functions, variables, lists, input, and dictionaries while teaching function scope and value passing through examples.
What you can do after
Build it from scratch by writing functions that return menu selections or collected order data to calling code.
How it connects
Links return statements with functions, variable scope, lists, input, and dictionaries.

Also explained in

Compare how 5 books explain return statement →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of A Pythonic Adventure: From Python basics to a working web app. The section links point to the parts of the book it draws on.