Exit while loop by user hitting ENTER key

前端 未结 14 1863
难免孤独
难免孤独 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:55

    This works for python 3.5 using parallel threading. You could easily adapt this to be sensitive to only a specific keystroke.

    import time
    import threading
    
    
    # set global variable flag
    flag = 1
    
    def normal():
        global flag
        while flag==1:
            print('normal stuff')
            time.sleep(2)
            if flag==False:
                print('The while loop is now closing')
    
    def get_input():
        global flag
        keystrk=input('Press a key \n')
        # thread doesn't continue until key is pressed
        print('You pressed: ', keystrk)
        flag=False
        print('flag is now:', flag)
    
    n=threading.Thread(target=normal)
    i=threading.Thread(target=get_input)
    n.start()
    i.start()
    

提交回复
热议问题