如何让“一级”函数在不断崩溃时运行?

2024-04-26 20:16:59 发布

您现在位置:Python中文网/ 问答频道 /正文

当程序运行时,它会通过菜单和播放功能,但当它到达“一级”功能时会崩溃,因为它声明存在名称错误。你知道吗

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

程序应该运行所有功能,包括“levelone”,其中用户必须输入显示的数字。但是,它崩溃了,说它没有定义。这个问题怎么解决?你知道吗


Tags: orthe功能inputifdefrootarray
1条回答
网友
1楼 · 发布于 2024-04-26 20:16:59

在play()中的第27行调用levelOne()函数之前,需要将第56行的levelOne()函数的定义移动到要定义的位置。由于menu()和play()等都是在函数本身中调用的,因此您可能还需要删除对方法的重复调用。你知道吗

说明:

请注意,Python解释器将到达第33行的menu(),然后在menu()内调用第13行的play(),然后尝试调用第27行的levelOne(),但此时尚未定义levelOne()。你知道吗

相关问题 更多 >