【问题标题】:How can I add an if statement to my code?如何在我的代码中添加 if 语句?
【发布时间】:2019-05-21 03:32:23
【问题描述】:

我正在编写密码复杂度代码...我已经完成了我的程序,它说与 true 的比较应该是if cond is true:if cond:,但我想不通

这是我的编程,我真的无法在其中添加或修复任何内容:

import re

print('Please copy the following: password()')
def password():
    print('Make sure that your password has the following rules:')
    print('1. more than 8 characters')
    print('2. has a compination of uppercase and lowercase letters')
    print('3. has digits')
    while True:
        password == input('password:  ')
        if password < 8:
            break
        print('Password must be at least 8 characters')
        if re.search(r'\d', password):
            if re.search(r'\d', password) == True: 
                print('it has a digit')
            else:
                print('Password must contain digits') 
        if re.search(r'[A-Z]', password):
            if re.search(r'[A-Z]', password) == True:
                print('it has uppercase letters')
            else:
                print('Password must contain upper case letters')
        if re.search(r'[a-z]', password):
            if re.search(r'[a-z]', password) == True:
                print('it has lowercase letters')
            else:
                print('Password must contain lowercase letters')

如果密码没有小写字母、大写字母、没有数字或少于 8 个字符,则应如此说明 例如,我希望 abcABC 的输出表明它必须至少为 8 个字符并且必须包含数字。

【问题讨论】:

  • 您的代码到底出了什么问题?
  • 只需使用if expression,不需要if expression == True
  • 好吧,我对你的问题一无所知......你已经在测试几个代码是否正确......你写了那一堆代码吗?
  • 它是说与true的比较应该是if cond is true:if cond:
  • 在这种情况下实际上是一样的。

标签: python python-3.x ipython


【解决方案1】:

我会假设你在这里的这一行中得到了一个TypeErrorif password &lt; 8:,这让你认为你不知道如何使用 if 语句。真的,你不想检查密码是否小于 8,那将是一个垃圾密码,你想检查密码的长度是这样的:

if len(password) &lt; 8:

供将来参考:发布 EXACT 错误消息(带有所有“垃圾”)对于我们找出问题所在非常有帮助。您应该养成发布完整回溯的习惯。

编辑:我还注意到这一行 password == input('password: ') 应该只有一个等号。按照您编写的方式,python 正在检查它们是否相同,得出“否”的结论,然后移至下一行。使用一个等号,您将设置密码变量的输入内容。

【讨论】:

  • 是的;我确实在这一行得到了TypeError。谢谢你让我明白了
  • 乐于助人!下一次,来自您的脚本的所有这些信息将有助于您的问题:Traceback (most recent call last): File "&lt;pyshell#98&gt;", line 1, in &lt;module&gt; None &lt; 8 TypeError: '&lt;' not supported between instances of 'NoneType' and 'int
【解决方案2】:

您不需要if re.search(r'[A-Z]', password) == True: 只需输入if re.search(r'[A-Z]', password),因为这些无论返回Object 还是None, 在 Python 中,if my_variable: 等同于 if my_variable is not None:,具体取决于您的变量数据类型

【讨论】:

    【解决方案3】:

    你可以只使用 if 条件如下:

    if condition:
        # Do something
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多