Monday, April 21, 2025

Pause Execution of Program in Python - time.sleep() Example

import time

names = ["Michael", "Samantha", "John"]

for x in names:
    print('Printing now: ' + x)
    time.sleep(2)

This Python code imports the "time" module using the "import" statement.

The code initializes a list variable named "names" with three string values: "Michael", "Samantha", and "John".

The code then enters a "for" loop that iterates over each element (a string value) of the "names" list. In each iteration of the loop, the code prints a message to the console screen using the "print()" function. The message being printed is "Printing now: " concatenated with the string value of the current element of the "names" list.

After printing the message, the "time.sleep()" function is used to pause the program execution for 2 seconds, which creates a delay before the next iteration of the loop.

The combination of these statements creates a program that prints a message with the name of each person in the "names" list to the console screen with a delay of 2 seconds between each name.

So, when the program is run, the console screen will display the message "Printing now: Michael", followed by a 2-second pause, then the message "Printing now: Samantha", followed by another 2-second pause, and finally the message "Printing now: John".

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...