【发布时间】:2015-05-01 03:05:44
【问题描述】:
我试图在另一个函数中调用我在一个函数中创建的列表,但我收到未定义列表的错误。当我尝试执行 Menu = The_menu() 时,它会在函数内运行 while 循环。当我调用 Restaurant_str 时出现问题
from collections import namedtuple
Restaurant = namedtuple('Restaurant', 'name cuisine phone menu')
Dish = namedtuple("Dish", "name price calories")
# Constructor: r1 = Restaurant('Taillevent', 'French', '01-11-22-33-44', 'Escargots', 23.50)
def Restaurant_str(self: Restaurant) -> str:
return (
"Name: " + self.name + "\n" +
"Cuisine: " + self.cuisine + "\n" +
"Phone: " + self.phone + "\n" +
"Menu: " + Dishlist_display(Menu))
def Restaurant_get_info() -> Restaurant:
""" Prompt user for fields of Restaurant; create and return.
"""
return Restaurant(
input("Please enter the restaurant's name: "),
input("Please enter the kind of food served: "),
input("Please enter the phone number: "), The_menu())
def The_menu():
""" Creates the menu that replaces dish in Restaurant.
"""
Menu = []
while True:
x = input("Please enter the name of a Dish: ")
if x == "No more":
break
y = float(input("Please enter the price of that Dish: "))
z = float(input("Please enter the calorie count of that Dish: "))
Menu.append(Dish(x, y, z))
return Menu
def Dish_str(x:Dish) -> str:
""" Takes a Dish and returns a string with name, price, and calories listed.
"""
return (x.name + " ($" + str(x.price) + "): " + str(x.calories) + " cal")
def Dishlist_display(x:list) -> str:
"""Takes a list of Dishes and returns one large string consisting of the string representation of each dish followed by a newline character
"""
dish = ""
for i in x:
dish = dish + Dish_str(i) + ("\n")
return dish
这是回溯,
Traceback (most recent call last):
File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 193, in <module>
restaurants()
File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 15, in restaurants
our_rests = handle_commands(our_rests)
File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 43, in handle_commands
print(Collection_str(C))
File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 128, in Collection_str
s = s + Restaurant_str(r)
File "C:\Users\jayjay\Documents\ICS 31\Lab 5\restaurantsd.py", line 76, in Restaurant_str
"Menu: " + Dishlist_display(Menu))
NameError: name 'Menu' is not defined
【问题讨论】:
-
您应该标记编程语言。这看起来像 Python?
-
哦,好的,谢谢@user1032613
-
能否请您复制并粘贴实际的回溯?
-
你在哪里
Dishlist_display(Menu)?如果它在这个函数之外,它不能访问这个函数的局部变量Menu。但是既然你做了一个return Menu,那么大概你把它存储在某个地方,并且可以从某个地方访问它。