Traffic Signal Program in Python

When I first started learning Python more than a decade ago, I loved building small projects that looked like real-world systems. One of my favorites was a traffic signal program.

It’s simple, fun, and surprisingly practical. If you live in the USA, you see traffic lights every day, green for go, yellow for slow down, and red for stop. Simulating this in Python makes the concept very relatable.

In this tutorial, I’ll show you different methods to create a traffic signal program in Python. Each method is beginner-friendly, and I’ll share the complete code so you can try it on your own system.

Method 1: Use While Loop in Python

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:

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:

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

You can refer to the screenshot below to see the output.

write python program for traffic signals

This example demonstrates simulating a traffic light system in Python using a while loop and time delays for each signal.

Method 2: Use Python classes 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.

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

You can refer to the screenshot below to see the output.

traffic signal python program

This example shows how to simulate a traffic light system in Python using classes, objects, and methods for better structure and readability.

Method 3: Use Python 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.

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

You can refer to the screenshot below to see the output.

create traffic signal program in python

This example demonstrates simulating a traffic light system in Python efficiently using a dictionary to map colors to their durations.

Method 4: Use Generator in Python

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.

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

You can refer to the screenshot below to see the output.

python program of traffic signal

This example shows how to use a generator for an elegant and memory-efficient way to simulate a continuous traffic light system in Python.

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:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.