实际上我有一个问题,因为我想在一个函数内创建一个列表,但它取决于变量,我的意思是...用输入我想定义变量的值,用我模拟程序的代码餐馆的桌子上,我应该能够将他们要的食物添加到每个桌子的列表中。现在这是我的代码:
foodlist = []
table_1 = []
table_2 = []
table_3 = []
table_4 = []
table_5 = []
table_6 = []
p = 0
def openFile():
file = open("cartarest.txt","r",1,"utf-8")
line = file.readline().strip()
while line != "":
parts = line.split(";")
name = parts[0]
price = int(parts[1])
type = parts[2]
foodlist.append(parts)
line = file.readline().strip()
p += 1
return (foodlist,p)
def serveTable(x):
print("The menu of the restaurant is:")
print(foodlist)
add = input("Which food do you want to add?: ")
while add != 0:
for i in range(p):
if add.lower() == foodlist[i][0]:
**table_+x.append(foodlist[i])**
add = input("Which food do you want to add?: ")
openFile()
tableserve = input("What table do you want to attend?")
while tableserve.lower() != "cerrar":
serveTable(tableserve)
tableserve = input("What table do you want to attend?")
编辑:我已经解决了变量'p'的问题,但是现在我有一个问题,如何限制表的范围,因为我尝试放置“ -1”之类的值并且代码正常运行,它不应该只在1到6之间的值上起作用(显然使用@Tim的答案)
答案 0 :(得分:3)
使用6个表变量,而不是6个表变量,并将表号作为索引传递:
tables = [[] for _ in range(ntables)]
def serveTable(x):
print("The menu of the restaurant is:")
print(foodlist)
add = input("Which food do you want to add?: ")
while add != 0:
for i in range(p):
if add.lower() == foodlist[i][0]:
tables[x].append(foodlist[i])
add = input("Which food do you want to add?: ")