3

开始学习 Python,所以如果这个问题看起来很明显,请多多包涵。我正在尝试创建一个高分程序,其中该程序将使用列表方法来创建和维护计算机游戏的用户最佳分数列表。然而,发生的事情是,虽然我根据用户输入编写了代码,但 while 循环继续执行并忽略用户输入。请查看下面的代码,希望能回答我做错了什么。提前致谢。

scores =[]
choice = None

while choice != "0":
    print """"High Scores Keeper
    0 - Exit
    1 -Show Scores
    2 - Add A score
    3- Delete a score.
    4- Sort Scores"""
    choice = raw_input("Choice:")
    print 


    if choice == "0":
        print "Good Bye"

    elif choice == "1":
        print "High Scores"
        for score in scores:
            print score

    elif choice == "2":
        score = int(raw_input("What score did you get?:  "))
        scores.append(score) 

例如,当我执行循环并选择 1,而不是打印高分时,循环会再次继续,并且两个相同。请帮忙。

4

2 回答 2

1

您对循环进行了编码,使其在 while 中继续运行,choice != "0"并且仅在 if 时退出循环choice == "0"。如果您想跳出循环,则"1"需要一个与此相对应的循环条件:

while choice != "0" and chioce != "1" and choice != "2" and ...

或者你可以用更简洁的方式来写它:

while 0 <= int(choice) and int(choice) <= 4:

while choice not in ["0", "1", "2", "3", "4", "5"]:

#or something like that.
于 2013-11-09T23:44:56.003 回答
1
scores =[]
choice = None

while choice != "0":
    print """High Scores Keeper
    0- Exit
    1- Show Scores
    2- Add A score
    3- Delete a score.
    4- Sort Scores"""
    choice = raw_input("Choice:")
    if choice == "0":
        print "Good Bye"
    elif choice == "1":
        print "High Scores"
        for score in scores:
            print score
    elif choice == "2":
        score = int(raw_input("What score did you get?:  "))
        scores.append(score)
于 2013-11-09T23:47:38.240 回答