Fix - NameError: name 'sleep' is not defined in Python


Borislav Hadzhiev

Wed Apr 20 20221 min read


Photo by Raychan

Fix - NameError: name 'sleep' is not defined in Python #

The Python "NameError: name 'sleep' is not defined" occurs when we use the sleep() function without importing it first. To solve the error, import the function from the time module before using it - from time import sleep.

nameerror name sleep is not defined

Here is an example of how the error occurs.
# ⛔️ NameError: name 'sleep' is not defined sleep(3) print('After 3 seconds')

To solve the error, we have to import the sleep function from the time module.
# 👇️ import sleep function from time import sleep sleep(3) # 👈️ time in seconds print('After 3 seconds')

Alternatively, you can import the time module and access the sleep function as time.sleep(N).
import time time.sleep(3) print('After 3 seconds')

The sleep function takes a number of seconds as a parameter and suspends execution for the given number of seconds.

If you need to call a function or run some logic every N seconds, use a while loop.
import time while True: print('Runs every 3 seconds') time.sleep(3)

The code in the body of the while loop is ran every 3 seconds.

You can also pass a floating point number as an argument to sleep if you need to suspend execution for X.Y seconds.
import time time.sleep(2.5) print('After 2.5 seconds')

Note that the sleep() function suspends execution at least for the provided number of seconds, except in the case when an exception is raised.

Use the search field on my Home Page to filter through my more than 1,000 articles.