2017-09-23 130 views
0

我有這個程序,我希望它通過每個菜單選項運行。基本上用戶登錄,出現菜單並按下其中一個。但是當我按2時,它告訴我'搜索學生沒有定義'我不明白它在說什麼。我試圖在程序中移動該功能,但如果我這樣做,我會得到其他錯誤。我正在尋找什麼是正確的方式來構建這個。功能是否在菜單之前?並在登錄後?那我怎麼能和應該打電話給他們呢?NameError:名稱''未定義

choice = input 
def PrintMenu(): 
    print("\n*******************") 
    print("\n School menu system") 
    print("\n*******************") 
    print(" [1] Add Student") 
    print(" [2] Search Student") 
    print(" [3] Find Report") 
    print(" [4] Exit") 
    choice = input ("Enter a choice: ") 
#while choice =='': 
    if choice == '1': 
     AddStudent() 
    elif choice == '2': 
     SearchStudent(ID) 
    elif choice == '3': 
     FindReport() 
    elif choice == '4': 
     print("\nExiting the system......\n") 
     sys.exit(0) 
    else: 
      print ("\n not valid choice") 
PrintMenu() 
def SearchStudent(ID): 
    with open("Students.txt", 'r') as file: 
     for i in file: 
      data = i.rstrip().split(",") 
      if data[0] == ID: 
       return "The student you require is: {} {}".format(data[2], data[1]) 
    return "No matches found" 
search = input("Please enter a student ID: ") 
print(SearchStudent(search)) 

回答

0

您應該在您的主要功能之前放置SearchStudent(ID)。在Python中,必須在調用它們之前定義之前的東西(例如函數)

主要部分必須遵循您要使用的功能。鑑於您的登錄功能應該是主要功能,您必須讓程序知道它。添加到您的代碼的末尾:

if __name__== "__main__": 
    yourMainFunction() 

您的代碼將最有可能是這樣的:

def FindReport(args): 
    #What it's going to do 

def SearchStudent(args): 
    #What it's going to do 

def AddStudent(args): 
    #What it's going to do 

def PrintMenu(): 
    #What it's going to do 

def Login(): 
    #Your main function 

if __name__ == "__main__": 
    Login() 
+0

我不明白的地方在代碼中的主要部分是,雖然還是需要的地方走。在菜單之前有一個登錄功能,然後有addstudent功能,我試着把它放在菜單前後,它仍然會出現相同的錯誤。 – CV9

+0

@cᴏʟᴅsᴘᴇᴇᴅ有什麼想法?或建議? – CV9

+0

我更進一步的幫助更新了答案。 –