Exit while loop by user hitting ENTER key

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

提交回复
热议问题