Home > Mobile >  Python: if condition before reading a right or wrong input data type or to avoid `ValueError`
Python: if condition before reading a right or wrong input data type or to avoid `ValueError`

Time:11-11

I have the following code. It reads inputs of 2 integers and prints the sum of them. It also tries to check if the user fails to provide the correct inputs, i.e. if by mistake the user inputs string or float, the code will produce an error message and ask the user to enter new inputs again.

I1, I2 = map(int, input('Enter 2 numbers\n').split())

print('Numbers entered, I1, I2 =', I1,I2)

if isinstance(I1, int) == False or isinstance(I2, int) == False:
     print('All inputs are not integers, please enter again\n')
else:
     print('Sum of the given integers =', I1   I2)

However, if one of the inputs is a non-integer (say, 'x'), I get the following error before the if condition checks whether the inputs are correct or not.

ValueError: invalid literal for int() with base 10: 'x'

Can this be resolved?

CodePudding user response:

The map function has the syntax: map(fun, iter)

So as you wrote it, it already performs a check on the input data type.

However, if you want to keep the code structure, you pass a lambda function that does nothing. For example:

I1, I2 = map(lambda x : x, input('Enter 2 numbers\n').split())

print('Numbers entered, I1, I2 =', I1,I2)

try:
    print('Sum of the given integers =', int(I1)   int(I2))
except ValueError:
     print('All inputs are not integers, please enter again\n')

I find this approach deeply wrong.

I agree with the comment by 0x5453.

Try following these guidelines: Asking the user for input until they give a valid response

CodePudding user response:

use error handling

try:
    I1, I2 = map(int, input('Enter 2 numbers\n').split())
    print('Numbers entered, I1, I2 =', I1,I2)
    if isinstance(I1, int) == False or isinstance(I2, int) == False:
        print('All inputs are not integers, please enter again\n')
    else:
        print('Sum of the given integers =', I1   I2) 
 except:
    print('check again')    # or another message

CodePudding user response:

You need to check if it is an intager before calling int() on it:

str_nums = input('Enter 2 numbers\n').split()

if not all(map(lambda s: s.isdecimal(), str_nums)):
     print('All inputs are not integers, please enter again\n')

else:
    I1, I2 = map(int, str_nums)
    print('Sum of the given integers =', I1   I2)

CodePudding user response:

Have the user enter numbers one at a time, check if they are an integer and then cast them.

I1 = ''
while type(I1) == str:
    I1 = input('Enter a number\n')
    if I1.isdigit():
        I1 = int(I1)

I2 = ''
while type(I2) == str:
    I2 = input('Enter another number\n')
    if I2.isdigit():
        I2 = int(I2)

print('Sum of the given integers =', I1   I2)

This also accommodates for users entering a word or words rather than 2 numbers. For instance, if i enter the word 'cats' or 'cats with hats' rather than 2 numbers, the map function will throw an error because the input is not split into two strings. By the time you perform all the validation needed to use map(), I found this to be shorter.

  • Related