Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for Errors

Tags:

python

How do I set a value to only accept certain data in Python? Like I am making a code for a colour identifier. I want my variable to only accept up to FFFFFF any nothing greater than that. The base-16 characters pretty much...hex code.

The reason I am trying to do this is because if a user enters in a value like GGGGGG it will give them a Script Error, which actually makes me look incompetent (which I might be, but I do not want to look like I am). And also, if they enter in special characters like F1F2G% it will mess up too. In addition, if they leave the box blank, it also gives a Script Error.

I want to avoid those errors. Does anyone know of a good way?

like image 380
Aj Entity Avatar asked Dec 06 '25 19:12

Aj Entity


2 Answers

try:
    val = int(hex_val, 16)
except ValueError:
    # Not a valid hex value

if val > int("FFFFFF", 16):
    # Value is too large
like image 141
Amber Avatar answered Dec 11 '25 03:12

Amber


You can also use the regex facility in re.

val = val.upper()
seeker = re.compile("^[0-9A-F]{1,6}$")

if seeker.search(val):
    hexCode = int(val, 16)
    # process a good value
else:
    #bail
like image 26
ncmathsadist Avatar answered Dec 11 '25 03:12

ncmathsadist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!