Amzo
Amzo

Reputation: 3

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: ")

Upvotes: 0

Views: 137

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114488

The NOR you want is either

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

or alternatively

Selection != 1 and Selection != 2

The two expressions above are equivalent to each other, but not to

not Selection == 1 or Selection == 2

This is equivalent to

Selection != 1 or Selection == 2

and thus to

not (Selection == 1 and Selection != 2)

Upvotes: 0

chepner
chepner

Reputation: 532093

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):

Upvotes: 0

Related Questions