如何减少变量数量并使代码高效

2024-09-29 21:51:50 发布

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

这是我第一次向stackoverflow发帖

创建和使用这些变量的有效方法是什么

lowerCharsEnabled = True
upperCharsEnabled = True
digitCharsEnabled = True
specialCharsEnabled = True

这个功能可以完成这项工作,但据我所知,这并不是最有效的方式

def usedChars():
    global finalChars

    if lowerCharsEnabled == True:
        finalChars = lowerChars

    if upperCharsEnabled == True:
        finalChars = finalChars + upperChars

    if digitCharsEnabled == True:
        finalChars = finalChars + digitChars

    if specialCharsEnabled == True:
        finalChars = finalChars + specialChars

期待您的建议,如有任何帮助,将不胜感激

完整的程序代码供参考

import random
import string

lowerChars = string.ascii_lowercase
upperChars = string.ascii_uppercase
digitChars = string.digits
specialChars = string.punctuation

lowerCharsEnabled = True
upperCharsEnabled = True
digitCharsEnabled = True
specialCharsEnabled = True
finalChars = ""

passLen = 8

def usedChars():
    global finalChars

    if lowerCharsEnabled == True:
        finalChars = lowerChars

    if upperCharsEnabled == True:
        finalChars = finalChars + upperChars

    if digitCharsEnabled == True:
        finalChars = finalChars + digitChars

    if specialCharsEnabled == True:
        finalChars = finalChars + specialChars


def generatePass():
    try:
        password = "".join(random.choice(finalChars) for x in range(passLen))
        print(password)

    except:
        print("Cant Generate Pass")

usedChars()
generatePass()

input("Waiting...")

Tags: truestringifdefglobalspecialcharsdigitcharsenableduppercharsenabled
1条回答
网友
1楼 · 发布于 2024-09-29 21:51:50

最后的答案谢谢大家

import string
import secrets

lower_chars = string.ascii_lowercase
upper_chars = string.ascii_uppercase
digit_chars = string.digits
special_chars = string.punctuation

lower_chars_enabled = True
upper_chars_enabled = True
digit_chars_enabled = True
special_chars_enabled = True
final_chars = ""

passLen = 8

def used_chars():
    global final_chars

    if lower_chars_enabled == True:
        final_chars = lower_chars

    if upper_chars_enabled == True:
        final_chars = final_chars + upper_chars

    if digit_chars_enabled == True:
        final_chars = final_chars + digit_chars

    if special_chars_enabled == True:
        final_chars = final_chars + special_chars



def generate_pass():
        password = "".join(secrets.choice(final_chars) for x in range(passLen))
        return password

used_chars()
generate_pass()

input("Waiting...")

相关问题 更多 >

    热门问题