dimanche 13 janvier 2019

For loop terminating early in nested ifs and function due to return

I am trying to solve the following practice question:

"Imagine you're writing the software for an inventory system for a store. Part of the software needs to check to see if inputted product codes are valid.

A product code is valid if all of the following conditions are true:

  • The length of the product code is a multiple of 4. It could be 4, 8, 12, 16, 20, etc. characters long.
  • Every character in the product code is either an uppercase character or a numeral. No lowercase letters or punctuation marks are permitted.
  • The character sequence "A1" appears somewhere in the product code.

Write a function called valid_product_code. valid_product_code should have one parameter, a string. It should return True if the string is a valid product code, and False if it is not."

def valid_product_code(code):
    if len(code)%4 == 0:
        if "A1" in code:
            if code.isalnum():
                for character in code:
                    #print(character) 
                    #print statement above when uncommented used to 
                    #check if the loop is actually running as intended
                    if character.isupper() or character.isdigit():
                        return True
                    else:
                        return False
            else:
                return False
        else:
            return False
    else:
        return False

The practice question had several test strings, of which they included the following:

print(valid_product_code("A12B44BP"))
print(valid_product_code("BFDSAUSA98932RWEFOEWA9FEAA1DSFSF"))
print(valid_product_code("A1BBD5"))
print(valid_product_code("BDD5664S"))
print(valid_product_code("66aBSaA1fdsv"))

My code worked for the first four examples, resulting in True, True, False, False but while the last one should be False, I got True. After attempting some debugging (hence the print(character) in the for loop and changing the return True and return False to print(True) and print(False) statements respectively), the print statements I used to check indicated that lowercase letters all had False values whereas numbers and uppercase letters had True values as intended.

I had no problems with the 3 outer if statements, but once I needed to isolate lowercase characters I thought a for-each loop would suffice but the fact that this is a function means return is terminating my function prematurely and not allowing me to actually indicate that the presence of even a single lowercase letter in the whole string should render the value of the whole string as False. I feel something is missing, like maybe that I am putting my return statements in the wrong place, or have I simply approached this question the wrong way?

Please help and thanks in advance!

Aucun commentaire:

Enregistrer un commentaire