NameError: name 'sleep' is not defined in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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.

main.py
# ⛔️ 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.

main.py
# 👇️ 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).

main.py
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.

main.py
import time while True: print('Runs every 3 seconds') time.sleep(3)

The code in the body of the while loop is run 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.

main.py
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.

Conclusion #

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.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.