【问题标题】:Why does my if statement return the wrong prompt?为什么我的 if 语句返回错误提示?
【发布时间】:2021-12-19 00:39:01
【问题描述】:

我确信答案就在我面前,但是当我输入正确的条件时,我似乎无法弄清楚如何解决我的第一个 if 语句的返回值。

create_password = input("Enter password here: ")

if len(create_password) > 6 and create_password.isdigit() > 0:
    print("Your account is ready!")
elif len(create_password) < 6 and create_password.isdigit() < 1:
    print("Password must be more than 6 characters and must include a number")
elif len(create_password) > 6 and create_password.isdigit() == 0:
    print("Password must include a number")
else:
    print("Your password sucks")

假设我输入了elephant100,我正试图获得“您的帐户已准备好!”的提示。但令我沮丧的是,它显示“密码必须包含数字”,我不知道为什么。我的其他条件与正确的输入匹配,但这是唯一不起作用的条件。

【问题讨论】:

  • isDigit() 函数长什么样子?
  • 我没有定义 isdigit()。我想我可以使用内置函数来检查密码是否至少有一个整数。
  • 对不起,我来自 Java 开发,我不知道这是 python 中的内置函数。我个人会研究正则表达式来解决这个问题
  • 你很好,我使用了一些内置函数来检查输入是否只有数字或字母,以及检查输入是否同时包含字母和数字

标签: python-3.x if-statement user-input


【解决方案1】:

.isdigit()方法如果所有字符都是数字则返回True,否则返回False。因此在这种情况下它返回False,因为您的字符串包含诸如e、l、p等字母。所以语句print("Your account is ready!")将永远不会被执行。

【讨论】:

  • 有道理,谢谢。但是在这种情况下,如何检查密码是否同时包含字母和整数?
  • 我做到了,再次感谢。我现在知道如何修复
【解决方案2】:

原来我需要使用 isalnum()、isnumeric() 和 isalpha() 来解决我的问题。感谢 Muhammed Jaseem 帮我解决了这个问题!这是我修改后的代码。

if create_password.isnumeric() == True:
    print("Password must be more than 6 characters and include letters")
elif create_password.isalpha() == True:
    print("Password must be more than 6 characters and include numbers")
elif len(create_password) > 6 and create_password.isalnum() == True:
    print("Your account is ready!")
else:
    print("Your password sucks. Must be more than 6 characters and contain only letters and numbers")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 2022-12-09
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    相关资源
    最近更新 更多