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 是一個不執行任何操作的命令。
添加回答
舉報