So I wrote this code to find whether there is an uppercase letter AND a number in my string or not and here is what I have so far
def passwordOK(password: str):
for char in password:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "1234567890":
return True
else:
return False
print(passwordOK(password='roskaisHsodihf'))
but the result only retyrns if the first variable is modified, so the output only prints True if the first variable is a number or an uppercase letter What changes to my code should be made?
Please do not use import and try to use the least amount of built in functions possible
CodePudding user response:
def passwordOK(txt):
return True if any(t.isupper() for t in txt) and any(t.isdigit() for t in txt) else False
CodePudding user response:
3 issues:
- You always return from the first loop iteration
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "1234567890"
does not mean what you think it does.- If it did, your logic would still be wrong. A char cannot be an uppercase letter AND a digit at the same time. And if you mean
or
, one of the two still does not confirm the existence of the other in another position.
The logic you need should go along the following lines:
def passwordOK(password: str):
upper = digit = False
for char in password:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and "1234567890":
upper = True
if char in "1234567890":
digit = True
if upper and digit:
return True
return False
If you were to use some utils you could avoid some of the boilerplate code:
from string import ascii_uppercase, digits
def passwordOK(password: str):
upper = any(c in ascii_uppercase for c in password)
digit = any(c in digits for c in password)
return upper and digit
Or even shorter, using the test methods:
def passwordOK(password: str):
return any(map(str.isupper, password)) and any(map(str.isdigit, password))
CodePudding user response:
Logical comparisons do not work like you expect them judging by your code. Each part left and right to the and
keyword will return either True
or False
. Therefore you need to repeat the char
variable to check against your second list of characters like so:
if char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and char in "1234567890":
An non-empty string will return True
by default in such a scenario.
Edit:
Also you have to use or
because and
will only return True
if both creterias are met. A single char can't be in two disjunct sets at the same time.
An approach here would be to set a variable if either criteria is met and as soon as both ciriterias are met, you return True
.