【问题标题】:password validation - python密码验证 - python
【发布时间】:2021-04-28 18:27:10
【问题描述】:

我正在尝试编写代码来验证密码。但是它不起作用,关于如何解决这个问题的任何想法?

password = input("Please enter password: ")

length = False
digit = False
capital = False

length = len(password)

if length > 6:
    length = True
    #print("Length Good")

for count in password:
    if count.isdigit():
        digit = True
        #print ("Contains digit")

for count in password:
    if count.isupper():
        capital = True
        #print ("Contains a capital")

if length != True and digit != True and capital != True:
    print("Password is good")
else:
    print("Bad password")

关于如何解决此问题的任何想法,谢谢

【问题讨论】:

  • length 不能是您的密码长度,并且也是一个真/假值。使用两个变量。
  • (1) 不能同时将同一个变量“长度”用于两个目的。 (2) 像“zgjf”这样的密码被认为是好的。
  • 另外,您的代码需要一个“好的”密码才能不包含大写字母并且不包含数字。这似乎不太可能是您想要的。
  • @khelwood 我已经更改了代码,但它似乎仍然不起作用?谢谢
  • @MichaelButscher 我已经更改了代码,但它似乎仍然不起作用?谢谢

标签: python validation passwords


【解决方案1】:

我运行它并输入“测试”,它说“密码是好的”。我怀疑你的意思是:

password = input("Please enter password: ")

length = False
digit = False
capital = False

length = len(password)

if length > 6:
    length = True
    #print("Length Good")

for count in password:
    if count.isdigit():
        digit = True
        #print ("Contains digit")

for count in password:
    if count.isupper():
        capital = True
        #print ("Contains a capital")

if length == True and digit == True and capital == True:
    print("Password is good")
else:
    print("Bad password")

因为否则您将强制使用错误的密码。

【讨论】:

  • 酷,太棒了@Katie010203 你能把这个标记为正确答案,这样我就可以得到分数了吗?
  • 我会的,它说我要等 1 分钟你 x
【解决方案2】:

在您的代码中,您将密码的长度分配给变量length,然后立即用False 覆盖length 中的值:

length = len(password)
length = False

此外,您正在检查 length、digit 和 capital 是否为 True,因为检查它们是否为 False 会得到相反的结果,除非您翻转语句

您应该将len(password) 移动到支票本身,如下所示:

password = input("Please enter password: ")

length = False
digit = False
capital = False

if len(password) > 6:
    length = True
    # print("Length Good")

for count in password:
    if count.isdigit():
         digit = True
         # print ("Contains digit")
    elif count.isupper():
         capital = True
         # print ("Contains a capital")

if length == True and digit == True and capital == True:
    print("Password is good")
else:
    print("Bad password")

【讨论】:

    【解决方案3】:

    你正在设置

    length = len(password)
    

    之后

    length = False
    

    所以Python首先将length设置为int,在第二条指令中Python取消variable的值并将length变量设置为boolean(False),条件length>6失败。

    【讨论】:

      猜你喜欢
      • 2017-04-28
      • 1970-01-01
      • 2018-04-17
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多