我应该创建一个名为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()
您所呈现的代码中有几个错误:
def
声明更高的缩进级别。你知道吗您已经将
choice
定义为menu
函数的输入,并且正在使用main()
方法调用menu()
。但是,choice
此时不是已定义的变量,在接受用户的输入之前,它不会在代码中定义。因此,在尝试使用此调用时,代码将失败。你知道吗按照当前设置此代码的方式,您只需在定义和调用中删除
choice
作为menu()
的输入,菜单将按预期显示。在创建条件语句时,您似乎也有误解。由
or
连接的条件将不会在返回true
的第一个条件之后计算。因此,菜单选择1
将使条件choice!=0
TRUE
,并且将始终进入Invalid choice
状态。你知道吗如果您对验证用户的输入感兴趣,您可能需要考虑使用^ {CD15>}关键字:
链接数值比较(在空白字符串检查之后)。解决了所有这些问题后,您的代码将更像以下内容:
Repl.it
相关问题 更多 >
编程相关推荐