A local variable belongs to the function where it is created. Think of it as a little note kept inside one room: code outside that function cannot see it directly. section 3.0
The menu’s private answer
In a coffee-shop menu function, choice and answer are local variables. The function can use them to turn the customer’s number into a drink, but the main program cannot print answer directly. Returning answer passes its value outside, where drink = menu(drinks, ...) stores it in a separate variable. section 3.0 section 5.1
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
Follow choice and answer inside the menu function, then see answer leave through return. section 3.0
Keep these points in mind:
- Define the variable inside the function that needs it. section 3.0
- Use return when the main program needs the value. section 5.1
