Home > Software engineering >  Not sure why Im getting ValueError: invalid literal for int() with base 10:
Not sure why Im getting ValueError: invalid literal for int() with base 10:

Time:11-30

SO i have a functions

def check_input(user_input, dictionary): #input from user, and dictionary of people and number
    numval = int(user_input)
    for name, code in dictionary.items():
        if user_input == name or numval == code:
            return True

I have a dictionary

 myDict = {'Mark':10, 'Harry':20, 'Richard':30}

Finally my main code looks like thius

chosenPerson = input('What Person do you want to pick?')
    checkInput = check_input(chosenPerson, my_dict)
 if checkInput == True:
     do something

not sure why I am getting invalid literal error

CodePudding user response:

If chosenPerson person is not an integer how would you expect to turn this into an integer?

Instead, use a try-except to guard against non-integer inputs.

def check_input(user_input, dictionary):
    # First check the if the input is a normal name
    if user_input in dictionary.keys():
        return True
    # Now see if the value is an integer and in the dict.
    try:
        # Here we're guarding against `ValueError` by 
        # calling `int` inside the try-except
        if int(user_input) in dictionary.values():
            return True
    except ValueError:
        # We expect this type of failure and ignore it.
        pass
    # We failed all the checks, so return false
    return False

CodePudding user response:

For simple checking, you can modify your check_input function like this:

def check_input(user_input, dictionary):
    if user_input in dictionary.keys(): #Check if a name
        return (user_input, dictionary[user_input]) #return name and value
    elif user_input in dictionary.values(): #Check if input in defined values
        for k in dictionary.keys(): #Loop over all keys
            if dictionary[k] == user_input: #Find key that stores required value
                return (k, user_input)
    else: #If not a name or a value
        return False #Indicates that the user_input is neither a key nor a value

Using a dict in this way is quite risky though. There's nothing to prevent the same value being stored multiple times in a dictionary. With the function as defined here, you'll only get one of the keys. If you need every key with the same name it can be modified to suit, but if you want the "right" key, there would be no way to identify it.

  • Related