使用if语句将对象实例附加到列表中,然后在另一个分支中打印它



我创建了一些关于宠物的类,下面的代码是我的main((函数的一部分,首先,让用户选择他们想做的一件事。那就是,如果使用输入"1",他们会添加一些宠物实例。同时,我想将宠物实例的部分信息附加到一个列表中。然后,如果用户选择读取此信息。我想在另一个if语句分支中打印它。即当用户输入"2"时。当我在已经生成了一些宠物实例之后输入2时,问题就会出现。名为lweight的列表总是无效的。我该怎么修?我已经尝试使用全局列表,但不起作用

def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1: 
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the  name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)      
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
return main()
elif a==2:  
for i in l_weight:
print(i)

return main()

l_weight((没有追加的原因是,在您的代码中,您将列表命名为l_weight,然后在代码的其余部分中,它被写为l_weigh

应该是:

def main():
l_weight=[]
print("========menu=========")
print("1. to add a pet")
print("2. print current weight for all pet")
print("3. print all pets and owners")
print("4. to exist system")
a=int(input("you selection(just input the number before each function)"))
while(True):
if a==1: 
a=int(input("please select what type of pet would be added: 1-- mammals 2--fish 3--amphibians"))
name = input('please enter the  name of pet:')
dob = input('please enter the dob of pet:(year,month,day)')
bw = input('please enter the birth weight:')
name = input('please enter the owner name:')
address = input('please enter the onwer address:')
if a==1:
ls = input('please enter the litter size:')
hs = input('pet has claws(yes or no):')
op=mammals(name,dob,bw,name,address,ls,hs)
print(op)
l_weight.append(op.get_current_weight)      
elif a==2:
sc = input('please enter the scale condition:')
sl = input('please enter the scale length:')
op =fish(name,dob,bw,name,address,sc,sl)
print(op)
l_weight.append(op.get_current_weight)
elif a==3:
iv = input('is venomous(yes or no):')
op =amphibians(name,dob,bw,name,address,iv)
print(op)
l_weight.append(op.get_current_weight)
else:
print(' input wrong vaule,please choose a number from 1,2 or 3')
elif a==2:  
for i in l_weight:
print(i)

相关内容

最新更新