Martin
Martin

Reputation: 25

How to iterate in a for loop with error handling

I am trying to catch input errors from the user. The input should be a float. I cannot figure out the logic.

I want the user to redirected to the same key value in material_vars if they enter an invalid input. Currently I can make it work so if an incorrectly it goes back to the first key input rather than the key the invalid entry occurred on.

def material_costs(update=False):

    global material_vars

    while update:

        try:
            for key in material_vars:
                material_vars[key] = float(input(f"Enter {key}:\n"))
        except ValueError:
            print ('Please enter a valid input')
        else:
            save_defaults('material_vars', material_vars)
            update = False

    else:
        material_vars = open_defaults('material_vars')
    return material_vars

Upvotes: 0

Views: 48

Answers (1)

bhavi
bhavi

Reputation: 190

You can modify your function like this

def material_costs(update=False):
    global material_vars
    while update:
        for key in material_vars:
            correct = False
            while (not correct):
                try:
                    material_vars[key] = float(input(f"Enter {key}:\n"))
                    correct = True
                except ValueError:
                    print ('Please enter a valid input')
                    correct = False
        save_defaults('material_vars', material_vars)
        update = False
    else:
        material_vars = open_defaults('material_vars')
    return material_vars

Run a while loop for each input until the user enters the correct input. The input will be verified by the try-except blocks inside the while.

I hope this helps.

Upvotes: 1

Related Questions