[英]Why does this while loop not break?
如果输入h,l或c,则此循环不会中断:
x = input('enter h,l, or c')
while (x != 'c') or (x != 'h') or (x != 'l'):
print('Sorry I didn't understand. Please enter h,l, or c')
x = input("enter h,l, or c")
我想要的可以通过这种方式解决:
x = input("enter h,l, or c")
while True:
if x == 'c' or x == 'h' or x == 'l':
break
else:
print('Sorry I didnt understand. Please enter h,l, or c')
x = input("enter h,l, or c")
第一段代码有什么不正确的地方? X不会在一开始就被评估吗?
看你的情况:
while (x != 'c') or (x != 'h') or (x != 'l'):
考虑输入字符为c
。 第一个条件为False
,但其他两个条件为True
。 F或T或T为True
。
您需要and
连接器处于您的状况。 更好的是,尝试
while not x in ['h', 'l', 'c']:
您应该使用and
条件,而不是or
。 也就是说,如果它是可接受的字母之一,则将(x != 'c')
, (x != 'h')
和(x != 'h')
评估为假。
x = input('enter h,l, or c')
while (x != 'c') and (x != 'h') and (x != 'l'):
print("Sorry I didn't understand. Please enter h,l, or c")
x = input("enter h,l, or c")
由于逻辑运算错误。
不是(A或B)
这个逻辑等于
(不是A)和(不是B)
所以第一个代码应该是
x = input('enter h,l, or c')
while (x != 'c') and (x != 'h') and (x != 'l'):
print("Sorry I didn't understand. Please enter h,l, or c")
x = input("enter h,l, or c")
让我们从声明false or true
评估为true的语句开始。 因此,如果x
为c
则(x != 'c')
将为false ,但是第二种情况(x != 'h')
将为true ,根据我们的第一个陈述,整个or
表达式的计算结果为true,因此您的循环将永远不会退出。 相反,您需要做的是:
x = input('enter h,l, or c')
while not ((x == 'c') or (x == 'h') or (x == 'l')):
print("Sorry I didn't understand. Please enter h,l, or c")
x = input("enter h,l, or c")
您的while循环将始终评估为True
0 x = input('enter h,l, or c')
1 while (x != 'c') or (x != 'h') or (x != 'l'):
2 print('Sorry I didn't understand. Please enter h,l, or c')
3 x = input("enter h,l, or c")
您的代码已变成这样:
0 x = input('enter h,l, or c')
1 while True:
2 print('Sorry I didn't understand. Please enter h,l, or c')
3 x = input("enter h,l, or c")
让我们解释一下。
输入场景:
一种。 如果输入为“ z”,则z不等于任何字母,因此在所有条件下均变为True
。 这意味着任何不是'h','l','c'之一的输入都将求值为True
。
b。 如果输入为“ h”,则h既不等于l也不等于c。 结果为True OR False OR True
场景,并且显然变为True
。 因此,如果您的输入也是指定的任何字母,则它将是True
因为它不等于条件中的其他字母,并且OR
条件只需要一个True
将条件求值为True
。
因此,您当前的代码将始终评估为True,并且循环将无限运行。 您需要使用AND
而不是OR
,使用发布的第二个代码,或者可以使用递归。
推荐选项:
x = input('enter h,l, or c')
while (x != 'c') and (x != 'h') and (x != 'l'):
print("Sorry I didn't understand. Please enter h,l, or c")
x = input("enter h,l, or c")
def checker():
x = input("enter h,l, or c")
if (x != 'c') and (x != 'h') and (x != 'l'):
print("Sorry I didn't understand. Please enter h,l, or c")
checker()
checker()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.