题目:
题目来源:
Python编程快速上手——让繁琐工作自动化(第二版)第8章:8.6.1三明治机
编写一个程序,向用户询问他们的三明治偏好。层序应使用
PyInputPlus
模块来确保用户输入的有效。
- 对面包类型使用
inputMenu()
:wheat、white、sourdough。- 对蛋白质类型使用
inputMenu()
:chicken、turkey、ham、tofu。- 用
inputYesNo()
询问他们是否要:cheese。- 如果需要cheese,请使用
inputMenu()
询问cheese的类型:cheddar、Swiss、mozzarella。- 用
inputYesNo()
询问他们是否需要mayor、mustard、lettuce、tomato。- 用
inputInt()
询问他们想要多少个三明治。确保这个数字大于等于1.
列出每一个选项的价格,并在用户输入选择后让程序显示总费用。
解答:【解答为自己编写的。】
'''第〇步:导入模块'''
import pyinputplus as pyip
'''第一步:定义各个选项的价格'''
# 面包类型价格
bread_prices = {
"wheat": 2.0,
"white": 1.5,
"sourdough": 2.5
}
# 蛋白质类型价格
protein_prices = {
"chicken": 3.0,
"turkey": 2.5,
"ham": 3.5,
"tofu": 2.0
}
# 芝士类型价格
cheese_prices = {
"cheddar": 1.5,
"Swiss": 2.0,
"mozzarella": 1.8
}
# 其他配料价格
extras_prices = {
"mayor": 0.5,
"mustard": 0.3,
"lettuce": 0.2,
"tomato": 0.4
}
'''第二步:获取用户输入'''
# 获取面包类型
bread_type = pyip.inputMenu(["wheat", "white", "sourdough"], prompt="请选择面包类型: ")
# 获取蛋白质类型
protein_type = pyip.inputMenu(["chicken", "turkey", "ham", "tofu"], prompt="请选择蛋白质类型: ")
# 询问是否要芝士
if pyip.inputYesNo("是否需要芝士? (yes/no) ") == "yes":
cheese_type = pyip.inputMenu(["cheddar", "Swiss", "mozzarella"], prompt="请选择芝士类型: ")
else:
cheese_type = None
'''第三步:询问是否需要其他配料'''
if pyip.inputYesNo("是否需要蛋黄酱? (yes/no) ") == "yes":
mayor_needed = True
else:
mayor_needed = False
if pyip.inputYesNo("是否需要芥末酱? (yes/no) ") == "yes":
mustard_needed = True
else:
mustard_needed = False
if pyip.inputYesNo("是否需要生菜? (yes/no) ") == "yes":
lettuce_needed = True
else:
lettuce_needed = False
if pyip.inputYesNo("是否需要番茄? (yes/no) ") == "yes":
tomato_needed = True
else:
tomato_needed = False
'''第四步:获取用户想要的三明治数量'''
num_sandwiches = pyip.inputInt("请输入您想要的三明治数量(大于等于 1): ", min=1)
'''第五步:计算总费用'''
total_cost = 0
total_cost += bread_prices[bread_type]
total_cost += protein_prices[protein_type]
if cheese_type:
total_cost += cheese_prices[cheese_type]
if mayor_needed:
total_cost += extras_prices["mayor"]
if mustard_needed:
total_cost += extras_prices["mustard"]
if lettuce_needed:
total_cost += extras_prices["lettuce"]
if tomato_needed:
total_cost += extras_prices["tomato"]
total_cost *= num_sandwiches
print(f"您的订单总费用为: {total_cost} 元")