2015-04-16 43 views
0

我的代碼(我認爲)中除了從我的字典中得到正確名稱的部分外,我擁有一切權利。我無法從我的字典中獲得正確的值。有什麼建議麼?

我的代碼是:

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
if studentdirectory.has_key(name): 
    mom = studentdirectory[key][0] 
    dad = (studentdirectory[key][1]) 

,並刪除for key in studentdirectory環路部分

因爲當你在主loop.Your原代碼得到學生的名字只返回一個const momdad varible,它來自於你for環路main()以上認定中。

和邏輯

你只能得到父母的名字你有孩子的名字

+0

謝謝!這工作! – Maddie

+0

@Maddie很高興爲您效勞 – amow

0

你得到一個循環的momdad值,但覆蓋它們每一次,所以他們總是設置爲最後一個循環的值(在你的情況下,路易絲)。你應該定義它們,當你只需要它們時:

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." 
+0

非常感謝!這解決了它! – Maddie

相關問題