how to reduce number of variables and make the code efficient

Viewed 163

this is first time i am posting to stackoverflow

what will be the efficient way to create and use such variables

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

this function does the job but according to me its not the most efficient way of doing this

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

looking forward for suggestions any help would be appreciated

full program code for reference

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...")
1 Answers

Final Answer thanks to everyone

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...")
Related