Exit while loop by user hitting ENTER key

前端 未结 14 1849
难免孤独
难免孤独 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条回答
  • 2020-12-08 23:56

    Here's a solution (resembling the original) that works:

    User = raw_input('Enter <Carriage return> only to exit: ')
    while True:
        #Run my program
        print 'In the loop, User=%r' % (User, )
    
        # Check if the user asked to terminate the loop.
        if User == '':
            break
    
        # Give the user another chance to exit.
        User = raw_input('Enter <Carriage return> only to exit: ')
    

    Note that the code in the original question has several issues:

    1. The if/else is outside the while loop, so the loop will run forever.
    2. The else is missing a colon.
    3. In the else clause, there's a double-equal instead of equal. This doesn't perform an assignment, it is a useless comparison expression.
    4. It doesn't need the running variable, since the if clause performs a break.
    0 讨论(0)
  • 2020-12-08 23:57
    if repr(User) == repr(''):
        break
    
    0 讨论(0)
  • 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."
    
    0 讨论(0)
  • 2020-12-09 00:01

    You are nearly there. the easiest way to get this done would be to search for an empty variable, which is what you get when pressing enter at an input request. My code below is 3.5

    running = 1
    while running == 1:
    
        user = input(str('Enter <Carriage return> only to exit: '))
    
        if user == '':
            running = 0
        else:
            print('You had one job...')
    
    0 讨论(0)
  • 2020-12-09 00:02

    Use a print statement to see what raw_input returns when you hit enter. Then change your test to compare to that.

    0 讨论(0)
  • 2020-12-09 00:05

    I ran into this page while (no pun) looking for something else. Here is what I use:

    while True:
        i = input("Enter text (or Enter to quit): ")
        if not i:
            break
        print("Your input:", i)
    print("While loop has exited")
    
    0 讨论(0)
提交回复
热议问题