Reputation: 95
actually I have a problem because I want to create a list inside a function but it depends on a variable, I mean... with a input I want to define the value of the variable, with the code I simulated the program of a restaurant to serve a table and I should be able to add to the list of each table, the food they ask. This is my code now:
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?")
EDIT: I have solved the problem with the variable 'p' but now I have a question, how to restrict the range of the tables, because i have tried to put a value like "-1" and the code runs normally, it shouldn't work, just with values between 1 and 6(obviously using the answer of @Tim)
Upvotes: 2
Views: 216
Reputation: 2843
Instead of 6 table variables, use a list of lists, and pass your table number as an index:
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?: ")
Upvotes: 3