Python Forum
How to print out multiple drinks instead of just one based on the input?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to print out multiple drinks instead of just one based on the input?
#5
You kind of inspired me with your code.
Here is one more tweak
#! /usr/bin/env python3

# Do the imports
from subprocess import call
import os

# Clears the screen of cluttered text
call('clear' if os.name == 'posix' else 'cls')

# Define Menu class and function/method
class Menu:
    def __init__(self):
        pass
    def menu(self):
        self.menuitems = {'coffee':1.25, 'tea': 1, 'coke':1.75, 'water':.5}
        return self.menuitems

# Define tax class and function/method
class AddTax:
    def add_tax(self, total, tax):
        return total*tax

# Define discount class and function/method
class Discount:
    def discount(self, total, discount_amount=0):
        return total*discount_amount

# class and function/method for displaying text
class Display:
    def output(self, text):
        print(text.title())

# Controller text for various operations
class Controller:
    def __init__(self, menu=None, addtax=None, discount=None, display=None):
        self.menu = menu or Menu()
        self.addtax = addtax or AddTax()
        self.discount = discount or Discount()
        self.display = display or Display()

    # Function/method for displaying menu items
    def show_menu(self):
        stuff = []
        for key, val in self.menu.menu().items():
            stuff.append(f'{key}: ${format(val, "0.2f")}')
        self.display.output(f'Menu: {", ".join(stuff)}')

# Define main
def main():
    # Initiate the controller class
    controller = Controller()

    # Start the loop
    while True:
        try:
            # Print out message
            print('What would you like to drink?')
            print('Format is item amount seperated by comma or space.')
            print('Example: coke 3, tea 1')
            # Add a blank line
            print()

            # Show the menu
            controller.show_menu()

            # Ask for order. Can be comma seperated or space
            # Examples coke 2, tea 2 or coke 2 tea 2
            order = input('>> ').lower().split()

            # Start a loop for asking if a member. Returns either True or False
            while True:
                print('Are you a member? (y/n)')
                member = input('>>> ')
                print()
                if member.strip() == 'y' or member.strip() == 'yes':
                    membership = True
                    break
                else:
                    membership = False
                    break

            # Prints the top part of receipt
            print(f"{''.ljust(25,'-')} Receipt {''.rjust(25,'-')}")

            # This check to make sure that an item and amount is entered
            # If not throws error and ask for correct input
            if order and len(order) >= 2:

                # Places the input into a dict for later use
                iters = iter(order)
                result = dict(zip(iters, iters))

                # Iniate a couple of list for storing
                total = []
                combined_total = []

                # Loop through our input and check if items are in our menu
                # Display accordingly
                for menuitem, amount in result.items():
                    if menuitem in controller.menu.menu().keys():

                        # Stores the cost of items .Gets the cost.
                        # Gets the cost
                        # Formats totalcost for display
                        # Stores combined total for item groups
                        total.append(controller.menu.menu()[menuitem])
                        cost = controller.menu.menu()[menuitem]
                        totalcost = f"{format(cost*int(amount.replace(',', ' ')), '0.2f')}"
                        combined_total.append(float(totalcost))

                        # Display items ordered
                        calmin = min(result)
                        calmax = max(result)
                        pad = len(calmin)

                        if len(menuitem) < len(calmin):
                            npad = len(calmin)-len(menuitem)+1
                        else:
                            npad = 1


                        controller.display.output(f'Item: {" ":>4} {menuitem} {"".rjust(npad," ")}Amount: {amount.replace(",","")} {" ":>2} Cost: ${format(cost, "0.2f")} {" ":>2} Total: ${totalcost}')
                    else:
                        controller.display.output(f'Item: {menuitem} is not on the menu.')
                # Print a blank line
                print()

                # Get a total cost of all ordered items
                total = sum(combined_total)

                # If a member add the discount
                if membership == True:
                    discount = controller.discount.discount(total, 0.15)
                else:
                    discount = 0

                # Get a new total with the discount
                newtotal = total-discount

                # Get the tax on our total
                tax = controller.addtax.add_tax(newtotal, 0.09)

                # Add the tax to our total
                finaltotal = newtotal+tax

                # Display the content
                controller.display.output(f'Total: {"".rjust(3," ")} ${format(total,"0.2f")}')
                controller.display.output(f'Discount: -${format(discount, "0.2f")}')
                controller.display.output(f'Total: {"".rjust(3," ")} ${format(newtotal,"0.2f")}')
                controller.display.output(f'Tax: {"".rjust(4," ")} +${format(tax,"0.2f")}')
                controller.display.output(f'Total: {"".rjust(3," ")} ${format(finaltotal,"0.2f")}')
                print(f'{"".rjust(59, "-")}')
                break
            else:
                print('You will need to enter both item and amout.')
                continue
        except ValueError as error:
            print('Please use the correct format when ordering.)

if __name__ == '__main__':
    main()
Output:
What would you like to drink? Format is item amount seperated by comma or space. Example: coke 3, tea 1 Menu: Coffee: $1.25, Tea: $1.00, Coke: $1.75, Water: $0.50 >> coke 1, tea 2 Are you a member? (y/n) >>> n ------------------------- Receipt ------------------------- Item: Coke Amount: 1 Cost: $1.75 Total: $1.75 Item: Tea Amount: 2 Cost: $1.00 Total: $2.00 Total: $3.75 Discount: -$0.00 Total: $3.75 Tax: +$0.34 Total: $4.09 -----------------------------------------------------------
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply


Messages In This Thread
RE: How to print out multiple drinks instead of just one based on the input? - by menator01 - Jul-01-2020, 06:53 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Change elements of array based on position of input data Cola_Reb 6 2,141 May-13-2022, 12:57 PM
Last Post: Cola_Reb
  How to map two data frames based on multiple condition SriRajesh 0 1,491 Oct-27-2021, 02:43 PM
Last Post: SriRajesh
  Exit function from nested function based on user input Turtle 5 2,930 Oct-10-2021, 12:55 AM
Last Post: Turtle
Exclamation question about input, while loop, then print jamie_01 5 2,685 Sep-30-2021, 12:46 PM
Last Post: Underscore
  Xlsxwriter: Create Multiple Sheets Based on Dataframe's Sorted Values KMV 2 3,507 Mar-09-2021, 12:24 PM
Last Post: KMV
Question How to print multiple elements from multiple lists in a FOR loop? Gilush 6 2,950 Dec-02-2020, 07:50 AM
Last Post: Gilush
  Loop back through loop based on user input, keeping previous changes loop made? hbkpancakes 2 2,956 Nov-21-2020, 02:35 AM
Last Post: hbkpancakes
  How to print string multiple times on new line ace19887 7 5,777 Sep-30-2020, 02:53 PM
Last Post: buran
  print function help percentage and slash (multiple variables) leodavinci1990 3 2,496 Aug-10-2020, 02:51 AM
Last Post: bowlofred
  taking input doesnt print as list bntayfur 2 2,126 Jun-04-2020, 02:48 AM
Last Post: bntayfur

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020