感谢您对此进行调查。我有一个项目,基本上是动物收容所的库存控制。我的采用功能有问题。我需要该函数附加到列表并将该列表返回给main函数,如果用户决定多次采用,它必须重复并更新列表。我的程序正在做的是每次再次运行采用函数时覆盖列表。不确定我做错了什么
#Steven Phu
#CSC 110, Spring 2017
#Animal Shelter
#This program keeps tracks of animals in an animal shelter. The program will
#access three different list and allows the user to manipulate what happens to
#the animals.
#main program calls upon function get_decision and gets return value of decision. It then runs if statements to see which function is appropriate for the input. While loop keeps running the program until user inputs quit.
#once program is out of while loop, it prints out the counter for each category
def main():
decision = get_decision()
adopted_counter = 0 #starting counters for adopted and transferred
transferred_counter = 0
pet_list = get_pet("pets.txt")
while (decision != "quit"):
elif (decision == "adopt"):
adopt = do_adopt(pet_list)
adopted_counter += 1
print(adopt)
print()
decision = get_decision()
for i in range(0, len(pet_list)):
current_counter = i
print(str(current_counter) + " pets currently in the shelter")
print(str(adopted_counter) + " adopted")
print(str(transferred_counter) + " transferred")
#Lists options of what the user can make and returns their decision to main function
def get_decision():
print("Welcome to animal shelter management software version 1.0!")
print("adopt: adopt a pet")
print("intake: add more animals to the shelter")
print("list: display all adoptable pets")
print("quit: exit the program")
print("save: save the current data")
print("transfer: transfer pets to another shelter")
decision = input("option? ")
while decision != "list" and decision != "adopt" and decision != "save" and decision != "quit" and decision != "transfer" and decision != "intake":
print("Not a valid option")
decision = input("option? ")
return decision
#opens pet file and breaks it down into a parts and puts it all together into a tuples and returns value
def get_pet(file):
f = open(file)
pet_info = f.readlines()
pet = []
for line in pet_info:
info = line.split()
pet_type = info[0]
name = info[1]
age = info[2]
pet.append((name, age, pet_type))
return pet
def do_adopt(pet_list):
decision_type = input("cat or dog? ")
decision_name = input("name? ")
adopt = []
i = 0
while i < len(pet_list):
if (pet_list[i][2] == decision_type):
if(pet_list[i][0] == decision_name):
pet = str(pet_list[i])
pet_list.pop(i)
adopt.append(pet)
return adopt
else:
i+=1
else:
i+=1
print("Not found")
return
main()
答案 0 :(得分:0)
列表被覆盖,因为您已在函数adopt = []
中声明do_adopt
,并且每次调用函数adopt
时都会分配一个新列表。解决方案:
pet_list = get_pet("pets.txt")
lst = [] # line to add
while (decision != "quit"):
和
adopt = do_adopt(pet_list)
lst.extend(adopt) # line to add
adopted_counter += 1
print(lst) # line to update