我所做的Python程序是基於菜單的,需要用戶輸入來瀏覽程序。Python:如何在循環中結束程序?
我已經放置了一個while
循環,以便使用戶回到開始菜單以執行任務,但其中一個選項是「按0退出」將只是重新啓動循環而不結束程序。下面是代碼:
terms = {"ALU":"Arithmetic Logic Unit", "CPU":"Central Processing Unit", "GPU":"Graphics Processing Unit"}
while True:
print(
"""
Computing Terminology
0 - Quit
1 - Look Up a Term
2 - Add a Term
3 - Redefine a Term
4 - Delete a Term
5 - Display All Terms
"""
)
menu = input("Choice: ")
print()
while menu != "0":
if menu == "1":
print("\n")
term = input("Type in a term you wish to see: ")
if term in terms:
definition = terms[term]
print("\n")
print(term, "means", definition, "\n")
break
else:
print("This term does not exist.\n")
break
elif menu == "2":
term = input("What term would you like to add?: ")
if term not in terms:
print("\n")
definition = input("What's the definition?: ")
terms[term] = definition
print("\n")
print(term, "has been added.\n")
break
else:
print("\n")
print("Term already exists, try redefining it instead.\n")
break
elif menu == "3":
term = input("Which term do you want to redefine?: ")
if term in terms:
definition = input("What's the new definition?: ")
terms[term] = definition
print("\n")
print(term, "has been redefined.\n")
break
else:
print("\n")
print("That term doesn't exist, try adding it instead.\n")
break
elif menu == "4":
term = input("Which term would you like to delete?: ")
if term in terms:
del terms[term]
print("\n")
print("The term has been deleted.\n")
break
else:
print("\n")
print("This term doesn't exist.\n")
break
elif menu == "5":
print("\n")
print("Terms available are: ")
for term in terms:
print("\n", term, "\n")
else:
print("\n")
print("Sorry, but", menu, "is not a valid choice.\n")
break
print("\n")
input("Press any key to exit.") #if user enters 0 I want the program to end here.
它可能是個人喜好,但我會避免使用字符串輸入,如果選擇將是數字。對我來說,讓它們成爲「int」是更有意義的,以避免對你是否需要引用行爲引起混淆。 – IanAuld
@IanAuld公平點。 – RoyalSwish