Search code examples
pythonloopsif-statementuser-input

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


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

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=''

Solution

  • The easiest way to do this is to use a while True: loop that would always repeat, and control it inside the loop with 'break' to exit the loop and drop into the start code if they enter start, otherwise continue.

    For example, this will do what you want:

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

    Incidentally, your commented out code:

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

    will not work as you intend. Python will interpret that as:

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

    where 'INSTRUCTIONS' (or any non-null string) will always evaluate to True, so the whole statement will always be True. One valid way of doing evaluation against a list of values is shown in my example of intro.upper() not in ["START", "INSTRUCTIONS"] which will correctly evaluate what you were trying to.