输入"Q"或"q"时如何停止循环



代码似乎在输入Q或Q后继续运行。我知道我们需要将其从循环中断开,但是当我将其保留在主函数内时,输出似乎两者都是感谢您使用本软件!无效输入,请输入1-2-Q以执行所需操作"当我输入Q

def main():
count = True
while count == True:
print("1 - Chemical formula for the Ionic Compound")
print("2 - Chemical Name for the Ionic Compound")
print("Q - EXIT")
print("-----------------------------------------------")
action = input("What action would you like to execute? ")
menu(action)
def menu(action):
if action == "1":
print()
e1 = input("Enter chemical symbol for first element: ")
c1 = int(input("Enter the first element charge: "))
e2 = input("Enter chemical symbol for second element: ")
c2 = int(input("Enter the second element charge: "))
print()
print(chemistry.ionicCompound(e1, c1, e2, c2))
elif action == "2":
print()
e1 = input("Enter chemical symbol for first element: ")
e2 = input("Enter chemical symbol for second element: ")
print(chemistry.ionicName(e1, e2))
elif action == "Q" or action == "q":
print()
print("Thank you for using the program!")
else:
print()
print("Invalid Input, Please Enter 1-2-Q for the desired action to be performed")
print()
print("----------------------------------------------------------------------------------")
main()

试试这个:

RUNNING = True
def main():
count = True
while count == True and RUNNING:
print("1 - Chemical formula for the Ionic Compound")
print("2 - Chemical Name for the Ionic Compound")
print("Q - EXIT")
print("-----------------------------------------------")
action = input("What action would you like to execute? ")
menu(action)
def menu(action):
global RUNNING
if action == "1":
print()
e1 = input("Enter chemical symbol for first element: ")
c1 = int(input("Enter the first element charge: "))
e2 = input("Enter chemical symbol for second element: ")
c2 = int(input("Enter the second element charge: "))
print()
print(chemistry.ionicCompound(e1, c1, e2, c2))
elif action == "2":
print()
e1 = input("Enter chemical symbol for first element: ")
e2 = input("Enter chemical symbol for second element: ")
print(chemistry.ionicName(e1, e2))
elif action == "Q" or action == "q":
print()
print("Thank you for using the program!")
RUNNING = False
else:
print()
print("Invalid Input, Please Enter 1-2-Q for the desired action to be performed")
print()
print("----------------------------------------------------------------------------------")
main()

最新更新