Check for a valid input from user

# from a hexadecimal number to an integer
def hex2int(hex_no):


    hexadecimals = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']

    if hex_no != numbers in hexadecimals:
        print ("please enter a valid hexadecimal")
        

I don’t know how to check for validity of an input against a given criteria

You have a very similar post from the other day regarding strings and integers.

What did you do there?

I used different if statements there for the items,

here we are dealing with strings and strings,

hex_no is a string and the numbers in the list are strings too

That may in fact be simpler then, what have you tried so far?

I have tried what l have written above

And what happens? Perhaps you should talk through the logic of your code.

its this part, so l am looking for a match in hex_no and elements in the list

I have also tried doing this, but its giving me a lot of print statements, but l don’t know how to avoid it

# from a hexadecimal number to an integer
def hex2int(hex_no):


    hexadecimals = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']

    for numbers in hexadecimals:
        if hex_no != numbers:
            print("you didn't enter a valid input")

Any specific knowledge area perhaps l am missing?

Ok l watched a video about lists

# from a hexadecimal number to an integer
def hex2int(hex_no):


    hexadecimals = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']

    if hex_no not in hexadecimals:
        print("you didn't enter a valid input")

it has worked or is there a better way?

Glad it worked. I think I preferred the version in the previous post that looped and checked every character that you passed in. Limiting the function to single character arguments might be a pain. Receiving too many print outputs sounds like you may want to return from the function once a certain condition was met. Can you recall the function specific syntax for that?

# from a hexadecimal number to an integer
def hex2int(hex_no):


    hexadecimals = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
    for items in hexadecimals:
        if hex_no != items:
            return "you have entered an invalid input"

The return statement also worked

Thanks

1 Like