Exit while loop by user hitting ENTER key

前端 未结 14 1883
难免孤独
难免孤独 2020-12-08 23:01

I am a python newbie and have been asked to carry out some exercises using while and for loops. I have been asked to make a program loop until exit is requested by the user

14条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 00:00

    Here is the best and simplest answer. Use try and except calls.

    x = randint(1,9)
    guess = -1
    
    print "Guess the number below 10:"
    while guess != x:
        try:
            guess = int(raw_input("Guess: "))
    
            if guess < x:
                print "Guess higher."
            elif guess > x:
                print "Guess lower."
            else:
                print "Correct."
        except:
            print "You did not put any number."
    

提交回复
热议问题