用户输入的票据

2024-10-01 13:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着运行一个脚本,要求用户为他们最喜欢的运动队。到目前为止,我的情况是:

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

而且,没有定义任何可供选择的团队。救命啊


Tags: 用户脚本inputiselseareteamprint
2条回答

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

You use == when comparing values and is when comparing identities.

您可能希望将代码更改为如下所示:

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.")

输入是一个函数,它要求用户给出答案

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

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

注意 您可能需要raw_input()来获得所需的字符串

记住去掉空白

相关问题 更多 >