How to use a while loop to continually display messages in Python

Published on Aug. 22, 2023, 12:16 p.m.

To use a while loop to continually display messages in Python, you can follow these steps:

  1. Create a variable to store the message that you want to display.
  2. Start a while loop that continues indefinitely using the True keyword.
  3. Inside the while loop, use the print() function to display the message.
  4. Use the time.sleep() function to pause for a specific amount of time between each message.

Here is an example code that displays a message every 5 seconds using a while loop:

import time

message = "Hello! This is a message."

while True:
    print(message)
    time.sleep(5)

This program will display the message “Hello! This is a message.” every 5 seconds until you stop the program manually using Ctrl+C on a Windows machine or COMMAND+C on a Mac.

Tags:

related content