我认为我有正确的想法来解决这个函数,但我不知道为什么 我没有得到文档字符串中显示的所需结果。谁能帮我解决这个问题吗?
def check_password(s):
'''(str, bool)
>>> check_password('TopSecret')
False
>>> check_password('TopSecret15')
True
'''
for char in s:
if char.isdigit():
if char.islower():
if char.isupper():
return True
else:
return False
最佳答案
你的逻辑有缺陷,它应该是这样的:
def check_password(s):
has_digit = False
has_lower = False
has_upper = False
for char in s:
if char.isdigit():
has_digit = True
if char.islower():
has_lower = True
if char.isupper():
has_upper = True
# if all three are true return true
if has_digit and has_upper and has_lower:
return True
else:
return False
现在,让我们谈谈您的代码有什么问题。
def check_password(s):
for char in s:
if char.isdigit():
if char.islower(): # we only get to this check if char was a digit
if char.isupper(): # we only get here if char was a digit and lower
# it is not possible to get here
# char would have to be a digit, lower, and upper
return True
else:
return False
作为示例,让我们看一下 TopSecret15,我们从 T 开始
isdigit
= False,因此我们立即为“T”返回 false- 我们将继续立即返回 false,直到达到“1”
- 假设我们在 1,
isdigit
为 true,但islower
为 false,因此它再次返回 false
你知道这三个对于同一个字符来说是如何不可能成立的吗?
您的代码相当于:
if char.isdigit and char.islower and char.isupper:
# this will never happen
关于python - 检查密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665631/