制作有效的密码检查器.无法让我的程序通过 if 条件来打印有效的密码



我被分配了以下练习作为家庭作业:

    某些
  1. 网站对密码施加了某些规则。编写一个函数来检查字符串是否为有效密码。假设密码规则如下:
    • 密码必须至少包含八个字符。
    • 密码只能由字母和数字组成。
    • 密码必须至少包含两位数字。 编写一个程序,提示用户输入密码,如果遵循规则,则显示有效密码,否则显示无效密码。

我知道有一种更有效和更合适的方法可以做到这一点,但我才刚刚开始,所以我不一定需要现在成为那些人。只想完成这个问题。

计数器/累加器工作,我没有收到任何错误,但我无法正确满足 if 条件,以便该程序打印"有效密码">

password = str(input("Enter in a password to be checked: "))
def valid_password_checker(password):
from string import ascii_lowercase as alphabet
digits = '0123456789'  # creates a string of digits
digit = 0  # acc for digits
length = 0 # acc for length
for char in password:  # calls on each character in string
if char in alphabet:
length += 1
if char in digits:
digit += 1
if digit >= 2:
flag = True
if length >= 8 and digit is True:
print("valid password")
else:
print("Password does not contain enough characters or digits.")
else:
print("Password does not contain enough digits.")
valid_password_checker(password)

现有代码的问题在于变量digit是一个数字,因此按照您在if语句中所做的那样执行digit is True,始终返回False。如果删除digit is True,则现有解决方案将起作用。但是看看我的版本:

def valid(password):
digits = 0
characters = 0
for char in password:
if char.isalpha():
characters += 1
elif char.isdigit():
digits += 1
characters += 1
if characters >= 8:
if digits >= 2:
print("Password is valid")
else:
print("Password doesn't contain enough digits")
else:
print("Password doesn't contain enough characters")

我对您的原始内容进行了以下修改:

  • 使用内置函数str.isdigit()来检查字符是否为数字。
  • 使用内置函数str.isalpha()检查字符是否为字母表中的字母
  • 将除计数操作以外的所有内容移出for循环,以便函数不会打印多个内容

如果需要,如果您担心老师知道您寻求帮助,可以撤消前两项更改。但是,我不会像输入的密码中有字符那样多次上交打印"密码不包含足够数字"的解决方案。

你可以写这样的东西:

password = str(input("What is the password that you want to validate: "))
def get_digits(password):
return [i for i in password if i.isdigit()]

numbers = ''.join(get_digits(password))
if (len(password) < 8) or (len(numbers) < 2):
print(password, "is an invalid password")
else:
print(password, "is a valid password")

很好,很简单。

最新更新