我试着运行一个脚本,要求用户为他们最喜欢的运动队。到目前为止,我的情况是:
print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input is "Yankees":
print("Good choice, go Yankees")
elif input is "Knicks":
print("Why...? They are terrible")
elif input is "Jets":
print("They are terrible too...")
else:
print("I have never heard of that team, try another team.")
每当我运行这个脚本时,最后一个“else”函数在用户可以输入任何内容之前接管
而且,没有定义任何可供选择的团队。救命啊
您的主要问题是使用
is
来比较值。正如在这里的问题中所讨论的>String comparison in Python: is vs. ==您可能希望将代码更改为如下所示:
但是,您可能需要考虑将代码放入
while
循环中,这样就可以询问用户问题,直到您的答案被接受为止您还可以考虑通过强制将比较值转换为小写字母来添加一些人为错误容忍度。这样,只要团队名称拼写正确,就可以准确地进行比较
例如,请参见下面的代码:
输入是一个函数,它要求用户给出答案
您需要调用它并将返回值赋给某个变量
然后检查该变量,而不是
input
本身注意 您可能需要
raw_input()
来获得所需的字符串记住去掉空白
相关问题 更多 >
编程相关推荐