top of page
top

Python 5b - Sleep

noun-import-1073974-FFFFFF.png

Using Sleep

To pause a program, import sleep from the time library.

 

Type the word sleep followed by the number of seconds that you wish the program to break for in brackets. It must be a whole number.

​

Below is an example of a program that imports the sleep command and waits for 2 seconds between printing:

from time import sleep

​

print("Hello!")

sleep(2)

print("Goodbye!")

You can implement the sleep command within a for loop to produce an effective timer that outputs each second waited to the screen:

You could also use a variable instead of a fixed value with the sleep command such as below:

from time import sleep

​

for second in range(1,11):

    print(second)

    sleep(1)

from time import sleep

​

seconds =  int(input("How many seconds should I sleep? "))

​

print("Going to sleep...")

sleep(seconds)

print("Waking up!")

Sleep Task (Slow Calculator)

Create a slow calculator program that needs time to think in between calculations.

​

Print a message to greet the user, then wait 3 seconds and ask them to enter a number.

​

Wait another 3 seconds and ask them to enter a second number.

 

Wait 2 more seconds, print “Thinking…” then 2 seconds later print the total of the two numbers added together.

Example solution:

bottom of page