This article will give you some solutions to fix “NameError: name ‘sleep’ is not defined” error in Python. Follow it and solve your problem.
What causes the “NameError: name ‘sleep’ is not defined” error?
‘NameError’ is an error when you use a variable, function, or module that is not declared or you are not using it properly.
‘NameError: name ‘sleep’ is not defined’ error happens when you use the function
sleep() without importing the function before using it.
sleep(2) print('My name is John')
Traceback (most recent call last): File "prog.py", line 1, in <module> sleep(2) NameError: name 'sleep' is not defined
How to solve this error?
Import the ‘sleep’ function from the ‘time’ module
You can import the ‘sleep’ function from the ‘time’ module to fix this problem. Look at the following example to understand more:
from time import sleep sleep(2) print('The program will output after 2 seconds')
The program will output after 2 seconds
In the example above, I use the
sleep() function after 2 seconds, and the program will execute the command line ‘print’.
Use time.sleep() function
time.sleep() function also is an excellent solution for this problem. First, you must import the ‘time’ module and then use the function
import time print("Hello") time.sleep(2) print("World!!!")
Firstly, the program outputs to the screen ‘hello’ and then executes the command line:
time.sleep(2), the program will be waiting. After 2 seconds, it continues to output ‘World!!!’ word to the screen.
The ‘sleep()’ function in a multithreaded program
In a multithreaded program, the ‘sleep’ function will pause the execution of the current thread for a certain number of seconds.
import threading import time def printName(): for i in range(5): time.sleep(0.3) print("Jason Wilson") def printGreeting(): for i in range(5): time.sleep(0.5) print("Nice to meet you!") a = threading.Thread(target = printName) b = threading.Thread(target = printGreeting) a.start() b.start()
Jason Wilson Nice to meet you! Jason Wilson Jason Wilson Nice to meet you! Jason Wilson Jason Wilson Nice to meet you! Nice to meet you! Nice to meet you!
Two ‘threads’ appear in the above program.
time.sleep(0.5) have the effect of pausing the execution of these two threads for 0.3 and 0.5 seconds
If you have any questions about the “NameError: name ‘sleep’ is not defined” error in Python, leave a comment below. I will answer your questions.
Maybe you are interested:
- NameError: name ‘xrange’ is not defined in Python
- NameError: name ‘unicode’ is not defined in Python
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Programming Languages: C++, Python, Java