4 回答
TA贡献1155条经验 获得超0个赞
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
action = main()
while action != 4:
action = main()
TA贡献1831条经验 获得超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")
print(action)
return action
returned_action = 0
while returned_action != 4:
returned_action = main()
TA贡献1797条经验 获得超6个赞
我建议在您的程序中进行某种形式的输入验证。
def main():
action = get_input()
# do something with action
def 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
这允许您检查用户输入是否是整数和/或它是您处理的操作。它会不断询问用户“你今天想做什么?” 直到输入有效。您可以修改范围以处理更多值,并且可以修改错误消息以显示帮助输出。
TA贡献1851条经验 获得超4个赞
对于每个循环,您调用 main() 两次,并且仅测试其中一个返回值。
使用这个代替:
while main() != 4: pass
pass 是一个不执行任何操作的命令。
添加回答
举报