我的代码中包含了一切(我认为),除了我从字典中获取正确名称的部分。
我的代码是:
studentdirectory = {"Andrew": ["Jane", "John"], "Betsy": ["Ellen", "Nigel"], "Louise": ["Natalie", "Louis"], "Chad": ["Mary", "Joseph"]}
def menu():
print
print ("Enter 1 to retrieve the mother's name of the child.")
print ("Enter 2 to retrieve the father's name of the child.")
print ("Enter 3 to retrieve the name of both parents of the child.")
print ("Enter 0 to quit.")
print
while True:
choice = input("Enter your choice now: ")
if (choice >= 0) and (choice<= 3) and (int(choice) == choice):
return choice
else:
print ("Your choice is invalid. Please try again with options 0 to 3.")
for key in studentdirectory:
mom = studentdirectory[key][0]
dad = (studentdirectory[key][1])
def main():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Enter the name of the child: ")
if studentdirectory.has_key(name):
if choice == 1:
print "The name of the child's mother is ", mom, "."
elif choice == 2:
print "The name of the child's father is ", dad, "."
else:
print "The name of the child's parents are ", mom, " and ", dad, "."
else:
print "The child is not in the student directory."
main()
我想让我的代码尽可能接近这一点。我只需要帮助理解如何在字典中获得单独的值,因为现在对于每个妈妈和爸爸我只会让路易丝的父母回来。我该如何解决?? 这是Python语言。
答案 0 :(得分:0)
if studentdirectory.has_key(name):
mom = studentdirectory[key][0]
dad = (studentdirectory[key][1])
并删除for key in studentdirectory
循环部分
因为当您在主循环中获得学生姓名时。您的原始代码仅返回const mom
和dad
变量,它来自for
循环上方的main()
循环定义。
逻辑上
您只能在之后获得姓名的父母姓名
答案 1 :(得分:0)
您在循环中获取mom
和dad
的值,但每次都会覆盖它们,因此它们始终设置为最后一个循环周期的值(路易斯在你的情况下)。您只应在需要时定义它们:
def main():
while True:
choice = menu()
if choice == 0:
break
else:
name = raw_input("Enter the name of the child: ")
if studentdirectory.has_key(name):
mom = studentdirectory[name][0]
dad = studentdirectory[name][1]
if choice == 1:
print "The name of the child's mother is ", mom, "."
elif choice == 2:
print "The name of the child's father is ", dad, "."
else:
print "The name of the child's parents are ", mom, " and ", dad, "."
else:
print "The child is not in the student directory."