我想調用我在另一個函數中的函數內創建的列表,但是我得到列表未定義的錯誤。當我試圖做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
哦好吧謝謝@ user1032613 – jjm318
你能複製並粘貼實際的回溯? – logic