<p>根据<code>isdigit()</code>方法的以下引用<a href="http://www.tutorialspoint.com/python/string_isdigit.htm" rel="nofollow">here</a>:</p>
<blockquote>
<p>This method returns true if all characters in the string are digits
and there is at least one character, false otherwise.</p>
</blockquote>
<p>这不适合你的案子</p>
<blockquote>
<p>A password must contain at least 2 digits</p>
</blockquote>
<p>该方法只让您知道给定的字符串是否是数字,而不是字符串中有多少数字。要做到这一点,你需要多加练习。</p>
<p>您可以使用以下命令</p>
<pre><code>if sum(character.isdigit() for character in password) >= 2:
</code></pre>
<p>此外,您的代码有一个小错误,因为您永远不会返回True。下面是一个可能的解决方案:</p>
<pre><code>def CountDigitsFor(password):
return sum(character.isdigit() for character in password)
def validPassword(password):
if len(password) >= 8 and password.isalnum() and CountDigitsFor(password) >= 2:
return True
return False
</code></pre>
<p>另外,在你的主体中,当你从用户那里得到密码时,你有一个小的输入错误</p>
<pre><code>password = validPassword()
</code></pre>
<p>应该是</p>
<pre><code>password = getPassword()
</code></pre>
<p>因此这里有一个完整的代码</p>
<pre><code>def getPassword():
return input("Enter password: ")
def CountDigitsFor(password):
return sum(character.isdigit() for character in password)
def validPassword(password):
if len(password) >= 8 and password.isalnum() and CountDigitsFor(password) >= 2:
return True
return False
def main():
password = getPassword()
if validPassword(password):
print(password + " is valid")
else:
print(password + " is invalid")
main()
</code></pre>