I am a beginner at python and have been stuck on a line of code for a while now and am unsure how to fix it.
The program requests user input, a HEX value and then converts this to a RGB value. I perform error checking to ensure that the input is a HEX value. However, when I input FEEZ00 it doesn't recognize that the char 'Z' is not in the string hexChars. (this should result in the break statement being activated)
I would greatly appreciate some help (please don't give me the full answer, I would like to learn) Thank you!
hexChars = '0123456789ABCDEF'
rgb1 = (input("Enter 1st color: #")).upper()
rgb2 = (input("Enter 2nd color: #")).upper()
if(len(rgb1) != 6 and len(rgb2) != 6):
print("Not a valid input!", end = "\n\n")
break
for i in range(6):
if((rgb1[i] not in hexChars) and (rgb2[i] not in hexChars)):
print("Not a valid input!", end = "\n\n")
break
My input:
Enter 1st color: #feez00
Enter 2nd color: #feed00
Edit: Clarification is needed. As this is a beginner course we are not allowed to use functions or imports.
break
is not allowed outside of a loop. In your example, you're using it in an if
statement, which should throw an error (so I'm not sure how your code is running at all).
As an alternative, try keeping track of whether the input is valid in a local variable, called is_valid
. You can update it to be False
when you find something wrong with the input.
hexChars = '0123456789ABCDEF'
rgb1 = (input("Enter 1st color: #")).upper()
rgb2 = (input("Enter 2nd color: #")).upper()
is_valid = True
if(len(rgb1) != 6 or len(rgb2) != 6): # as others noted, use or here
is_valid = False
for i in range(6):
if((rgb1[i] not in hexChars) or (rgb2[i] not in hexChars)):
is_valid = False
if not is_valid:
print("Not a valid input!", end = "\n\n")