2

I am new to python and would like to create a Pizza ordering system using python, that looks something like this.

1   Hawaiian                      $7.50
2   Champagne Ham & Cheese        $7.50
3   Beef & Onion                  $7.50
4   Pepperoni                     $7.50
5   Simply Cheese                 $7.50
6   Bacon & Mushroom              $7.50
7   Italiano                      $7.50
8   The Deluxe                    $13.50  
9   Ham, Egg & Hollandaise        $13.50
10  Americano                     $13.50
11  Mr Wedge                      $13.50
12  BBQ Meatlovers                $13.50

I would then like the customer to be able to select different pizzas based on the number so that they don't have to type Hawaiian, they can instead type 1. I have tried both dictionaries and lists but always resulted in this problem:

1  Hawaiian $7.50
2  Champagne Ham & Cheese$7.50
3  Beef & Onion $7.50
4  Pepperoni $7.50
5  Simply Cheese $7.50
6  Bacon & Mushroom $7.50
7  Italiano $7.50
8  The Deluxe $13.50 
9  Ham, Egg & Hollandaise $13.50
10  Americano $13.50
11  Mr Wedge $13.50 
12  BBQ Meatlovers $13.50

Where the prices would "stick to the pizza name" and the names of pizzas 10 onwards were indented by one character. Manually putting spaces does not seem like the most efficient way of going about my problem. e.g

standardprice = "$7.50"
    deluxeprice = "13.50"
    print (
    """   
1   Hawaiian                      %s
2   Champagne Ham & Cheese        %s
3   Beef & Onion                  %s
4   Pepperoni                     %s
5   Simply Cheese                 %s
6   Bacon & Mushroom              %s
7   Italiano                      %s
8   The Deluxe                    %s  
9   Ham, Egg & Hollandaise        %s
10  Americano                     %s
11  Mr Wedge                      %s
12  BBQ Meatlovers                %s
     """  % (standardprice, standardprice, standardprice, standardprice, 
             standardprice, standardprice, standardprice,deluxeprice,            
             deluxeprice,deluxeprice, deluxeprice, deluxeprice)
        )

Is there an easier way to solve my problem? Also as a side question when printing is there a way that "standardprice" variable applies to the first 7 elements and deluxe price applies to 8-12, rather than the crude way I have done it.

here had a somewhat similar problem but the page did not help.Code Academies "A day at the supermarket tutorial" was not particularly helpful either. I'm very new to python, so explaining like I know nothing would be very helpful

Community
  • 1
  • 1
afro
  • 33
  • 1
  • 1
  • 3
  • You can't create a restaurant menu in Python without [spam](http://www.detritus.org/spam/skit.html)! – abarnert May 02 '15 at 04:47
  • Meanwhile, "I have tried both dictionaries and lists" doesn't help us unless you show us _what_ you tried. This problem certainly can be solved with a dictionary or with a list; if you got it wrong and want us to help you, we'll need to see your attempt to explain what you got wrong and how to fix it. – abarnert May 02 '15 at 04:50
  • http://stackoverflow.com/questions/5676646/fill-out-a-python-string-with-spaces – abcd May 02 '15 at 05:06
  • http://stackoverflow.com/questions/14776788/python-how-can-i-pad-a-string-with-spaces-from-the-right-and-left – abcd May 02 '15 at 05:08

4 Answers4

1

There are some super handy utilities for string formatting: ljust|rjust, for just this sort of thing.

Here's a quick example I whipped up using ljust, but don't stop here; take a peek at the doc linked above and let your imagination go wild with string-formatting-freedom!

from collections import namedtuple

MenuEntry = namedtuple('MenuEntry', ['index','description','price'])
_menu = []
_menu.append(MenuEntry(1, 'Hawaiian', '$7.50'))
_menu.append(MenuEntry(2, 'Champagne Ham & Cheese', '$7.50'))
_menu.append(MenuEntry(3, 'Beef & Onion', '$7.50'))
_menu.append(MenuEntry(40, 'Pepperoni', '$10.50'))
_menu.append(MenuEntry(100, 'Simply Cheese', '$17.50'))

for entry in _menu:
    index = str(getattr(entry,'index')).ljust(5)
    descr = getattr(entry,'description').ljust(25)
    price = getattr(entry,'price').ljust(7)
    print '{0}{1}{2}'.format(index,descr,price)

""" Output: """

1    Hawaiian                 $7.50  
2    Champagne Ham & Cheese   $7.50  
3    Beef & Onion             $7.50  
40   Pepperoni                $10.50 
100  Simply Cheese            $17.50 

""""""""""""""""""""""""""""
MrDuk
  • 16,578
  • 18
  • 74
  • 133
  • 1
    Why are you using `getattr(entry, 'index')` instead of just `entry.index`? – abarnert May 02 '15 at 10:55
  • Also, if you're going to end up using `str.format`, why not just put the justification in the format string instead of doing it in two steps over 4 lines? (And then you also don't need the `str` call, to boot.) – abarnert May 02 '15 at 10:55
  • 1
    Thanks, This method was best suited to my question. I would like if you could answer abarnert's comment for further refinement of the code. In terms of the next step where the user selects the meals they would like, if you have any free time and would like to hep me further that would be great however in the mean time i will work through it myself. @MrDuk – afro May 04 '15 at 00:10
  • 1
    @afro - Sure, the primary reason is because the `namedtuple` documentation page lists `getattr()` as the suggested method for getting values. Albeit, if you check out the `getattr()` docs, it mentions being equivalent to `obj.item`, as abarnert suggests. As to the format suggestion, I just find it cleaner to separate it out into several lines, rather than have one super long line, that's likely to grow as we add columns. What other questions do you have? I suggest creating a new question, and linking it here. – MrDuk May 04 '15 at 06:04
0

Here's a working example, but I used the pandas library to save myself lots of grief. Go through the comments first if you can/want, then hit back if you have other questions.

Admittedly, this is not for beginners, but except for the formatting part for the DataFrame, it's pretty basic.

import pandas as pd

pizzas = [
    "Hawaiian",
    "Champagne Ham & Cheese",
    "Beef & Onion",
    "Pepperoni",
    "Simply Cheese",
    "Bacon & Mushroom",
    "Italiano",
    "The Deluxe",
    "Ham, Egg & Hollandaise",
    "Americano",
    "Mr Wedge",
    "BBQ Meatlovers"
    ]

df = pd.DataFrame(pizzas, columns=["Pizzas"])
df.loc[:8, "Prices"] = 7.50     # First 7 items.
df.loc[8:, "Prices"] = 13.50    # All the rest.
df.index += 1                   # So that it's not zero-indexed.
total_bill = 0.0                # Meh.

print "Welcome to Pizza Planet!" # So unoriginal, I know.
print
print "Here's our menu!"
print
# Following method taken and modified from unutbu's amazing answer
# here: http://stackoverflow.com/questions/25777037
print df.to_string(justify='left',
                   header=False,
                   formatters={
                    'Pizzas':'{{:<{}s}}'.format(
                        df['Pizzas'].str.len().max()
                        ).format,
                    'Prices':'     ${:.2f}'.format})
print
print "Input a number and press enter to select an item."
print "Input 'done' to finish your order and tabulate your bill."
print "Input 'exit' to cancel your orders."

while True:

    order = raw_input(">>>  ")

    if order == 'exit':
        break
    elif order == 'done':
        print "Your total bill is ${:.2f}.".format(total_bill)
        raw_input("Press any key to exit.")
        break
    elif int(order) in df.index:
        item = df.loc[int(order), "Pizzas"]     # Get the respective items
        price = df.loc[int(order), "Prices"]    # by indexing order input.
        print "You've selected {}! That would be ${:.2f}.".format(item, price)
        total_bill += price
        continue
    else:
        print "Don't be an idiot." # :-)
        raw_input("Press any key to exit.")
        break

Result:

enter image description here

WGS
  • 13,969
  • 4
  • 48
  • 51
0
menu = int(input("   ORDER PLEASE \n 1.kanji with \n 2. fish with \n 3.rise with chicken \n \n   Select Yours"))

if menu == 1:
    print("\n kanji with $10 ")

    conform =int(input("\n conform to press one"))

    if conform ==1:
        print("\n Order confirmed")
    else:
        print("chose correct option")

elif menu == 2:
    print("\n fwith booti $15")

    confm = int(input("\nconform to press one"))

    if confm == 1:
        print("\n Order confirmed")
    else:
        print("chose correct option")

elif menu == 3:
    print("\npoola with booti $20")

    conform = int(input("\n conform to press one"))

    if conform == 1:
        print("\n Order confirmed")
    else:
        print("chose correct option")

else:
    print("\n WRONG SELECTION")
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Asharu Ashkar
  • 51
  • 1
  • 3
-1

Here's a quick and dirty version, you should of course do some checking to avoid errors. But this will work:

from collections import OrderedDict

thatsALowPrice = 7.50
thatsAHighPrice = 10.50

myMenu = OrderedDict()

myMenu["Sandwich"] = thatsALowPrice
myMenu["Burger"] = thatsALowPrice
myMenu["Steak"] = thatsAHighPrice

i=1
for k, v in myMenu.items():
    print(i, ":", k, "\t\t", v)
    i+=1

itemNumber = int(input("Choose your item: "))
item=list(myMenu.items())[itemNumber-1]

print("You chose", item[0], "at a price of: $"+str(item[1]))
connorjan
  • 24
  • 4
  • 1
    not only is this quick and dirty, it straight up does not accomplish what the OP asked for. – abcd May 02 '15 at 05:12
  • 1
    @dbliss: But on the plus side, it makes sure to use tabs so that it will fail to accomplish it in different ways on different terminals. – abarnert May 02 '15 at 10:57