如何捕获错误,并返回到循环的开始



我正在编写一些代码,允许用户计算分子的质量,一开始我与一些特定的关键字进行了一些用户交互。例如,用户可以键入"指令"或"启动",但如果他们键入其他内容,程序就会结束。我如何打印'error, try again',然后它重新开始?

print ("Welcome to MOLECULAR MASS CALCULATOR n")
intro=input("Calculate mass of any molecule or element by entering the chemical formula. nn If this is your first time, it is recommended you read the instructions before you start. n Type 'instructions'. Otherwise, type 'start'. nn")
while intro.upper() == 'INSTRUCTIONS':
print ("nn Calculate the mass of any molecule or element by entering the chemical formula. nn Subscripts are possible; simply type the chemical formula. For e.g., to type the chemical formula of water simply type 'H20'. Only one digit of subscript per element is possible. n Subscripts with  brackets, and oefficients are not possible. You would have to manually find the mass individually. For e.g., to find the mass of two gallium carbonate molecules '2Ga2(CO3)3', you would have to find the mass of one gallium carbonate molecule, and then multiply it by two. This would require you to first find the mass of one carbonate atom, then multiply by three, then add the mass of two gallium atoms. nn Note: If you make an error with typing, the program will terminate and you will have to  start again.")
intro=''
intro=input("nn Type 'start' to begin. nn ")
while intro.upper() == 'START':
mol=input("nEnter a molecule:")
intro=''
#while intro.upper() != 'START' or 'INSTRUCTIONS':
#     print ("nError, please try again.")
#     intro=''

最简单的方法是使用一个总是重复的while True:循环,并用"break"将其控制在循环内部,以退出循环并放入start代码(如果输入start,则为continue(。

例如,这将做你想做的事:

print("Welcome to MOLECULAR MASS CALCULATOR n")
intro = input("Introduction.n Type  'instructions'. Otherwise, "
"type 'start'. nn")
while True:
if intro.upper() not in ["START", "INSTRUCTIONS"]:
intro = input("nError, please try again:")
continue
if intro.upper() == 'INSTRUCTIONS':
print("Instructions")
intro = input("nn Type 'start' to begin. nn ")
elif intro.upper() == 'START':
break
# 'START' code goes here
mol = input("nEnter a molecule:")

顺便说一句,你的注释代码:

while intro.upper() != 'START' or 'INSTRUCTIONS'

不会按你的意愿工作。Python将其解释为:

while (intro.upper() != 'START') or ('INSTRUCTIONS')

其中'INSTRUCTIONS'(或任何非空字符串(的计算结果始终为True,因此整个语句始终为True。根据值列表进行评估的一种有效方法显示在我的intro.upper() not in ["START", "INSTRUCTIONS"]示例中,它将正确评估您尝试的内容

相关内容

  • 没有找到相关文章

最新更新