Search code examples
pythonwhile-looplogicnor

While Loop Using Nor Logic


I'm trying to create a console menu in python where the options in the menu are listed 1 or 2. The selection of the number will open the next menu.

I decided to try and use a while loop to display the menu until the right number is selected, but I'm having an issue with the logic.

I want to use NOR logic as in if one or both values are true it returns false and the loop should break when false, however the loop just keeps looping even when I enter either 1 or 2.

I know I could use while True and just use break which is how I normally do it, I was just trying to achieve it a different way using logic.

while not Selection == 1 or Selection == 2:
    Menus.Main_Menu()
    Selection = input("Enter a number: ")

Solution

  • not has higher precedence than or; your attempt is parsed as

    while (not Selection == 1) or Selection == 2:
    

    You either need explicit parentheses

    while not (Selection == 1 or Selection == 2):
    

    or two uses of not (and the corresponding switch to and):

    while not Selection == 1 and not Selection == 2:
    # while Selection != 1 and Selection != 2:
    

    The most readable version though would probably involve switching to not in:

    while Selection not in (1,2):