How to create a validation loop for multiple inputs I wrote some code to get 3 integers from the user. The code then prints the sum of the 3 integers. The code works as expected. I want to validate all input before doing the calculation. However, the code just doesn't feel right. Is there another approach I should be taking? It seems.. redundant. I am looking into nested try/except, but so far no luck.
msg = &quot;Invalid Input&quot;


while True:
    try:
        a = int(input(&quot;Enter 1st number: &quot;))
        break
    except:
        print(msg)
while True:
    try:
        b = int(input(&quot;Enter 2nd number: &quot;))
        break
    except:
        print(msg)
while True:
    try:
        c = int(input(&quot;Enter 3rd number: &quot;))
        break
    except:
        print(msg)

print(a + b + c)
Your revised code in on the right track. You can simplify the function a fair bit:
def get_integer_input(prompt):
    while True:
        try:
            # Just return directly. No need for an invalid_input flag.
            return int(input(prompt))
        except ValueError:
            print('Invalid input')

# Where you see repetition in your code, consider using a data structure to
# address it. There are libraries that will give you the ordinals. Personally,
# I would just rephrase the input() prompt so that the ordinals are not needed.
ORDINALS = ('1st', '2nd', '3rd')

# Get the integers.
fmt = 'Enter {} number: '
a, b, c = [get_integer_input(fmt.format(o)) for o in ORDINALS]
print(a + b + c)

# Or if you care only about the total, just get it directly.
tot = sum(get_integer_input(fmt.format(o)) for o in ORDINALS)
print(tot)