Python implementation of a class to simulate a queuing system
We will use Python to implement a simple queuing system class. This class will allow users to add customers to the queue, remove customers, and view the current queue status.
Example
class QueueSystem:
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} has been added to the queue.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} has been removed from the queue.")
else:
print("The queue is empty.")
def show_queue(self):
if self.queue:
print("Current queue:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("The queue is empty.")
# Example usage
queue_system = QueueSystem()
queue_system.add_customer("Alice")
queue_system.add_customer("Bob")
queue_system.show_queue()
queue_system.remove_customer()
queue_system.show_queue()
def __init__(self):
self.queue = []
def add_customer(self, name):
self.queue.append(name)
print(f"{name} has been added to the queue.")
def remove_customer(self):
if self.queue:
removed_customer = self.queue.pop(0)
print(f"{removed_customer} has been removed from the queue.")
else:
print("The queue is empty.")
def show_queue(self):
if self.queue:
print("Current queue:")
for i, customer in enumerate(self.queue, 1):
print(f"{i}. {customer}")
else:
print("The queue is empty.")
# Example usage
queue_system = QueueSystem()
queue_system.add_customer("Alice")
queue_system.add_customer("Bob")
queue_system.show_queue()
queue_system.remove_customer()
queue_system.show_queue()
Code analysis:
QueueSystemWhen the class is initialized, an empty list is createdqueueto store customers.add_customerThe method accepts a customer's name and adds it to the end of the queue.remove_customerThe method removes the first customer in the queue (i.e., the customer who joined earliest). If the queue is empty, it prompts that the queue is empty.show_queueThe method displays all customers in the current queue. If the queue is empty, it prompts that the queue is empty.
Output result:
Alice has been added to the queue. Bob has been added to the queue. Current queue: 1. Alice 2. Bob Alice has been removed from the queue. Current queue: 1. BobOther extensions
Python3 Examples