How can I validate user input in Python

How can I make the program ask for valid inputs instead of crashing when non-sensible data is entered?

1 comment

  1. To continue the input instead of getting the program terminated, we need to use the concept of “Try … Except …” block. Try… Except… blocks are used for Exception Handling.

    Whenever an error is occured, the except block handles it. And whenever the input is correct the loop will break.

    Example:

    ##########################################

    while True:
    try:
    integer_input = int(input(‘Enter a number: ‘))
    except:
    print(‘Input should be a number !!!’)
    else:
    print(‘\n\nCorrect Input …’)
    break

    print(‘The number entered is ‘, integer_input)

    ##########################################

    In the above program, we need an integer/numeric input. If an user enters ‘abcd’, instead of terminating the program, the program will go to except  block and this loop will continue till the user enters a correct input i.e. integer input.

    As soon as the user enters 43, the loop breaks.

Leave a comment