Python如何使用用户输入停止循环

时间:2017-10-23 02:45:00

标签: python loops

这可能是一个简单的答案,但我想我还是会问。

我的下面的代码是询问用户的号码,根据提供的答案,将打印与号码对应的等级。

我想通过让用户键入(999)来停止循环(终止程序)。我知道问题出在if userScore >= 90" print ('A')。因此,当用户输入999时,计算机将其视为A.

是否有解决此问题的快捷方式?

(PS我将断点添加到每一行,因为当它们不存在时,输出会不断重复。)

    userScore = float(input('Enter the score or type "999" to quit: '))

    while True:

        try:
            if userScore >= 90:
                print ("You earned an A")
                break


            elif userScore >= 80:
                print ("You earned a B")
                break


            elif userScore >= 70:
                print ("You earned a C")
                break


            elif userScore >= 60:
                print ("You earned a D")
                break


            elif userScore <= 59.9:
                print ("You earned an F")
                break

        except:
            if userScore == '999':
                break
          main()

2 个答案:

答案 0 :(得分:1)

不要使用try除外。尝试除了用于错误处理。这可以使用简单的while循环来处理。

userScore = float(input('Enter the score or type "999" to quit: '))

while userScore!=999:
    if userScore >= 90:
        print ("You earned an A")
        break

    elif userScore >= 80:
        print ("You earned a B")
        break

    elif userScore >= 70:
        print ("You earned a C")
        break

    elif userScore >= 60:
        print ("You earned a D")
        break

    elif userScore <= 59.9:
        print ("You earned an F")
        break
main()  # Why is this even required?

答案 1 :(得分:0)

以下是您要完成的任务。评论中对此进行了解释。

while True:

    #This part gets the user input.  It waits until the user enters a valid number input.
    while True:
        prelim = input('Enter the score or type "999" to quit: ')
        try:
            prelim = int(prelim)
        except:
            print("Please enter a valid input.")
        else:
            #if the input can be converted into a number, then this is our final input value
            userScore = float(prelim)
            break

    #The first thing we should check is if the user wants to exit.  This way it won't print out an answer then exit.
    if userScore == 999:
        break

    if userScore >= 90:
        print ("You earned an A")


    elif userScore >= 80:
        print ("You earned a B")


    elif userScore >= 70:
        print ("You earned a C")


    elif userScore >= 60:
        print ("You earned a D")


    elif userScore <= 59.9:
        print ("You earned an F")