python 3.3密码ch

2024-09-29 02:27:26 发布

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

我正在创建一个程序来检查密码是否足够强:

  • 他们需要帽子
  • 小写字母
  • 数字
  • 符号和
  • 不能包含简单密码。在

正如你在下面看到的,这只是我的一些代码,我有一个菜单,和一个密码检查器,唯一的问题是,当我输入密码时,它总是说它是一个强密码,即使它不包含任何大写字母、数字或符号。以下是我目前为止的代码。在

import random #importing random
import time #importing time
global Menu

def Menu():
    global optionchoice #globalising variable optionchoice so that it can be used inside of another def of the code
    print("Hey, Welcome to PassWordChecker.")
    time.sleep(2) #delaying the next line for 2 seconds
    print("Please choose one of the options below." )
    time.sleep(1)
    print("MENU:")
    print("***")
    print("    press 1 once for              :           password checker  ")
    print("    press 2 twice for             :           password generator")
    print("    press 3 two or three times to :           Quit              ")
    print("                                                                 ***") #creating a basic menu
    optionchoice = (input("which option would you like to choose?"))

def checkpasswordandinput():
    global optionchoice
    optionchoice = optionchoice
    if optionchoice == '1':
        print(" please enter a password. ")
        UserPassword = input("")
        if len(UserPassword) <= 8 or len(UserPassword) >= 24 or UserPassword == UserPassword.isupper() or UserPassword == UserPassword.isdigit() or UserPassword == UserPassword.islower() or UserPassword == UserPassword.isalpha():
            print("make sure your password includes numbers and upper and lower case letters  ")
            UserPassword = input('please enter a new password')
        else:
            print('your password is a very good one that is difficult to crack')
            return Menu()

未来读者须知:

请不要在上表中填写代码:

  1. 不要导入不需要的模块
  2. 不要使用全局变量
  3. 使用循环:例如while True:
  4. 从其他函数调用函数
  5. 将一个函数的值返回给调用者:optionchoice = menu()

以上代码在这种形式下会更好:

^{pr2}$

Tags: oroftheto代码密码fortime
2条回答

表单UserPassword == UserPassword.isupper()中的检查将不起作用。在这里,您将比较一个字符串密码和一个布尔值,isX()的结果。因此,所有这些检查都是False,并且您可以得到else分支(如果长度可以接受的话)。在

在大写和小写字符的情况下,可以使用UserPassword == UserPassword.upper()(只使用upper,而不是{},类似于{}),也就是说,将密码与其大写/小写版本进行比较,但对于数字,这是行不通的。相反,您可以使用any来检查是否有任何字符是数字:any(c.isdigit() for c in UserPassword)

编辑:您可以使用UserPassword == UserPassword.upper()检查密码是否包含任何小写字母,这有点不直观。相反,我建议在所有检查中使用any,并将条件倒置,这样“正”的情况在if的主体中,而“否定”的情况在其他主体中。像这样:

up = UserPassword
if 8 <= len(up) <= 24 and any(c.isupper() for c in up) and any(c.islower() for c in up) and any(c.isdigit() for c in up) and any(c.isalpha() for c in up):

或者简短一点,使用函数列表:

^{pr2}$

所以你需要做如下的事情:

hasUpper = False
hasLower = False
hasDigit = False

等等

然后,逐个检查“密码”一个字符: 即字符串[1],字符串[2],字符串[3]

对其运行布尔结果(isupper、islower等) 如果为true,请将hasUpper、hasLower、hasDigit更改为true

然后,在遍历整个字符串之后,根据您的需求检查boolean结果。即:

如果要求是上、下和数字。在

^{pr2}$

那就是一个好的密码,等等

有道理吗?在

相关问题 更多 >