ErikS
ErikS

Reputation: 163

What is the simplest way to pause a loop by waiting for a user to press a key?

In Python, what is the simplest and most Pythonic way to pause a loop where a user keypress would restart the loop? I'm looking at doing this just as a debugging aid, so that I can output some debug messages to stdout from within the loop without dumping a ton of text at once.

Upvotes: 2

Views: 451

Answers (1)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

If you are willing to limit the keypress to the Enter key, you can use input (raw_input in Python 2). Otherwise, you'll need something platform specific.

for i in range(10):
    print(i)
    input() # Loop continues after <Enter> is pressed

Alternatively, you could use pdb, Python's built in debugger.

See also Python read a single character from the user.

Upvotes: 6

Related Questions