使用while循环在python 3.4中创建安全密码程序

时间:2015-04-01 23:25:01

标签: python

如何创建一个python密码程序,要求用户输入密码,并检查密码是否至少为8个字符,一个数字,一个大写字母和一个小写字母。如果缺少其中一个,它将打印出一个声明,告诉他们需要添加什么才能使密码安全。 我的代码到目前为止:

incorrectPassword= True
while incorrectPassword:
    password = input("type in your password")
    if len(password < 8):
        print("your password must be 8 characters long")
    elif noNum(password == False):
        print("you need a number in your password")
    elif noCap(password == False):
        print("you need a capital letter in your password")
    elif NoLow(password == False):

3 个答案:

答案 0 :(得分:0)

len(password - 8)首先尝试将8与用户输入的密码进行比较,但这不起作用。您必须先找到密码的长度,然后将其与8进行比较:len(password) - 8

noNum(password == False)之类的东西会向noNum()函数发送一个布尔值,我认为你有一个地方,这可能不是它需要的东西。你可能想要noNum(password) == True - 如果传递的字符串不包含数字,noNum()应返回True

也就是说,Python有字符串方法来确定字符串是大写,小写还是数字(仅包含数字)。使用这些来评估给定的密码以及any()函数。

incorrectPassword= True
while incorrectPassword:
    password = input("type in your password: ")
    if len(password) < 8:
        print("your password must be 8 characters long")
    elif not any(i.isdigit() for i in password):
        print("you need a number in your password")
    elif not any(i.isupper() for i in password):
        print("you need a capital letter in your password")
    elif not any(i.islower() for i in password):
        print("you need a lowercase letter in your password")
    else:
        incorrectPassword = False

答案 1 :(得分:0)

while True :
      name = input('Enter user name')
      if name != 'leela':
              continue
      password = input('hello,leela Enter password')
       if password='sana':
              break
print('Access granted')

答案 2 :(得分:-2)

要检查密码字符串是否包含数字,大写字母或类似字符,您可以使用正则表达式,这是一个很好的工具来测试和学习[RegExr](http://www.regexr.com/)。

最好有一个功能可以检查,验证您的输入是否需要多次执行此操作e.q.在一个循环中。

import re

def checkPassword(password):
    """
    Validate the password
    """
    if len(password) < 8:
        # Password to short
        print("Your password must be 8 characters long.")
        return False
    elif not re.findall(r'\d+', password):
        # Missing a number
        print("You need a number in your password.")
        return False
    elif not re.findall(r'[A-Z]+', password):
        # Missing at least one capital letter
        print("You need a capital letter in your password.")
        return False
    else:
        # All good
        print("All good")
        return True

# Promt user to enter valid password
passwordValid = False
while not passwordValid:
    password = input("Type in your password: ")
    passwordValid = checkPassword(password)
相关问题