Search code examples
pythonloopsoptimizationwhile-looptry-catch

Optimise python while loop with try exception


this is a simple question for a newbie python developer, but as I know python code can be optimised a lot ... I was wondering if there is a way to optimise the following, so I don't need 2 while loops, but I also do not want to re-ask the user to input the 1st number if he already sone that correctly:

def sum(a, b):
    return (a + b)

while True:
    try:
        # TODO: write code...
        a = int(input('Enter 1st number: '))
        break
    except:
        print("Only integers allowed for input!")
        continue

while True:
    try:
        # TODO: write code...
        b = int(input('Enter 2nd number: '))
        break
    except:
        print("Only integers allowed for input!")
        continue

print(f'Sum of {a} and {b} is {sum(a, b)}')

Solution

  • You can use a function (with a simplified loop). You may want to rename the sum function as there is already a built-in function with the same name.

    def my_sum(a, b):
        return a + b
    
    def get_int_from_user():
        while True:
            try:
                # TODO: write code...
                return int(input('Enter a number: '))
            except:
                print("Only integers allowed for input!")
    
    
    a = get_int_from_user()
    b = get_int_from_user()
    
    print(f'Sum of {a} and {b} is {my_sum(a, b)}')