Python wait time, wait for user input

Filed Under: Python

Sometimes we want our python program to wait for a specific time before executing the next steps. We can use time module sleep() function to pause our program for specified seconds.

Python wait time

Let’s see a quick example where we will pause our program for 5 seconds before executing further statements.


import time

print('Hello There, next message will be printed after 5 seconds.')

time.sleep(5)

print('Sleep time is over.')

When we run this program, there will be 5 seconds delay between first print statement and second print statement.

Python wait for user input

Sometimes we want to get some inputs from the user through the console. We can use input() function to achieve this. In this case, the program will wait indefinitely for the user input. Once the user provides the input data and presses the enter key, the program will start executing the next statements.


sec = input('Let us wait for user input. Let me know how many seconds to sleep now.\n')

print('Going to sleep for', sec, 'seconds.')

time.sleep(int(sec))

print('Enough of sleeping, I Quit!')

Below short screen capture shows the complete program execution.

python wait time, python wait for user input

Surprising, there is no easy way to wait for user input with a timeout or default value when empty user input is provided. I hope these useful features come in future Python releases.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages