Search code examples
pythonfunctionpygamenameerror

how do i get the 'level one' function to run as it keeps crashing?


when the program is run, it goes through the menu and the play function but crashes when it gets to the 'level one' function as it states that there is a name error.

def main():
   menu()

def menu():
   print()

   choice = input("""
                   A: Play
                   Q: Exit
                   Please enter your choice: """)

   if choice == "A" or choice =="a":
     play()
   elif choice=="Q" or choice=="q":
     sys.exit
   else:
     print("You must only select either A or Q")
     print("Please try again")

def play():
    choice = input("""
                   A: Level One
                   Q: Exit
                   Please enter your choice: """)

    if choice == "A" or choice =="a":
       levelOne()
    elif choice=="Q" or choice=="q":
       sys.exit
    else:
        print("You must only select either A or Q")
        print("Please try again")
menu()
main()

import random
array = []

for i in range(3):
  randomNumber = random.randint(0,100)
  array.append(randomNumber)

# this function displays the random number for 1250 milliseconds
def randomNumberDisplay():
  import tkinter as tk
  root = tk.Tk()
  root.title("info")
  tk.Label(root, text=array).pack()
  # time in ms
  root.after(2150, lambda: root.destroy())
  root.mainloop()   
randomNumberDisplay()

#this function requires the user to enter the numbers displayed.
score = 0
def levelOne():
  incorrect = 0
  for i in range (3):
     userNumber = int(input("please enter the numbers you saw IN ORDER(press Enter when finished): "))

  #if they enter the right number, they gain a score and get to move to the next level
  if userNumber != array:
      print ("the numbers where: ", array)
      incorrect = incorrect +1
      print("you got ", incorrect, "wrong")
  else:
      score += 100
      i = i + 1
      print ("you have ",score, "points")
levelOne()
play()

the program should run through all functions including 'levelone' where the user has to input the numbers shown. However, it crashes saying that it's not defined. How can this be solved?


Solution

  • You need to move the definition of the levelOne() function at line 56 to be defined before you call it on line 27 in play(). You may also want to remove the repeated calls to your methods since menu() and play() etc. are called within your functions themselves.

    Explanation:

    Notice that the Python interpreter will arrive at menu() on line 33, then inside menu() it will call play() at line 13, then it will try to call levelOne() at line 27 but levelOne() has not been defined at this point.