Python: 为什么我的内部嵌套 while 循环继续无限期地执行

Python: Why does my inner-nested while-loop continue to execute indefinitely

Python 3.4.3

我正在尝试使用 Python 和 turtle 创建一个交互式绘图程序。我的程序 运行s 首先要求用户指定形状边的长度。如果长度大于零,程序将开始执行。

我希望程序继续 运行ning 并继续向用户询问信息,直到用户输入边长小于或等于零为止,此时该程序将退出。因此,我对程序使用“while-loop”运行,并向用户询问具体细节。

我希望用户只能请求以下三种形状之一;八角形、七角形或六角形。如果用户输入除此以外的任何内容,我希望程序要求用户再次指定他们选择的形状。

因此,我有如下代码:

import turtle
lineLength = float(input("What length line would you like? "))

while lineLength > 0 :
    print("You have choosen to draw a shape, please enter specifics:")
    penColor = input("Please choose a pen color: ")
    shape = input("which shape would you like to draw? ")

    while shape.lower() != "octagon".lower() or shape.lower() !=
    "heptagon".lower() or shape.lower() != "hexagon".lower() :
        print("You have to select a shape from the specified list.")
        shape = input("What shape would you like to draw: ")

输出: 实际输出是代码将 运行 无限期地 "You have to select a shape from the specified list. What shape would you like to draw: ";无论用户的输入如何。

预期输出: 我的目标和我的期望是,一旦用户输入八边形、七边形或六边形,内部 while 循环就会退出。事实上,我不明白为什么如果用户选择这三种形状中的一种,因为 while 循环的条件不满足,为什么内部 while 循环应该 运行。

您需要使用 and,而不是 or

如果你考虑一下,你的循环永远不可能结束,因为无论形状是什么,它总是不会同时是其他形状名称。即 'octagon' 不等于 'heptagon',因此它将继续循环。如果您将其更改为 and,它只会在形状不等于其中任何一个时循环,这正是您想要的。 De Morgan's laws 阅读以更好地理解这种逻辑是一件好事。

更简洁的方法是使用 not in:

while shape.lower() not in ["octagon", "heptagon", "hexagon"] :
    print("You have to select a shape from the specified list.")
    shape = input("What shape would you like to draw: ")

当至少一个参数为真时,或条件为真

当所有参数都为 TRUE 时,AND 条件为 TRUE

所以,可能的方法是,

  • (形状==八边形)或(形状==七边形)或(形状==六边形)
  • (形状!=八角形)AND(形状!=七边形)AND(形状!=六角形)