猿问

使用 While 循环在 Python 中创建的菜单在需要时不会退出

我是 Python 新手,一直在尝试创建一个简单的菜单,当用户按 4 时退出程序。如果用户立即选择 4,则菜单可以工作,但如果用户在按 4 之前选择其他选项,则 while 循环不会不会中断,菜单会继续。有什么想法可以更改它以便菜单正确退出吗?


def main(): 

     print('''

           Welcome to Grade Central

           [1] - Enter Grades

           [2] - Remove Student

           [3] - Student Average Grades

           [4] - Exit

           \n

           ''')


     action = int(input("What would you like to do today? \n"))

     if action == 1:

         print(1)

     elif action == 2:

         print(2)

     elif action == 3:

         print(3)

     elif action == 4:

         print("The program has been exited")

     else:

         print("Invalid input! Please select an option")

     return action


while main() != 4:

     main()


慕田峪7331174
浏览 137回答 4
4回答

白衣非少年

def main():      print('''           Welcome to Grade Central           [1] - Enter Grades           [2] - Remove Student           [3] - Student Average Grades           [4] - Exit           \n           ''')     action = int(input("What would you like to do today? \n"))     if action == 1:         print(1)     elif action == 2:         print(2)     elif action == 3:         print(3)     elif action == 4:         print("The program has been exited")     else:         print("Invalid input! Please select an option")     return actionaction = main()while action != 4:     action = main()

慕容708150

如果您在函数外部创建一个变量,该变量设置为从函数返回的任何内容,并通过 while 循环检查该变量,那么应该可以工作。def main():    print('''           Welcome to Grade Central           [1] - Enter Grades           [2] - Remove Student           [3] - Student Average Grades           [4] - Exit           \n           ''')    action = int(input("What would you like to do today? \n"))    if action == 1:        print(1)    elif action == 2:        print(2)    elif action == 3:        print(3)    elif action == 4:        print("The program has been exited")    else:        print("Invalid input! Please select an option")    print(action)    return actionreturned_action = 0while returned_action != 4:    returned_action = main()

FFIVE

我建议在您的程序中进行某种形式的输入验证。def main():    action = get_input()    # do something with actiondef get_input():    action = 0    while action not in range(1,5):        try:            action = int(input('What would you like to do today?\n'))            if action not in range(1,5):                print('Action not recognized.')        except ValueError:            print('Please enter an integer.')    return action这允许您检查用户输入是否是整数和/或它是您处理的操作。它会不断询问用户“你今天想做什么?” 直到输入有效。您可以修改范围以处理更多值,并且可以修改错误消息以显示帮助输出。

繁花不似锦

对于每个循环,您调用 main() 两次,并且仅测试其中一个返回值。使用这个代替:while main() != 4:      passpass 是一个不执行任何操作的命令。
随时随地看视频慕课网APP

相关分类

Python
我要回答