pythonfunctionmenuprocedures

NameError: name ' ' is not defined


I have this program and I would like it to run through each menu option. Basically the user logs in, the menu appears and pressing one works. However when I press 2 it tells me that 'Search Student is not defined' I don't understand what it is talking about. I have tried to move the function around in the program but I get other errors if I do that. I am looking for what is the right way to structure this. Do the functions go before the menu? and after the login? then how can and should I call them up?

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))

Solution

  • You should place SearchStudent(ID) before your main function. In Python, things (such as functions) must be defined before you call them.

    The main section must go after the functions you're going to use. Given your login function should be the main function, you must let the program know it. Add this to the end of your code:

    if __name__== "__main__":
      yourMainFunction()
    

    Your code will most likely look like this:

    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()