我目前正在开发一个程序,用户可以在其中订购披萨。我在以最佳方式从字典中获取特定价值并将其放入列表中时遇到了一些问题,最终可以用来为客户提供最终的总计。
我的问题是:我将如何获取用户输入的内容,将其与“键”进行匹配并将“值”附加到列表中,以便以后用于用户最终总计。 < / p>
这是我目前拥有的字典:
sizePrice = {
'small': 9.69,
'large': 12.29,
'extra large': 13.79,
'party size': 26.49
}
我写的一个例子:
class PizzaSize():
"""" Takes the customers size requested and returns total cost of that pizza size"""
sizePrice = {
'small': 9.69,
'large': 12.29,
'extra large': 13.79,
'party size': 26.49
}
ordered_size= []
def size(self):
self.size_wanted = input("What size pizza would you like? ")
self.size_wanted = self.size_wanted.title()
customer_size = self.size_price[self.size_wanted]
odered_size.append(customer_size)
order = PizzaSize()
order.size()
我知道上面的代码是错误的,但是,我正在寻找能使我朝正确方向发展的任何事物。
答案 0 :(得分:1)
未经全面测试,但是这是一种通过注释来解释思想过程的方法:(请注意,您可以用更少的代码实现相同的目标,但是编写具有简单对象和明确定义的属性的代码可以使操作起来更加容易保持较大的应用程序,因此是一个很好的习惯)
# We'll ask the user for a number since those are easier to input,
# especially in console applications without auto-complete/other visual feedback.
# Ideally I would suggest looking into Enums,
# but I'm guessing you're just starting out so this should suffice
size_mappings = {
1: "small",
2: "large",
3: "extra large"
}
# Note that we could have mapped numbers to prices as well,
# but it's not very readable. Readability is supreme. Enums solve this problem.
cost_mappings = {
"small": 6,
"large": 10,
"extra large": 12
}
# I like my objects simple, and designing classes etc. comes with practice
# but intuitively I would want Pizza as one object with a single size property
# Cost could also have been a property but this application is simple enough
# and I didn't see a need to make a part of the object,
# especially since we already have a mapping declared above.
# In general you want objects to have properties and methods to access
# those properties. A pizza can have a size,
# and the way you get the pizza's size is by calling get_size()
class Pizza():
def __init__(self, size):
self.size = size
def set_size(self, size):
self.size = size
def get_size(self):
return self.size()
def get_cost(self):
return cost_mappings[self.size]
# Once again, intuitively an order can have multiple pizzas, so we
# construct an order object with a list of pizzas.
# It's an object with a property to add pizzas to it,
# as well as compute the order total (which is what you wanted to do).
# To compute the total, we go through all the pizzas in the order,
# access their cost and return the total.
class Order():
def __init__(self):
self.pizzas = []
def addPizza(self, pizza):
self.pizzas.append(pizza)
def getTotal(self):
total = 0
for pizza in self.pizzas:
total += pizza.get_cost()
return total
# start processing the order
order = Order()
# This is an infinite loop, implying the user can continue adding pizzas
# until they are satisfied, or dead from heart disease (*wink*)
while True:
try:
# Need a way to exit the loop, here it is by pressing q and then enter
response = input("What size pizza would you like?\n\
(1: small | 2: large | 3: extra large)\n \
Press q to finish order and compute the total\n"
)
# This is where we check if the user is done ordering
if response == 'q':
break
# The input is taken in as a string,
# convert it to an integer for processing
# since our dictionary has integers as keys
size_wanted = int(response)
# A few things going on here.
# Lookup the string version of the size we stored in the dictionary
# Construct a pizza with a specific size, "small", "large" etc.
# The pizza object gets stored inside the order object
# through the addPizza method
size_wanted = size_mappings[size_wanted]
order.addPizza(Pizza(size_wanted))
except:
print("An error occurred, please try again")
# The beauty of OOP, the logic to compute the total is already there.
# Call it and be done.
print("Your total is: ", "$" + str(order.getTotal()))
如果您想进一步澄清,请随时告诉我!
根据要求进行澄清(请查看评论以获取解释):
如果要将while循环放入函数中,可以执行以下操作:
def run():
while True:
# code here
# Single function call in the entire file
# But you must have atleast one to make sure
# SOMETHING happens. Every other function can
# be called inside run(), the "main" function
run()