Exit while loop by user hitting ENTER key

前端 未结 14 1848
难免孤独
难免孤独 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-09 00:06
    user_input=input("ENTER SOME POSITIVE INTEGER : ")
    if((not user_input) or (int(user_input)<=0)):    
       print("ENTER SOME POSITIVE INTEGER GREATER THAN ZERO") #print some info
       import sys        #import
       sys.exit(0)       #exit program 
    '''
    #(not user_input) checks if user has pressed enter key without entering  
    # number.
    #(int(user_input)<=0) checks if user has entered any number less than or 
    #equal to zero.
    '''
    
    0 讨论(0)
  • 2020-12-09 00:07

    Actually, I suppose you are looking for a code that runs a loop until a key is pressed from the keyboard. Of course, the program shouldn't wait for the user all the time to enter it.

    1. If you use raw_input() in python 2.7 or input() in python 3.0, The program waits for the user to press a key.
    2. If you don't want the program to wait for the user to press a key but still want to run the code, then you got to do a little more complex thing where you need to use kbhit() function in msvcrt module.

    Actually, there is a recipe in ActiveState where they addressed this issue. Please follow this link

    I think the following links would also help you to understand in much better way.

    1. python cross platform listening for keypresses

    2. How do I get a single keypress at a time

    3. Useful routines from the MS VC++ runtime

    I hope this helps you to get your job done.

    0 讨论(0)
提交回复
热议问题