Traffic signal Program in Python [4 Approaches]

In this Python tutorial, we will see how to create a traffic signal program in Python with 4 different approaches and practical examples.

Traffic signals are crucial in regulating traffic flow and ensuring road safety. We will explore four different approaches to implementing a traffic signal program by using a while loop, using a dictionary, using class and object, using a generator

Let’s understand how it will work, we will set the timer which will change the signal every 5 seconds. These are the different approaches we will cover in this article.

  • Using While loop
  • Using class and objects
  • Using Dictionary
  • Using a Generator

Note: I have used the time module from Python in each case, and each example I have taken is an infinite loop in Python.

Python Traffic signal program using While Loop.

This approach uses a while loop in Python to iterate through the traffic signal sequence continuously. It uses a sleep function from the time module in Python to pause the execution for the specified duration.

The signal sequence consists of red, green, and yellow lights with respective durations.

Here is an instance:

Code

import time

def traffic_signal():
    while True:
        # Red light
        print("Red light - Stop")
        time.sleep(5)  # 5 seconds for red light
        
        # Green light
        print("Green light - Go")
        time.sleep(5)  # 5 seconds for green light
        
        # Yellow light
        print("Yellow light - Prepare to stop")
        time.sleep(2)  # 2 seconds for yellow light
traffic_signal()

Output: This is an infinite loop. It will go on until we forcefully stop it.

Red light - Stop
Green light - Go
Yellow light - Prepare to stop
Red light - Stop
Green light - Go
Yellow light - Prepare to stop
Red light - Stop
Green light - Go

The screenshot was taken after the code was implemented in the Python editor.

write python program for traffic signals

Traffic Signal Program in Python by class and objects

This approach defines a TrafficSignal class with attributes for colors and durations in Python.

The run method of the class iterates through the colors and durations, displaying each traffic signal state, and the display method formats and prints the signal state based on the color in Python.

Let’s see the example related to a traffic signal program in Python using class and objects

import time

class TrafficSignal:
    def __init__(self):
        self.colors = ["Red", "Green", "Yellow"]
        self.durations = [5, 5, 2]  # Duration for each color in seconds
    
    def run(self):
        while True:
            for color, duration in zip(self.colors, self.durations):
                self.display(color)
                time.sleep(duration)
    
    def display(self, color):
        print(f"{color} light - {'Stop' if color == 'Red' else 'Go' if color == 'Green' else 'Prepare to stop'}")

traffic_signal = TrafficSignal()
traffic_signal.run()

Output

Red light - Stop
Green light - Go
Yellow light - Prepare to stop
Red light - Stop
Green light - Go

Below screenshot provided, was taken after running the code in the Python editor.

traffic signal python program

Write a program for Traffic Signals in Python using the Dictionary

We use a Python dictionary to map colors to their respective durations.

The program iterates through the dictionary items and uses time to display each signal state accordingly. sleep to control the duration of each state.

Here is an example of a traffic signal program in Python using a dictionary:

Code

import time

def traffic_signal():
    signal = {"Red": 5, "Green": 5, "Yellow": 2}  # Color-duration mapping
    
    while True:
        for color, duration in signal.items():
            print(f"{color} light - {'Stop' if color == 'Red' else 'Go' if color == 'Green' else 'Prepare to stop'}")
            time.sleep(duration)

 traffic_signal()

Output

Red light - Stop
Green light - Go
Yellow light - Prepare to stop
Red light - Stop
Green light - Go

The resulting output is displayed in the screenshot below after running the code in Python editor.

create traffic signal program in python

Python Program for Traffic Signals Using Generator

We’ve defined a generator function traffic_signal that yields color and duration pairs in Python. It utilizes a while loop to generate signal states continuously and uses a display function to print them.

The generator in Python allows for a more concise representation of the signal sequence.

Here is an example of using the generator for a traffic signal program in Python:

Code

import time

def traffic_signal():
    colors = ["Red", "Green", "Yellow"]
    durations = [5, 5, 2]
    
    while True:
        for color, duration in zip(colors, durations):
            yield color, duration

def display(color):
    print(f"{color} light - {'Stop' if color == 'Red' else 'Go' if color == 'Green' else 'Prepare to stop'}")

signal_generator = traffic_signal()
while True:
    color, duration = next(signal_generator)
    display(color)
    time.sleep(duration)

Output

Red light - Stop
Green light - Go
Yellow light - Prepare to stop
Red light - Stop
Green light - Go

Below is a screenshot that reveals the output after the code has been implemented in the Python editor.

python program of traffic signal

Conclusion

Here, we have seen four approaches to implementing a traffic signal program in Python. Each approach demonstrated various programming techniques, including while loops, dictionaries, classes and objects, and generator functions, with some practical examples.

By understanding these methods, one can use them in different situations of Python programming and choose the most appropriate approach for their code.

You may also like to read these articles: