Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python break statement not function

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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") 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading