简体   繁体   中英

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

The most succinct way to accomplish this is to bin the ages, determine which bin a given age falls into, and then use the index to return the price.

  • np.digitize accomplishes that task
    • the parameter bins , contains the ages, and determines which index in the list, a given value fits into. bins is exclusive, therefore the ranges are 0-4, 5-9, 10-17, 18-65 and 66+.
    • the ranges correspond to index 0, 1, 2, 3, and 4.
  • idx is used to return the corresponding price per age range
  • Use a function to return the cost, instead of a bunch of if-elif statements
  • The directions in yellow, don't require the name or the age of the person to be returned.
  • Everything required to print at the end, can be calculated from maintaining a list of cost, containing the price of each customer.
  • print(f'some string {}') is an f-String
  • Type Hints are used in functions (eg 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}')

Output:

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

If not allowed to use 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}')

Notes:

  • Don't use break in all the if-elif conditions, because that breaks the while-loop
  • Anytime you're repeating something, like calculating price, write a function.
  • Familiarize yourself with python data structures , like list and dict
  • this one needs to have the amounts added all together and I'm not sure how.
    • list.append(price) in the loop
    • sum(list) to get the total

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM