【问题标题】:If else statement printing "you're right" even if the minimum length is not metIf else 语句打印“你是对的”,即使不满足最小长度
【发布时间】:2019-03-17 01:10:55
【问题描述】:

我刚开始使用 python,但在 python 中使用 if else 语句时遇到了一些问题。我正在尝试创建一个检查密码长度的程序。如果它匹配最小长度它应该打印一条消息说你是正确的,但是当它不匹配时它应该打印你不正确。当我运行我的代码时,即使不满足最小长度,它也只会打印出“你是正确的”。我不确定我是否正确使用了 if else 语句,是否需要使用 2 个变量才能使其工作?

MIN_PASSWORD_LENGTH = 6 #The length of the password is determined by the variable MIN_PASSWORD_LENGTH.
                    #We have assigned the variable with the value of 6.

password = input('Enter your password: ')
password_length = len(password)

if MIN_PASSWORD_LENGTH >= 6:
    print("Your password is correct!")
else:
    print("Your not correct!")

print('Number of characters used in password: ', password_length,'and the min length expected is: ',MIN_PASSWORD_LENGTH)

【问题讨论】:

  • 您在 if 语句中使用的是 MIN_PASSWORD_LENGTH 而不是 password_length,因此它将始终测试 6 >= 6。你的意思是if password_length >= MIN_PASSWORD_LENGTH

标签: python if-statement


【解决方案1】:

你正在比较你的常量变量,你应该使用:

if password_length >= MIN_PASSWORD_LENGTH:
    ...
    ...

【讨论】:

    【解决方案2】:

    问题出在你的 if 条件下。似乎您打算检查 password_lenth 是否等于或大于 MIN_PASSWORD_LENGTH ,而不是检查 MIN_PASSWORD_LENGTH >= 6 是否检查 MIN_PASSWORD_LENGTH 是否大于 6。

    您可以通过将if MIN_PASSWORD_LENGTH >= 6: 替换为以下行来修复它:

    if password_length >= MIN_PASSWORD_LENGTH:
    

    希望它是您正在寻找的解决方案。

    【讨论】:

      【解决方案3】:

      if 语句应该是

      if password_length >= MIN_PASSWORD_LENGTH:
      

      【讨论】:

        猜你喜欢
        • 2020-06-07
        • 1970-01-01
        • 2012-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-18
        • 2021-06-07
        • 1970-01-01
        相关资源
        最近更新 更多