[英]Function if only accepts one input
My code is here: http://pastebin.com/bK9SR031 . 我的代码在这里: http : //pastebin.com/bK9SR031 。 I was doing the PygLatin exercise on Codecademy and got carried away, so most of it is... beginner. 我在Codecademy上做了PygLatin练习并且被带走了,所以大部分都是......初学者。
Sorry that it's really long. 对不起,这真的很长。 The problem is that when the [Y/N] questions come up, no matter what I type in it behaves as if I input "yes". 问题是,当[Y / N]问题出现时,无论我输入什么,它都表现得好像输入“是”。
One of the relevant excerpts: 相关摘录之一:
def TryAgain():
repeat = raw_input("\nStart over?[Y/N] ").lower()
if repeat == "y" or "yes" :
print "OK.\n"
PygLatin()
elif repeat == "n" or "no" :
raw_input("\nPress ENTER to exit the English to Pig Latin Translator.")
sys.exit()
else:
TryAgain()
No matter what I input, it prints "OK." 无论我输入什么,都打印“OK”。 and then starts the PygLatin() function again. 然后再次启动PygLatin()函数。
The condition in your first if
statement: 第一个if
语句中的条件:
if repeat == "y" or "yes":
print "OK.\n"
PygLatin()
always evaluates to True
, regardless of the value of repeat
. 无论repeat
的值如何,始终计算结果为True
。 This is because "Yes"
is not an empty string (it's boolean value is True
), so the or
always results in True
. 这是因为"Yes"
不是空字符串(它的布尔值为True
),所以or
总是得到True
。 One way to fix it is with: 修复它的一种方法是:
if repeat == "y" or repeat == "yes":
print "OK.\n"
PygLatin()
another one (as sateesh mentions below) is: 另一个(如下面的sateesh提到)是:
if repeat in ("y","yes"):
print "OK.\n"
PygLatin()
You should also change the else
condition accordingly 您还应该相应地更改else
条件
Also it is better to do if check in below manner: 如果以下方式检查,最好还是这样做:
if repeat in ("y","yes"):
...
elif repeat in ("n","no"):
...
Comparing by keeping all possible values in a tuple (list) makes the code readable. 通过在元组(列表)中保留所有可能的值进行比较使代码可读。 Also if there are more values to be compared with you can create a tuple (or list) to store those values and make comparison against the stored values. 此外,如果有更多值要与之比较,您可以创建一个元组(或列表)来存储这些值并与存储的值进行比较。 Say something like below keeps code more readable: 说下面的内容让代码更具可读性:
acceptance_values = ('y','yes')
...
if repeat in acceptance_values :
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.