How to understand 'time.sleep(secs)'

In Unit-5, Functions, exercise 4.1,
a new thing is introduced:
import time

time.sleep(5) # This will make your program sleep for 5 seconds

the solution for the exercise is:
from robot_control_class import RobotControl
import time

robotcontrol = RobotControl()

def move_x_seconds(secs):
    robotcontrol.move_straight()
    time.sleep(secs)
    robotcontrol.stop_robot()


move_x_seconds(5)

So I was confuse that time.sleep(5) is worked as ‘make the program sleep for 5 seconds’, or it works as ‘make the program sleep when counted to 5 seconds’?

Hi @253874655,

I don’t understand what you mean by ‘make the program sleep when counted to 5 seconds’, but what time.sleep(secs) does is make the program sleep (that is, pause execution) for secs seconds. secs is any integer you specify.

The function def move_x_seconds(secs) is a function that takes number of seconds as an argument. When you call it and pass the number of seconds, by writing something like move_x_seconds(5):

  • it moves the robot on the line robotcontrol.move_straight()
  • it then waits for secs on the line time.sleep(secs). In this case, secs=5 because 5 was passed to the function when it was called.
  • Finally it stops the robot on the line robotcontrol.stop_robot().

So in effect, the robot moves for 5 seconds because there’s a 5-second pause between when it was moved and when it was stopped.

Thanks for reply,

Can I understand in this way: when time.sleep(5) calls 5 seonds program pause, robot keep moving because command ‘moving_straight’ is already sent into program?

1 Like

Exactly, that’s right!