Python验证检查不正确

2024-09-29 17:18:18 发布

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

我有一些验证检查我的菜单,似乎是重复的错误信息,我花了这么长时间盯着这个错误,我似乎已经变成一片空白!你知道吗

我正在运行一个名为student\u class的文件(不是类,只是文件名),作为任何菜单验证,如果用户输入错误的选项,我希望它显示错误消息,然后重新显示菜单等

验证代码为:

def ValidateMenuChoice(choice):
  validchoice = False
  Num = [1,2,3,4,5,6]
  while validchoice == False :
    if choice not in Num:
      print("Invalid choice, please try again.")
      display = menu.Menu("Student")
      display.printMenu()
      GetMenuChoice()
      ValidateMenuChoice(choice)
    else:
      validchoice = True
  return choice

我犯的是一个简单的错误还是更复杂的错误?任何帮助都将不胜感激。你知道吗

GetMenuChoice函数:

def GetMenuChoice(): #Gets users menu choice
  MenuChoice = int(input())
  print()
  return MenuChoice

答案编辑:

使用下面的一些答案(谢谢!)我只需在代码中添加main(choice),如下所示:

def ValidateMenuChoice(choice=None):
  Num = [1,2,3,4,5,6]
  while True:
    if choice not in Num:
      print("Invalid choice, please try again.")
      display = menu.Menu("Student")
      display.printMenu()
      choice = GetMenuChoice()
      main(choice) #Added to make it work
    else:
      return choice

感谢您的帮助:)


Tags: 代码falsereturndef错误display菜单num
2条回答

我认为你需要做一个简单的调整:

choice = GetMenuChoice()

目前,您从未更新choice,因此它无限期地递归。你知道吗

更广泛地说,我可能会采用迭代方法,并避免使用标志(validchoice):

def GetValidMenuChoice():
    display = menu.Menu("Student")
    while True:
        display.printMenu()
        choice = GetMenuChoice()
        if choice in range(1, 7):
            return choice
        else:
            "Invalid choice, please try again."

理想情况下,我会删除硬编码的range(1, 7),并使其依赖于Menu,但我无法从您发布的内容判断这是否可行。你知道吗

您正在尝试迭代和递归方法,但没有正确跟踪choicevalidchoice变量。你知道吗

对于正确的递归方法,去掉while并添加return

def ValidateMenuChoice(choice):
  Num = [1,2,3,4,5,6]
  if choice not in Num:
      print("Invalid choice, please try again.")
      display = menu.Menu("Student")
      display.printMenu()
      choice = GetMenuChoice()
      return ValidateMenuChoice(choice)
  return choice

迭代方法如下所示:

def ValidateMenuChoice(choice=None):
  Num = [1,2,3,4,5,6]
  while True:
    if choice not in Num:
      print("Invalid choice, please try again.")
      display = menu.Menu("Student")
      display.printMenu()
      choice = GetMenuChoice()
    else:
      return choice

相关问题 更多 >

    热门问题