首页 > 解决方案 > How do I make this code loop into dictionaries and not continue looping in python?

问题描述

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}.")

标签: pythonpython-3.xloopsdictionaryinput

解决方案


最简洁的方法是对年龄进行分类,确定给定年龄属于哪个分类,然后使用索引返回价格。

  • 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数据结构,比如listdict
  • 这个需要把所有的金额加在一起,我不知道怎么做。
    • list.append(price)在循环
    • sum(list)得到总数

推荐阅读