【问题标题】:How do I close a while loop and then execute another block of code? While loop is always repeating如何关闭一个while循环然后执行另一个代码块?虽然循环总是重复
【发布时间】:2013-11-21 23:12:32
【问题描述】:

刚开始学习 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,而不是打印高分时,循环会再次继续,并且对于两个相同。请帮忙。

【问题讨论】:

    标签: python loops for-loop while-loop


    【解决方案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)
    

    【讨论】:

    • 感谢阿拉丁,我看到缩进在 python 中是一个强大的东西 :)
    • 缩进是python中的一切;)
    【解决方案2】:

    您对循环进行了编码,以便它在choice != "0" 时继续运行,并且只有在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.
    

    【讨论】:

    • 我不确定我是否遵循,例如,假设用户输入“1”,然后打印的是高分,然后将最近的分数放入程序中(假设有人已经输入了分数),然后它会再次打印 High Scores Keeper 字符串吗?
    猜你喜欢
    • 2016-04-08
    • 2017-11-16
    • 2023-03-03
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-26
    相关资源
    最近更新 更多