【问题标题】:While Loop Using Nor Logic使用 Nor 逻辑的 While 循环
【发布时间】:2019-05-20 19:18:20
【问题描述】:

我正在尝试在 python 中创建一个控制台菜单,其中列出了菜单中的选项 1 或 2。选择数字将打开下一个菜单。

我决定尝试使用while 循环来显示菜单,直到选择了正确的数字,但我遇到了逻辑问题。

我想使用 NOR 逻辑,如果一个或两个值都为真,它返回假,循环应该在假时中断,但是即使我输入 1 或 2,循环也会继续循环。

我知道我可以使用while True 并且只使用break,这是我通常的做法,我只是尝试使用逻辑以不同的方式实现它。

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

【问题讨论】:

  • not Selection == 1 or Selection == 2 not (Selection == 1 or Selection == 2) 相同。您的意思可能是后者。

标签: python while-loop logic nor


【解决方案1】:

not 的优先级高于or;您的尝试被解析为

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

你要么需要明确的括号

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

或者not的两种用法(以及对应的切换到and):

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

虽然最易读的版本可能涉及切换到not in

while Selection not in (1,2):

【讨论】:

  • 我没有意识到更高的优先级。切换到:while not (Selection == "1" or Selection == "2"):工作,似乎输入数字被保存为字符串而不是 int,所以我不得不使用引号
【解决方案2】:

你想要的 NOR 要么是

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

或者

Selection != 1 and Selection != 2

上面两个表达式等价,但不等价

not Selection == 1 or Selection == 2

这相当于

Selection != 1 or Selection == 2

因此

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-08
    • 2015-12-17
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多