[英]boolean string not counted in while/if statement in python[3.8]
[英]While statement and boolean OR in Python
y=''
print 'y= nothing'
y = raw_input('-->')
while y!='O' or y!='X':
print 'You have to choose either X or O'
y = raw_input('-->')
print 'Loop exited'
print y
谁能解释为什么上面的代码不能在python中正常运行?
我假设,只要用户输入“ X”或“ O”以外的任何内容,他都会得到消息和输入提示。 但是,只要用户提供“ X”或“ O”,循环就应该退出。 但这不是...你们可以帮忙吗? 我是python的新手...
此错误逻辑流有多种修复方法。 @Aanchal Sharma已经提到了一个and
在while循环中有两个!=
和an and
,如下所示:
while y != 'O' and y != 'X':
一个替代解决方法是使用in
我个人找到更多可读:
while y not in ['X', 'O']:
print 'You have to choose either X or O'
y = raw_input('--> ')
希望这对您有所帮助!
y=''
print 'y= nothing'
y = raw_input('-->')
while (y!='O' and y!='X'):
print 'You have to choose either X or O'
y = raw_input('-->')
print 'Loop exited'
print y
使用“和”条件而不是“或”。 在您的情况下, y
始终等于或等于'O'或等于'X'。 它不能同时等于两个。
执行此操作的另一种方法是使用while True
和break
语句:
while True:
y = raw_input('-->')
if y in ['O', 'X']:
break
print 'You have to choose either X or O'
print 'Loop exited'
print y
例如:
-->a
You have to choose either X or O
-->b
You have to choose either X or O
-->c
You have to choose either X or O
-->O
Loop exited
O
这避免了需要两个输入语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.