使用输入确定在Python中调用哪个函数

2024-04-19 04:00:54 发布

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

我应该创建一个名为menu的函数,它将显示菜单,检查输入是否有效,如果无效,请用户再次输入。如果输入正确,则返回值。你知道吗

我知道参数必须是int,但如何使它接受用户的输入,然后相应地显示函数?这就是我目前所拥有的。你知道吗

def menu(choice):
    print("===============================================")
    print("Welcome to Students' Result System")
    print("===============================================")
    print("1: Display modules average scores")
    print("2: Display modules top scorer")
    print("0: Exit")
    choice=int(input("Enter choice:"))
    while (choice=="" or choice!=0 or choice!=1 or choice!=2):
        print("Invalid choice, please enter again")
        choice=int(input("Enter choice:"))
        return choice
    if choice ==1:
        display_modules_average_scores()
    elif choice ==2:
        display_modules_top_scorer()
    elif choice==0:
        print("Goodbye")

def display_modules_average_scores():
    print("average")

def display_modules_top_scorer():
    print ("top")

def main():
    menu(choice)

main()

Tags: or函数用户modulestopdefdisplayint
1条回答
网友
1楼 · 发布于 2024-04-19 04:00:54

您所呈现的代码中有几个错误:

  1. Python是一种对空格敏感的语言。您需要缩进代码,以便与函数相关的代码包含在比它关联的def声明更高的缩进级别。你知道吗
  2. 您已经将choice定义为menu函数的输入,并且正在使用main()方法调用menu()。但是,choice此时不是已定义的变量,在接受用户的输入之前,它不会在代码中定义。因此,在尝试使用此调用时,代码将失败。你知道吗

    按照当前设置此代码的方式,您只需在定义和调用中删除choice作为menu()的输入,菜单将按预期显示。

  3. 在创建条件语句时,您似乎也有误解。由or连接的条件将不会在返回true的第一个条件之后计算。因此,菜单选择1将使条件choice!=0TRUE,并且将始终进入Invalid choice状态。你知道吗

    如果您对验证用户的输入感兴趣,您可能需要考虑使用^ {CD15>}关键字:

    链接数值比较(在空白字符串检查之后)。
    while (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
    

解决了所有这些问题后,您的代码将更像以下内容:

def menu():
  print("===============================================")
  print("Welcome to Students' Result System")
  print("===============================================")
  print("1: Display modules average scores")
  print("2: Display modules top scorer")
  print("0: Exit")
  choice=int(input("Enter choice:"))
  while (choice=="" or (choice!=0 and choice!=1 and choice!=2)):
      print("Invalid choice, please enter again")
      choice=int(input("Enter choice:"))
      return choice
  if choice ==1:
      display_modules_average_scores()
  elif choice ==2:
      display_modules_top_scorer()
  elif choice==0:
      print("Goodbye")

def display_modules_average_scores():
    print("average")

def display_modules_top_scorer():
    print ("top")

def main():
    menu()

main()

Repl.it

相关问题 更多 >