我刚刚开始学习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'
答案 0 :(得分:0)
您的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
答案 1 :(得分:0)
原因是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
答案 2 :(得分:0)
您的get_order()
函数没有return
语句。结果,它将始终返回None
。因此,在main()
中:
orders = get_order(menu)
total = bill_total(orders, menu)
orders
将获得一个值None
,然后将其传递给bill_total()
。当您尝试在for循环中进行迭代时,结果就是您所看到的异常
答案 3 :(得分:0)
最新答案,但您可以使用:
// existing unmanaged code
class UnmanagedClass
{
public:
void SomeMethod();
};
// a C++ CLR
ref class ManagedWrapper
{
public:
void SomeMethod()
{
obj->SomeMethod();
}
private:
UnmanagedClass* object;
};