python - How do I make this code loop into dictionaries and not continue looping in python?
问题描述
- Write a program to calculate the cost of dinner
- If the person is under 5, dinner is free
- If the person is under 10, dinner is $5
- If the person is under 18, dinner is $10
- If the person is over 65, the dinner is $12
- All other dinners pay $15
- Calculate 8% tax
- Display the total for each diner, the number of diners, the average cost per diner, and the cumulative total for all diners
- Program should loop until exit is entered, with each loop a new diner is added and the total overall numbers updated
Is what I need to do. I'm not sure how to do it so the totals go into dictionaries and not loop.
I've done a similar question, but now this one needs to have the amounts added all together and I'm not sure how. This is the code I've done for a previous similar question. The problem I seem to be currently having i it wont go into the dictionary and there for wont print it at the end. I also need it to keep looping until I type quit.
dinner = {}
total ={}
name = input("What's your name? ")
age = input("What age is the person eating? ")
age = int(age)
amount = input("How many people that age? ")
amount = int(amount)
while True:
if name == 'quit':
print('Done')
break
elif age < 5:
price = 0 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age < 10:
price = 5 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age < 18:
price = 10 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
elif age > 65:
price = 12 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
else:
price = 15 * amount
tax = price * 0.08
dinner[name] = name
dinner[age] = age
total[amount] = price + tax
break
print("Thank you for having dinner with us! \nYour total is {total}, for {dinner}.")
解决方案
最简洁的方法是对年龄进行分类,确定给定年龄属于哪个分类,然后使用索引返回价格。
np.digitize
完成该任务- 参数
bins
,包含年龄,并确定列表中的哪个索引,给定值适合。bins
是独占的,因此范围是 0-4、5-9、10-17、18-65 和 66+。 - 范围对应于索引 0、1、2、3 和 4。
- 参数
idx
用于返回每个年龄段对应的价格- 使用函数返回成本,而不是一堆
if-elif
语句 - 黄色方向,不要求返回人的姓名或年龄。
- 最后打印所需的所有内容都可以通过维护成本清单来计算,其中包含每个客户的价格。
print(f'some string {}')
是一个f 字符串- 类型提示用于函数(例如
def calc_cost(value: int) -> float:
)。
import numpy as np
def calc_cost(value: int) -> float:
prices = [0, 5, 10, 15, 12]
idx = np.digitize(value, bins=[5, 10, 18, 66])
return prices[idx] + prices[idx] * 0.08
cost = list()
while True:
age = input('What is your age? ')
if age == 'exit':
break
cost.append(calc_cost(int(age)))
# if cost is an empty list, nothing prints
if cost:
print(f'The cost for each diner was: {cost}')
print(f'There were {len(cost)} diners.')
print(f'The average cost per diner was: {sum(cost)/len(cost):.02f}')
print(f'The total meal cost: {sum(cost):.02f}')
输出:
What is your age? 4
What is your age? 5
What is your age? 9
What is your age? 10
What is your age? 17
What is your age? 18
What is your age? 65
What is your age? 66
What is your age? exit
The cost for each diner was: [0.0, 5.4, 5.4, 10.8, 10.8, 16.2, 16.2, 12.96]
There were 8 diners.
The average cost per diner was: 9.72
The total meal cost: 77.76
如果不允许使用numpy
:
def calc_cost(value: int) -> float
return value + value * 0.08
cost = list()
while True:
age = input("What age is the person eating? ")
if age == 'exit':
break
age = int(age)
if age < 5:
value = 0
elif age < 10:
value = 5
elif age < 18:
value = 10
elif age < 66:
value = 15
else:
value = 12
cost.append(calc_cost(value))
if cost:
print(f'The cost for each diner was: {cost}')
print(f'There were {len(cost)} diners.')
print(f'The average cost per diner was: {sum(cost)/len(cost):.02f}')
print(f'The total meal cost: {sum(cost):.02f}')
笔记:
- 不要
break
在所有if-elif
条件下使用,因为这会破坏while-loop
- 每当您重复某些事情(例如计算价格)时,请编写一个函数。
- 熟悉python数据结构,比如
list
和dict
- 这个需要把所有的金额加在一起,我不知道怎么做。
list.append(price)
在循环sum(list)
得到总数
推荐阅读
- python - OSError:[Errno 22] 无效参数:“路径”
- rendering - 我们可以从窗口中读取 3D 切片器中的医学图像体积渲染中的体素吗
- python - 用于计算线段方位角的 Python 2.7 语法 - 不填充字段
- wordpress - WordPress 设置了一个自定义 cookie,其值取自 GET 参数
- react-native - 使用 M1 芯片 MacOS 上的自签名证书进行本机反应
- python - ModuleNotFoundError:没有名为“sklearn.ensemble.iforest”的模块
- python - 确定哪个数字列定义最精确
- node.js - 如何为 socket.io 中的每个房间生成自定义链接
- javascript - Javascript/React 如何从 Promise 中返回数据?
- selenium - 在 XPath 中,我如何在两个元素之间寻找一些东西?