Я только начинаю изучать python и написал скрипт с тремя функциями. После прохождения ввода Q я получаю сообщение об ошибке Traceback.
Это просто обучающее упражнение, чтобы я мог развивать свои навыки Python. Исходный код учебного модуля и мой код кажутся абсолютно одинаковыми, но по какой-то причине мой вывод возвращает ошибку.
File "C:\Users\Desktop\DearWorld\new.py", line 36, in <module>
main()
File "C:\Users\Desktop\DearWorld\new.py", line 33, in main
total = bill_total(orders, menu)
File "C:\Users\Desktop\DearWorld\new.py", line 24, in bill_total
for order in orders:
TypeError: 'NoneType' object is not iterable
menu = {'Angel Dust Blunt': 6.66, 'The OG Blunt': 4.20, 'Caviar Blunt': 7.10, 'The Chronic Blunt' : 4.20}
def print_menu(menu):
for name, price in menu.items():
print(name, ': $', format(price, '.2f'), sep = '')
def get_order(menu):
orders = []
order = input("What would you like to order (Q to quit)")
while (order.upper() != 'Q'):
#Find the order and add it to the list if it exists
found = menu.get(order)
if found:
orders.append(order)
else:
print("Menu item doesn't exist")
order = input("Anything else? (Q to Quit)")
def bill_total(orders, menu):
total = 0
for order in orders:
total += menu[order]
return total
def main():
menu = {'Angel Dust Blunt': 6.66, 'The OG Blunt': 4.20, 'Caviar Blunt': 7.10, 'The Chronic Blunt' : 4.20}
print_menu(menu)
orders = get_order(menu)
total = bill_total(orders, menu)
print("You ordered:" ,order, "Your total is: $", format(total, '.2f'), sep='')
main()
The script is supposed to return the bill_total and the items ordered as the output. What is returned instead when the user enters 'Q' is a 'TypeError'
Ваша функция get_order
ничего не возвращает, поэтому значение orders
в строке:
orders = get_order(menu)
будет None
. Затем вы пытаетесь перебрать переменную, и это не удастся.
Вам нужно добавить эту строку в конец функции get_order
:
return orders
Таким образом, функция должна выглядеть так:
def get_order(menu):
orders = []
order = input("What would you like to order (Q to quit)")
while (order.upper() != 'Q'):
#Find the order and add it to the list if it exists
found = menu.get(order)
if found:
orders.append(order)
else:
print("Menu item doesn't exist")
order = input("Anything else? (Q to Quit)")
return orders # Added this line
Причина в том, что orders
— это None
, и это потому, что функция get_order
ничего не возвращает.
посмотрите на эту строку:
orders = get_order(menu)
вы должны добавить:
return orders
в конце функции get_order
. так:
def get_order(menu):
orders = []
order = input("What would you like to order (Q to quit)")
while (order.upper() != 'Q'):
#Find the order and add it to the list if it exists
found = menu.get(order)
if found:
orders.append(order)
else:
print("Menu item doesn't exist")
order = input("Anything else? (Q to Quit)")
return orders
Отлично, теперь я получаю вывод NameError: имя «порядок» не определено. Ошибка указывает мне на строку 36 в файле main. Это из-за того, что я что-то делаю неправильно перед этой строкой кода?
В вашей get_order()
функции нет оператора return
. В результате он всегда будет возвращаться None
. Поэтому в main()
:
orders = get_order(menu)
total = bill_total(orders, menu)
orders
получит значение None
, которое затем будет передано bill_total()
. Когда вы пытаетесь повторить это в цикле for, результатом является исключение, которое вы видите
Поздний ответ, но вы можете использовать:
menu = {
"1": {"name":"Angel Dust Blunt", "price":6.66},
"2": {"name":"The OG Blunt", "price":6.66},
"3": {"name":"Caviar Blunt", "price":7.10},
"4": {"name":"The Chronic Blunt", "price":4.20}
}
orders = []
def print_menu():
for k, v in menu.items():
print(f"[{k}] - ", v['name'], ': $', format(v['price'], '.2f'), sep = '')
def bill_total():
total = 0
for id in orders:
total += menu[id]['price']
return total
def get_order():
while 1:
order = input(f"What would you like to order (Q to quit)\n")
if order.strip().upper() == 'Q':
return
else:
found = menu.get(order)
if found:
# avoid dup orders, can be improved to increase the count of product items.
if order in orders:
print("Product already in cart")
continue
orders.append(order)
print(f"Item {found['name']} added to cart")
else:
print("Menu item doesn't exist")
print_menu(), get_order(), print("You ordered:\n")
for id in orders:
print(menu[id]['name'], f"${menu[id]['price']}")
print(f"\nYour total is: ${bill_total()}" )
get_order
неreturn
ничего…