A function declaration defines a named operation before the program uses it. In Python, write def, the function name, parentheses for arguments, a colon, and an indented body. section 3.0 section 7.3
A declaration can gather repeated menu work into one small operation:
- Pass changing information such as choices, a title, and an input prompt as arguments. section 3.0
- Indent the statements that belong to the function, including printing, looping, and input. section 3.0
- Return the selected item so callers can store and use the result. section 3.0
A reusable coffee-shop menu
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 Calling menu with drinks, flavors, and toppings uses the same declaration for each list. section 3.0
drinks = ["chocolate", "coffee", "decaf"]
flavors = ["caramel", "vanilla", "peppermint", "raspberry", "plain"]
toppings = ["chocolate", "cinnamon", "caramel"]
print("Erik's Coffee Shop drinks")
print("-------------------------")
i = 1
for d in drinks:
print(i, d)
i = i + 1
drink = input("Choose your drink: ")
print("Erik's Coffee Shop flavors")
print("--------------------------")
i = 1
for f in flavors:
print(i, f)
i = i + 1
flavor = input("Choose your flavor: ")
print("Erik's Coffee Shop toppings")
print("---------------------------")
i = 1
for t in toppings:
print(i, t)
i = i + 1
topping = input("Choose your topping: ")
print("Here is your order: ")
print("Main product: ", drinks[int(drink) - 1])
print("Flavor: ", flavors[int(flavor) - 1])
print("Topping: ", toppings[int(topping) - 1])
print("Thanks for your order!")
Compare the repeated menu code with the function-based version to see how one declaration replaces duplicated loops and prompts. section 3.0





