Select Page

Most recent update: 1 Jul 2021

Sometimes, you will need to have a program wait before it moves on. You might need to wait for another function to complete, for a file to upload, or simply to make the user experience smoother. If you’ve got a Python program and you want to make it wait, you can use a simple function like this one:

time.sleep(x) where x is the number of seconds that you want your program to wait.

For example, the following Python code will make your program wait for 10 seconds:

import time
time.sleep(10)

Watch this quick time.sleep(x) tutorial to get started with making your program wait:

 

How Python Wait Works Under The Hood

On modern computers, the operating system (OS) is responsible for keeping track of the current time and date. In Python, “time” is the library that contains a number of time-related functions that interface with the operating system.

“time.sleep()” is a function that takes advantage of the operating system’s clock functionality. Underneath the surface, the Python standard library calls your operating system’s implementation of a “sleep” function — on Linux, for example, it’s just named “sleep”. 

The operating system then temporarily suspends the execution of your program and, after the indicated number of seconds has passed, awakens it.

Because the sleep functionality is handled by the operating system, your computer’s processor will be freed up for any other work while your Python program is asleep. Programs that are waiting on sleep timers don’t actively use your system’s resources.

The operating system will do its best to resume your program’s execution after the exact number of seconds in your “time.sleep()” call, but the precision isn’t guaranteed for reasons of system performance and power efficiency. Depending on how occupied your system is with other programs, it is possible for the “sleep” call to take a bit longer than you expected — although normally the delay will be measured in milliseconds.

Practise Using Python Wait

Now that you know how to make a program wait, want to practice using this function? You can practice by creating your own program, “Take A Break,” from Udacity’s Intro to Programming with Python course.

Take a Break instructs your computer periodically to open a web browser and play your favorite YouTube song. This is a great way to use a program function to remind yourself to take a stretch (or dance!) break when you’ve been glued to the computer screen all day.

What's your break jam!

What’s your break jam?

There are more fun mini-projects where that came from! Learn more about functions with six projects in Intro to Object Oriented Programming, an introductory course where you’ll master foundational programming concepts.

If you’re ready to take the next step, you can learn Python to prepare for a career in Data with our Python for Data Science Nanodegree Program

Enroll Now