密码输入帮助{Python}

2024-05-15 23:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个密码输入,必须是6-10个字符长,并给出一个错误,如果密码或

  1. 少于6个字符或超过10个字符
  2. 里面没有两个数字

我试图使它如果你输入错误的密码3次,它将给出一个错误消息,并自动关闭。在

例如,请输入一个密码:hell(3个字符,这样它会重复) 请输入密码:helloa(6个字符,不重复数字) 请输入一个密码:hell12(3个字符2个数字,所以你弄错了3次,所以我想让它关机)

错误:密码错误3次关机。。。。。在

这是我所做的

#Ask user for creation of password
iCount + 1 # Goes up by one everytime password is incorrect
for iCount in range (1,4):
    while len(sPassword) <6 or len(sPassword) >10:
        sPassword =input("Please enter a Password\n\t(Must be 6-10 Characters and  must contain 2 numbers)\n Password: ")
        if len(sPassword) >10:
            print ("Error the password must be 6 characters or more 10 characters or less ")       
            if len([x for x in sPassword if x.isdigit()]) >= 2:
                print (" Password is OK")
            else:
                    print ("Error: The password must contain atleast 2 numbers") 
        elif  iCount==3:
            print ("error")

谁能帮帮我吗?在


Tags: or密码forlenif错误数字password
1条回答
网友
1楼 · 发布于 2024-05-15 23:31:12

由于只允许三次猜测,所以您只需要在代码中使用一个循环语句。如果运行了for循环的末尾,代码应该放弃。在

def get_password():
    for password_tries in range(3):
        password = input("Enter your password: ")

        if len(password) < 6:
            print("Your password is too short (minimum of 6 characters).")

        elif len(password) > 10:
            print("Your password is too long (maximum of 10 characters).")

        elif sum(c.isdigit() for c in password) < 2:
            print("Your password does not contain enough digits (minimum 2).")

        else: # none of the previous checks was hit, so password is valid!
            return password

    print("Too many failed password entries, giving up.")
    return None # or maybe raise an exception here, instead

如果您真的不需要单独的函数,您可以使用一个变量来指示密码是否有效。以下是上述最后几行的另一种选择:

^{pr2}$

相关问题 更多 >