A function is a named piece of code that performs a job you may want again. Call it by writing its name with parentheses. Put information it needs—arguments—inside the parentheses, and it can print an output or return one to the rest of the program. section 1.4 section 3.1
Imagine a coffee-shop program that displays three similar menus: drinks, flavors, and toppings. Rather than copy the same loop, printing, and input steps three times, collect the repeating work in one menu() function. Keep the changing parts—choices, title, and prompt—as arguments. section 3.0
Create and use a function in small steps:
- Spot repeated code. Ask which instructions stay the same and which values change. section 3.0
- Define the reusable job with def, a function name, parentheses, and a colon. section 3.0 section 7.3
- Indent the instructions that belong to the function. section 3.0
- Call the function with arguments. Each call can use different lists, titles, and prompts. section 3.0
- Use return when the caller needs a result, such as the customer’s selected item or order dictionary. section 3.0 section 7.0
One menu, three choices
The menu() function prints numbered choices, asks for a selection, finds the selected item, and returns it. A program can call it once for drinks, again for flavors, and again for toppings. Default arguments let a call such as menu(drinks) use a standard title and prompt, while another call can supply custom text. section 3.0
Listing 3.1 The full menu program with a function
def menu(choices, title="Erik's Menu", prompt="Choose your item: "):
print(title)
print(len(title) * "-")
i = 1
for c in choices:
print(i, c)
i = i + 1
choice = input(prompt)
answer = choices[int(choice) - 1]
return answer
drinks = ["chocolate", "coffee", "decaf"]
flavors = ["caramel", "vanilla", "peppermint", "raspberry", "plain"]
toppings = ["chocolate", "cinnamon", "caramel"]
drink = menu(drinks)
flavor = menu(flavors, "Erik's flavors", "Choose your flavor: ")
topping = menu(toppings, "Erik's toppings", "Choose your topping: ")
print("Here is your order: ")
print("Main product: ", drink)
print("Flavor: ", flavor)
print("Topping: ", topping)
print("Thanks for your order!")
Browse a complete menu program: its function accepts choices, title, and prompt; returns a selection; and is reused for three parts of one order. section 3.0
Functions also help plan a larger program. Start with big jobs such as get_order(), print_order(), and save_order(), even if their first versions are simple placeholders. The main menu can then be tested while each job is filled in separately. section 6.0 section 7.0
Before calling a function, define it. When a function builds an order, create the order dictionary before adding values to it; otherwise Python reports that the name is not defined. Testing small calls interactively can make these checks quick. section 7.0 section 7.3



















