Python while 循环未按预期工作

问题描述 投票:0回答:4

当我在输入中输入“no”时,我期望它向“x”添加 1,从而结束循环,但发生的情况是它忽略它并且不添加 1 x。这是代码。

x = 1
password = ""

while x == 1:        
    # imagine there is some code here which works

    ans1 = input("\n\nTest a new password? ")
    ans1 = ans1.upper()

    print(ans1)

    if ans1 == ("Y" or "YES"):
        x = x
    elif ans1 == ("N" or "NO"):
        x = x + 10

    print(x)

这是底部的 if/elif 语句不起作用。它应该继续再次请求输入,直到用户说“否”,但这不起作用。

python loops while-loop
4个回答
6
投票

你应该使用 or 那样。

if ans1 == ("Y" or "YES"):

可以替换为:

if ans1 == "Y" or ans1 == "YES": 

或者:

if ans1 in ("Y", "YES"): 

该错误来自

or
运算符的定义。当您执行“Y”或“YES”时,它将返回“Y”,因为
A or B
被定义为如果 A 不为假则返回 A。这里,A 是“Y”,它不是 False 值。因此,它将返回 A="Y"。如果您执行
if a == ("Y" or "YES"):
,il 将相当于
if a == "Y":
。好吧,这有点棘手,但这就是 python 的工作原理。

而且,你的代码很奇怪。退出这样的循环是一个非常坏的习惯。通常,当我们想要离开循环时,我们会放置一个布尔值“looping”,并将其设置为 false。

这是我如何做你的循环:

looping = True 
password = "" 

while looping: 

    ans1 = input("\n\nTest a new password? ")

    if ans1.upper() in ("NO", "N"): 
        looping = False

您还可以使用无限循环的结构 (

while True:
)。然后,调用指令
break
退出循环。


2
投票

您还可以使用“break”或“exit”退出循环或程序。通常,最好使用在意外情况下运行良好的较大条件 (x<=0 or ans1 isn't YES rather than x==0 or ans1 is YES or ans1 is NO).

while True:
  # Code
  if ans1 not in ["Y", "YES"]:
    break # or exit

那么您将不会有未定义的行为,并且需要处理的条件也更少:如果不是“YES”或“Y”,则程序退出。


1
投票

嗯,这一行有问题: ans1 ==(“Y”或“是”)

与此行不相似:

ans1 == "Y" or ans1 == "YES"

第二个是对的,第一个叫

null coalescing
。那不是你想要的。基本上,如果 x 不为空,则
x or y
返回 x,否则返回 y。

所以基本上你只需检查 ans1 是否是“Y”(而不是“YES”)

您可以通过以下方式检查习语列表中是否包含您的习语:

if ans1 in ["Y", "YES"]:

您可以继续向该列表添加任意数量的值。


0
投票

您可以使用 list 和 in 语句:

x = 1
password = ""

while x == 1:        
# imagine there is some code here which works

 ans1 = input("\n\nTest a new password? ")
 ans1 = ans1.upper()

 print(ans1)

 if ans1 in ["Y","YES"]:
    x = x
 elif ans1 in ["N","NO"]:
    x = x + 10

print(x)

这可确保代码正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.