Tony Neydon
Tony Neydon

Reputation: 25

How to make my while loop check both conditions

For my program i am asking the user for a zip code. I am trying to make the program ask the user for their zip code again if the one they typed in isn't only numbers and is exactly 5 characters. It does ask for the zip code again if it isn't 5 characters, but it doesn't ask again if the user typed in something that isn't a number. For example if you typed in "8789" it wouldn't work, but if you typed in "8jkf0" it would work.

I've tried switching my or to an and but that's about it. I couldn't think of anything else to try. I am very new to python. I use it in school and do it sometimes in my free time.

zipcode = input("What is your ZIP code? ")
ziplen = len(zipcode)
while not (char.isnumber() for char in zipcode) or not ziplen == 5:
    zipcode = input("What is your ZIP code? ")
    ziplen = len(zipcode)

I expected that the program would ask for the user's zipcode again if what they typed in wasn't only numbers and exactly 5 characters, but it only checks if it is exactly 5 characters.

Upvotes: 0

Views: 34

Answers (2)

thebjorn
thebjorn

Reputation: 27311

isnumeric checks the entire string, so it's just:

while not zipcode.isnumeric() or not len(zipcode) == 5:
    ...

Upvotes: 4

Barmar
Barmar

Reputation: 780714

You need to call the all() function to return the result of testing all the characters in zipcode. Your list comprehension produces a generator, which will always be truthy.

And the correct function is isdigit, not isnumber.

while ziplen != 5 or not all(map(str.isdigit, zipcode)):

Upvotes: 1

Related Questions