dimanche 8 mars 2020

How to trap errors, and go back to start of a loop?

I was working on a code that allows user to calculate the mass of molecules, and I had some user interaction at the start with some specific keywords. For eg the user can type 'instructions' or 'start', but if types something else the program just ends. How can I instead print 'error, try again' and it goes to the start again.

I have tried multiple versions of this code, I am new to python so please excuse if this is super easy. Thanks!

print ("Welcome to MOLECULAR MASS CALCULATOR \n")
intro=input("Calculate mass of any molecule or element by entering the chemical formula. \n\n If this 
is your first time, it is recommended you read the instructions before you start. \n Type 
'instructions'. Otherwise, type 'start'. \n\n")
while intro.upper() == 'INSTRUCTIONS':
    print ("\n\n Calculate the mass of any molecule or element by entering the chemical formula. \n 
\n 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. \n\n Note: If you make an error with typing, the program will terminate and you will have to 
start again.")
    intro=''
    intro=input("\n\n Type 'start' to begin. \n\n ")
while intro.upper() == 'START':
    mol=input("\nEnter a molecule:")
    intro=''
#while intro.upper() != 'START' or 'INSTRUCTIONS':
 #       print ("\nError, please try again.")
  #      intro=''

Aucun commentaire:

Enregistrer un commentaire