What is sleep()?
Sometimes you want your program to wait before doing the next thing—perhaps to create suspense in a game, rate-limit API calls, or print a countdown. Python’s sleep() function (from the time module) pauses execution for a number of seconds.
Basic Pause with sleep()
Import the function and pass the number of seconds to wait:
from time import sleep
print("Hello!")
sleep(2) # wait for 2 seconds
print("Goodbye!")
Using sleep() in a Loop (Timer)
Add a short delay on each iteration to print a friendly timer or countdown:
from time import sleep
for second in range(1, 11):
print(second)
sleep(1) # 1-second interval
Let the User Choose the Delay
Prompt the user, then sleep for that many seconds:
from time import sleep
seconds = int(input("How many seconds should I sleep? "))
print("Going to sleep...")
sleep(seconds)
print("Waking up!")
Sleep Task – Slow Calculator
- Greet the user.
- Wait 3 seconds, then ask for the first number.
- Wait another 3 seconds, then ask for the second number.
- Pause for 2 seconds, print “Thinking…”, wait another 2 seconds, then print the sum.
from time import sleep
print("Welcome to the Slow Calculator!")
sleep(3)
num1 = int(input("Enter the first number: "))
sleep(3)
num2 = int(input("Enter the second number: "))
sleep(2)
print("Thinking...")
sleep(2)
print("The total is", num1 + num2)