Python Forum
How to print out multiple drinks instead of just one based on the input? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to print out multiple drinks instead of just one based on the input? (/thread-27997.html)



How to print out multiple drinks instead of just one based on the input? - jayfre - Jun-30-2020

coffee=4
tea=3
coke=2
print()
menu={'Coffee':'$4.00','Tea':'$3.00','Coca-cola':'$2.00',"Press 'd' ":"complete order"}
ccount=0
tcount=0
cokecount=0
while True:
    for i in menu:
        print(f"{i}={menu[i]}")
    print()


    Condition=True
    while(Condition):
        drink=input('Select your drink from the menu:')
        drink=drink.capitalize()

        if drink == 'Coffee':
              quantity=int(input('Quantity:'))
              ccount+=quantity
              Condition=False
        elif drink == 'Tea':
             quantity=int(input('Quantity:'))
             tcount+=quantity
             Condition=False
        elif drink == 'Coca-cola':
             quantity=int(input('Quantity:'))
             cokecount+=quantity
             Condition=False

        elif drink=='D':
            condition=False
            amount=( ccount*4)+(tcount*3)+(cokecount*2)
            mem=input('Do u have membership?( Enter Y for yes, N for no):')
            mem=mem.capitalize()
            if amount>=10 and mem=='Y':
                purchaseDisc=amount*0.05
                memDisc=(amount-purchaseDisc)*0.15
                befTotal=(amount-purchaseDisc-memDisc)
                gst=befTotal*0.07
                total=befTotal+gst

            elif amount<10 and mem=='Y':
                purchaseDisc=0
                memDisc=amount*0.15
                befTotal=amount-memDisc
                gst=befTotal*0.07
                total=befTotal+gst

            elif amount>=10 and mem=='N':
                purchaseDisc=amount*0.05
                memDisc=0
                befTotal=amount-purchaseDisc
                gst=befTotal*0.07
                total=befTotal+gst

            else:
                purchaseDisc=0
                memDisc=0
                befTotal=amount
                gst=befTotal*0.07
                total=befTotal+gst


            print()
            print('Receipt')
            print('==============================')
            print(f'{"Drink":5s}:               {drink:>1s}')
            print(f'{"Quantity":8s}:{quantity:>13}')
            print(f'{"Member":6s}:{mem:>15}')
            print(f'{"Amount":6s}:{"$":>15}{amount:>5.2f}')
            print(f'{"Purchase Disc.":14s}{"$":>8}{purchaseDisc:>5.2f}')
            print(f'{"Member Disc.":12s}{"$":>10}{memDisc:>5.2f}')
            print(f'{"Total (bef. GST)":16s}{"$":>6}{befTotal:>5.2f}')
            print(f'{"GST":3s}{"$":>19}{gst:>5.2f}')
            print(f'{"Total (incl. GST)":17s}{"$":>5}{total:>5.2f}')
            exit()
        else:
             print('Please enter a drink from the menu!')
             Condition=True
How can i print out the different drinks and quantity that i inputted instead of just printing out 1?


RE: How to print out multiple drinks instead of just one based on the input? - Larz60+ - Jun-30-2020

You code is over complicated for the task at hand.
You use a dictionary for your menu, why not use one for choices made?
It will make the code much simpler, and more readable.


RE: How to print out multiple drinks instead of just one based on the input? - jayfre - Jun-30-2020

ccount=0
tcount=0
cokecount=0

while True:
    print("1.Coffee = $4.00")
    print("2.Tea = $3.00")
    print("3.Coca-Cola = $2.00")
    print("4.Complete order")
    choice= int(input("Make a selection:"))
    if choice ==1:
        quantity=int(input("Enter your quantity:"))
        ccount+= quantity
        drink="Coffee"
    elif choice ==2:
         quantity=int(input("Enter your quantity:"))
         tcount+= quantity
         drink="Tea"
    elif choice ==3:
          quantity=int(input("Enter your quantity:"))
          cokecount+= quantity
          drink="Coca-Cola"
    elif choice==4:
        mem=input('Do u have membership?( Enter Y for yes, N for no):')
        mem=mem.capitalize()
        amount=( ccount*4)+(tcount*3)+(cokecount*2)
        if amount>=10 and mem=='Y':
                purchaseDisc=amount*0.05
                memDisc=(amount-purchaseDisc)*0.15
                befTotal=(amount-purchaseDisc-memDisc)
                gst=befTotal*0.07
                total=befTotal+gst

        elif amount<10 and mem=='Y':
                purchaseDisc=0
                memDisc=amount*0.15
                befTotal=amount-memDisc
                gst=befTotal*0.07
                total=befTotal+gst

        elif amount>=10 and mem=='N':
                purchaseDisc=amount*0.05
                memDisc=0
                befTotal=amount-purchaseDisc
                gst=befTotal*0.07
                total=befTotal+gst

        else:
            purchaseDisc=0
            memDisc=0
            befTotal=amount
            gst=befTotal*0.07
            total=befTotal+gst

        print()
        print('Receipt')
        print('==============================')
        print(f'{"Drink":5s}:               {drink:>1s}')
        print(f'{"Quantity":8s}:{quantity:>13}')
        print(f'{"Member":6s}:{mem:>15}')
        print(f'{"Amount":6s}:{"$":>15}{amount:>5.2f}')
        print(f'{"Purchase Disc.":14s}{"$":>8}{purchaseDisc:>5.2f}')
        print(f'{"Member Disc.":12s}{"$":>10}{memDisc:>5.2f}')
        print(f'{"Total (bef. GST)":16s}{"$":>6}{befTotal:>5.2f}')
        print(f'{"GST":3s}{"$":>19}{gst:>5.2f}')
        print(f'{"Total (incl. GST)":17s}{"$":>5}{total:>5.2f}')
        exit()
i try to redo my previous codes to this is it more simplier?? However i still cannot print out the 1st input when i enter the 2nd input in this while true loop as they have the same variable name.


RE: How to print out multiple drinks instead of just one based on the input? - menator01 - Jul-01-2020

Here is my go at it. Modified
There is room for improvement.
#! /usr/bin/env python3

from subprocess import call
import os

call('clear' if os.name == 'posix' else 'cls')

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

class AddTax:
    def add_tax(self, total, tax):
        return total*tax

class Discount:
    def discount(self, total, discount_amount=0):
        return total*discount_amount

class Display:
    def output(self, text):
        print(text.title())

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()

    def show_menu(self):
        dodads = []
        for k, val in self.menu.menu().items():
            dodads.append(f'{k}: ${format(val, "0.2f")}')
        self.display.output(f'Menu: {", ".join(dodads)}')

def main():
    controller = Controller()

    while True:
        try:
            print('What would you like to drink?')
            print('Format is item amount seperated by comma or space.')
            print('Example: coke 3, tea 1')
            print()
            controller.show_menu()
            order = input('>> ').lower().split()
            while True:
                print('Are you a member? (y/n)')
                member = input('>>> ')
                print()
                print('--------------- Receipt ------------')
                if member.strip() == 'y' or member.strip() == 'yes':
                    membership = True
                    break
                else:
                    membership = False
                    break

            if order and len(order) >= 2:
                iters = iter(order)
                result = dict(zip(iters, iters))
                total = []
                combined_total = []
                for menuitem, amount in result.items():
                    if menuitem in controller.menu.menu().keys():
                        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))
                        controller.display.output(f'Item: {menuitem} {" ":>2} Amount: {amount} {" ":>2} Cost: ${format(cost, "0.2f")} {" ":>2} Total: ${totalcost}')
                    else:
                        controller.display.output(f'Item: {menuitem} is not on the menu.')
                print()
                total = sum(combined_total)
                if membership == True:
                    discount = controller.discount.discount(total, 0.15)
                else:
                    discount = 0
                newtotal = total-discount
                tax = controller.addtax.add_tax(newtotal, 0.09)
                finaltotal = newtotal+tax
                controller.display.output(f'Total: ${format(total,"0.2f")}')
                controller.display.output(f'Discount: - ${format(discount, "0.2f")}')
                controller.display.output(f'Total: ${format(newtotal,"0.2f")}')
                controller.display.output(f'Tax: ${format(tax,"0.2f")}')
                controller.display.output(f'Total: ${format(finaltotal,"0.2f")}')
                break
            else:
                print('You will need to enter both item and amout.')
                continue
        except ValueError as error:
            print(error)

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 2, tea 3, pepsi 1 Are you a member? (y/n) >>> y --------------- Receipt ------------ Item: Coke Amount: 2, Cost: $1.75 Total: $3.50 Item: Tea Amount: 3, Cost: $1.00 Total: $3.00 Sorry, Pepsi Is Not On The Menu. Total: $6.50 Discount: - $0.97 Total: $5.53 Tax: $0.50 Total: $6.02



RE: How to print out multiple drinks instead of just one based on the input? - menator01 - Jul-01-2020

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 -----------------------------------------------------------