1

In my program, the user will enter more than one code in the "AB123" format. Based on the entered codes, I have to filter out those that start with the letters "AB" and end with the numbers "00". I have to print and count their number separately from the bulk of all codes, how can this be done?

My current code is:

def main():
    code = input("Please enter all codes of your products in format 'AB123':")
    print("Your codes are:", code)
    pCodes = None

    if len(code) == 5 and code.startswith('AB') and code.endswith('00'):
        pCodes = code.startswith('AB') and code.endswith('00')
        print("Ok, here are your prioritized codes", pCodes)
    else:
        print("There are no codes with 'AB' letters and '00' digits at the end!")

main()

I tried to integrate a new variable pCodes to assign all codes with letters "AB" and digits "00" but it's not working as planned...

1 Answer 1

1

You need to use a for loop, and add brackets in order for it to be a list comprehension:

def main():
    code = input("Please enter all codes of your products in format 'AB123':")
    print("Your codes are:", code)
    codes = [c for c in code.split() if len(c) == 5 and c[:2] == 'AB' and c[-2:] == '00']  
    if codes:
        print("Ok, here are your prioritized codes", codes)
    else:
        print("There are no codes with 'AB' letters and '00' digits at the end!")


main()

Input:

Please enter all codes of your products in format 'AB123':AB100 UI812 GS901 AB300

Output

Your codes are: AB100 UI812 GS901 AB300
Ok, here are your prioritized codes ['AB100', 'AB300']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.