In: Computer Science
Write a TicketMachine class in PYTHON PROGRAM, which models a ticket machine that issues flatfare tickets. The price of a ticket is specified via the constructor (you can use price variable).
Your TicketMachine class will have the following methods:
(a) insertMoney, which receives an amount of money from a customer and updates customer’s balance (you can use balance variable).
(b) getPrice, which return and prints the price of a ticket.
(c) getBalance, which returns and prints the amount of money already inserted for the ticket
(d) printTicket, which prints a ticket, update the total collected by the machine and reduce the balance to zero.
The ticket will be printed if the customer’s balance is greater than or equal to ticket price. You also need to define a variable e.g., total, which keeps track of the total amount of money collected by the machine.
Your program should be able to check if the ticket price and the amount entered by the customer is valid. For example, ticket price and the amount entered by the user cannot be negative.
Python code:
class TicketMachine: # Static variable to keep track of the total amount # of money collected by the machine total = 0 # Constructor which takes ticket price def __init__(self, price): # To keep track of customer's balance self.balance = 0 # Ticket price self.price = 0 # Validate ticket price if price >= 0: self.price = price # (a) Function which receives an amount of money from a customer # and updates customer’s balance def insertMoney(self, amount): # Validate amount entered by the customer if amount > 0: self.balance += amount # (b) Function which returns and prints the price of a ticket def getPrice(self): return self.price # (c) Function which returns and prints the amount of money # already inserted for the ticket def getBalance(self): return self.balance # prints a ticket, update the total collected by # the machine and reduce the balance to zero. # The ticket will be printed if the customer’s # balance is greater than or equal to ticket price. def printTicket(self): # If balance is not sufficient, do not print the ticket if self.balance < self.price: print("Insufficient balance\n") return # Print the ticket print("*********TICKET*********") print("Ticket price: ${:.2f}".format(self.price)) print("Ticket qty: 1\n") # Update the total collected by the machine TicketMachine.total += self.price # Reduce the balance to zero self.balance = 0 # Create a TicketMachine with ticket price set to $12.00 ticket = TicketMachine(12) # Customer A inserts $15.00 to the machine ticket.insertMoney(15) ticket.printTicket() # Customer B inserts $11.00 to the machine ticket.insertMoney(11) ticket.printTicket() # Customer B inserts $1.00 more to the machine ticket.insertMoney(1) ticket.printTicket() # Print the total money collected by the TicketMachine print("Total amount collected: ${:.2f}".format(TicketMachine.total))
Output:
Kindly rate the answer and for any help just drop a comment