在 python 中创建具有良好布局的 restaurant/pizza 菜单
Creating a restaurant/pizza menu in python, with a good layout
我是 python 的新手,想使用 python 创建一个披萨订购系统,看起来像这样。
1 Hawaiian .50
2 Champagne Ham & Cheese .50
3 Beef & Onion .50
4 Pepperoni .50
5 Simply Cheese .50
6 Bacon & Mushroom .50
7 Italiano .50
8 The Deluxe .50
9 Ham, Egg & Hollandaise .50
10 Americano .50
11 Mr Wedge .50
12 BBQ Meatlovers .50
然后我希望客户能够根据数量 select 不同的比萨饼,这样他们就不必输入夏威夷语,而是可以输入 1。
我试过字典和列表,但总是导致这个问题:
1 Hawaiian .50
2 Champagne Ham & Cheese.50
3 Beef & Onion .50
4 Pepperoni .50
5 Simply Cheese .50
6 Bacon & Mushroom .50
7 Italiano .50
8 The Deluxe .50
9 Ham, Egg & Hollandaise .50
10 Americano .50
11 Mr Wedge .50
12 BBQ Meatlovers .50
价格 "stick to the pizza name" 并且比萨饼的名称从 10 开始缩进一个字符。手动放置空格似乎不是解决我的问题的最有效方法。例如
standardprice = ".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)
)
有没有更简单的方法来解决我的问题?另外作为打印时的附带问题,是否有一种方法可以将 "standardprice" 变量应用于前 7 个元素,并将豪华价格应用于 8-12,而不是我所做的粗略方式。
here had a somewhat similar problem but the page did not help.Code Academies
"A day at the supermarket tutorial" 也不是特别有用。
我是 python 的新手,所以像我什么都不知道的那样解释会很有帮助
这里是一个快速而粗略的版本,你当然应该做一些检查以避免错误。但这会起作用:
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]))
这是一个工作示例,但我使用 pandas
库来避免很多麻烦。如果您 can/want,请先浏览评论,如果您有其他问题,请回复。
不可否认,这不适合初学者,但除了 DataFrame 的格式化部分,它是非常基础的。
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:
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
结果:
字符串格式化有一些super handy utilities:ljust
|rjust
,只是这种东西。
这是我使用 ljust
快速创建的一个示例,但不要就此打住;看看上面链接的文档,让您的想象力随着字符串格式的自由而疯狂!
from collections import namedtuple
MenuEntry = namedtuple('MenuEntry', ['index','description','price'])
_menu = []
_menu.append(MenuEntry(1, 'Hawaiian', '.50'))
_menu.append(MenuEntry(2, 'Champagne Ham & Cheese', '.50'))
_menu.append(MenuEntry(3, 'Beef & Onion', '.50'))
_menu.append(MenuEntry(40, 'Pepperoni', '.50'))
_menu.append(MenuEntry(100, 'Simply Cheese', '.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 .50
2 Champagne Ham & Cheese .50
3 Beef & Onion .50
40 Pepperoni .50
100 Simply Cheese .50
""""""""""""""""""""""""""""
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 ")
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 ")
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 ")
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")
我是 python 的新手,想使用 python 创建一个披萨订购系统,看起来像这样。
1 Hawaiian .50
2 Champagne Ham & Cheese .50
3 Beef & Onion .50
4 Pepperoni .50
5 Simply Cheese .50
6 Bacon & Mushroom .50
7 Italiano .50
8 The Deluxe .50
9 Ham, Egg & Hollandaise .50
10 Americano .50
11 Mr Wedge .50
12 BBQ Meatlovers .50
然后我希望客户能够根据数量 select 不同的比萨饼,这样他们就不必输入夏威夷语,而是可以输入 1。 我试过字典和列表,但总是导致这个问题:
1 Hawaiian .50
2 Champagne Ham & Cheese.50
3 Beef & Onion .50
4 Pepperoni .50
5 Simply Cheese .50
6 Bacon & Mushroom .50
7 Italiano .50
8 The Deluxe .50
9 Ham, Egg & Hollandaise .50
10 Americano .50
11 Mr Wedge .50
12 BBQ Meatlovers .50
价格 "stick to the pizza name" 并且比萨饼的名称从 10 开始缩进一个字符。手动放置空格似乎不是解决我的问题的最有效方法。例如
standardprice = ".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)
)
有没有更简单的方法来解决我的问题?另外作为打印时的附带问题,是否有一种方法可以将 "standardprice" 变量应用于前 7 个元素,并将豪华价格应用于 8-12,而不是我所做的粗略方式。
here had a somewhat similar problem but the page did not help.Code Academies "A day at the supermarket tutorial" 也不是特别有用。 我是 python 的新手,所以像我什么都不知道的那样解释会很有帮助
这里是一个快速而粗略的版本,你当然应该做一些检查以避免错误。但这会起作用:
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]))
这是一个工作示例,但我使用 pandas
库来避免很多麻烦。如果您 can/want,请先浏览评论,如果您有其他问题,请回复。
不可否认,这不适合初学者,但除了 DataFrame 的格式化部分,它是非常基础的。
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:
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
结果:
字符串格式化有一些super handy utilities:ljust
|rjust
,只是这种东西。
这是我使用 ljust
快速创建的一个示例,但不要就此打住;看看上面链接的文档,让您的想象力随着字符串格式的自由而疯狂!
from collections import namedtuple
MenuEntry = namedtuple('MenuEntry', ['index','description','price'])
_menu = []
_menu.append(MenuEntry(1, 'Hawaiian', '.50'))
_menu.append(MenuEntry(2, 'Champagne Ham & Cheese', '.50'))
_menu.append(MenuEntry(3, 'Beef & Onion', '.50'))
_menu.append(MenuEntry(40, 'Pepperoni', '.50'))
_menu.append(MenuEntry(100, 'Simply Cheese', '.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 .50
2 Champagne Ham & Cheese .50
3 Beef & Onion .50
40 Pepperoni .50
100 Simply Cheese .50
""""""""""""""""""""""""""""
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 ")
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 ")
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 ")
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")