0

I am trying to write a program which accepts multiple inputs from user and do whatever is required but i don't want the program execution stop when user gives some error in the input rather i would like that line of program to be repeated again and again until the user gives a valid input or cancel the operation. For example i have the following piece of program :-

# Error handling    
i=int(eval(input("Enter an integer: " )))
print(i)

Now if the user enters a string following error is occurs :

Enter an integer: helllo
Traceback (most recent call last):
  File "C:/Users/Gaurav's PC/Python/Error Management.py", line 2, in <module>
    i=int(input("Enter an integer: " ))
ValueError: invalid literal for int() with base 10: 'helllo'

HERE, I want Python to re-run the line 2 only for a valid input until user inputs a correct input or cancel the operation and once a correct input is passed it should continue from line 3, How can i do that?

I have tried a bit about it using try and except statement but their are many possible errors and i cannot find a way to run that line again without re-writing it in the except block and that too works for one error or the number of times i copy the same code in the except block.

Tushar
  • 167
  • 7

2 Answers2

0

You can put it in a while loop and check to see if an an input is an integer or not:

def is_integer(s):
    try:
        int(s)
        return True
    except ValueError:
        return False

while True:
    i = input("Enter an integer: " )
    if is_integer(i):
        print(i)
        break
Minh Nguyen
  • 755
  • 5
  • 11
  • Well that will not repeat and will not ask user to give an input again until he passes an integer. – Tushar Sep 17 '20 at 04:18
  • @Tushar I have updated the answer; basically you can put it in a while loop and break when the input is an integer – Minh Nguyen Sep 17 '20 at 04:22
0

Try :

while True: 
     try: 
         i = int(input("Enter number : ")) 
         break 
     except: 
         continue 

Or you can use pass instead of continue.

Pawan bisht
  • 183
  • 1
  • 9