用户输入的脚本

时间:2015-02-12 01:33:19

标签: python python-3.x

我正在尝试运行一个脚本,询问用户最喜欢的运动队。这就是我到目前为止所做的:

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”函数将在用户输入任何内容之前接管。

此外,没有一个团队可供选择。帮助

2 个答案:

答案 0 :(得分:3)

输入是一个询问用户答案的​​功能。

您需要调用它并将返回值分配给某个变量。

然后检查该变量,而不是input本身。

注意 你可能希望raw_input()代替你想要的字符串。

请记住剥去空白。

答案 1 :(得分:1)

您的主要问题是您使用is来比较值。正如在这里的问题中所讨论的那样 - > String comparison in Python: is vs. ==

  

比较值时使用==,比较身份时使用is

您可能希望将代码更改为:

print("Who is your favorite sports team: Yankees, Knicks, or Jets?")
if input == "Yankees":
    print("Good choice, go Yankees")
elif input == "Knicks":
    print("Why...? They are terrible")
elif input == "Jets":
    print("They are terrible too...")
else:
    print("I have never heard of that team, try another team.")

但是,您可能需要考虑将代码放入while循环中,以便在用您接受的答案回答问题之前询问用户问题。

您可能还需要考虑通过将比较值强制为小写字母来添加一些人为错误容差。这样,只要团队名称拼写正确,就可以准确地进行比较。

例如,请参阅以下代码:

while True: #This means that the loop will continue until a "break"
    answer = input("Who is your favorite sports team: Yankees, Knicks, or Jets? ").lower() 
#the .lower() is where the input is made lowercase
    if answer == "yankees":
        print("Good choice, go Yankees")
        break
    elif answer == "knicks":
        print("Why...? They are terrible")
        break
    elif answer == "jets":
        print("They are terrible too...")
        break
    else:
        print("I have never heard of that team, try another team.")