liveBook · Manning

Nested if statement

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

A nested if statement is a conditional statement placed inside the body of another conditional statement.

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

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

How deep it goes
Defines nesting, demonstrates two levels, and emphasizes indentation without developing deeper nesting beyond a brief warning.
Examples
Uses a drinks menu whose x or X choice returns an empty string across several menu prompts.
What it assumes
Assumes familiarity with if statements, menu choices, allowed-answer lists, and basic Python indentation.
What you can do after
Builds a Python menu branch that handles an exit choice before converting numbered input.
How it connects
Connects conditional statements with input validation, lists, functions, and loops.

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.