A nested if statement places one conditional inside another. Python checks the outer condition first, then evaluates the inner condition only when the surrounding branch is reached. Indentation shows this structure, so keep it exact. section 4.0
Adding an exit option to a menu
A menu first checks whether the input is allowed. Inside that branch, a nested if checks whether the choice is x or X. If so, it assigns an empty string and exits; otherwise, it selects the numbered menu item. Try entering x at every menu: the resulting order is empty. section 4.0
Listing 4.1 The final version of Erik’s menu
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
while True:
choice = input(prompt)
allowed_answers = []
for a in range(1, len(choices)+1):
allowed_answers.append(str(a))
allowed_answers.append('X')
allowed_answers.append('x')
if choice in allowed_answers:
if choice == 'X' or choice == 'x':
answer = ''
break
else:
answer = choices[int(choice) - 1]
break
else:
print("Enter number from 1 to ", len(choices))
answer = ''
return answer
Inspect the completed Python menu, including the outer allowed-answer check and the inner exit-option check. section 4.0
