Exit while loop by user hitting ENTER key

前端 未结 14 1884
难免孤独
难免孤独 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  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  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.

提交回复
热议问题