Python 5b - Sleep

Why use Sleep?

Sometimes in a program you will want to pause. You might want to do this:

  • To not overload a user with information all at once,

  • As part of a timer program,

  • To make it seem as if a program is loading or thinking.

Using Sleep

Start by importing sleep from the time library.

 

To pause the program, simply write the word sleep followed by the number of seconds that you wish the program to pause for in brackets.

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

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:

Practice Task

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

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

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

3. Wait 2 seconds, print “Thinking…” then 2 seconds later print the total of the two numbers multiplied by each other.

Example solution:

© CSNewbs 2019