Search code examples
pythonpython-3.xoptimizationnested-if

How do I optimize nested if statements? I cannot use && here


Is there a better way in which this can be written? I'm new to python coding and I want to improve below lines of code. I have included a few lines of my code here but the original code is much longer than this(multiple if statements). Any guidance/feedback would be helpful.

    upperchar = #generate a char
    pwdlist.append(upperchar)
    if len(pwdlist) < length:
        upperchar2 = #generate a char
        pwdlist.append(upperchar2)
        if len(pwdlist) < length:
            lowerchar = #generate a char
            pwdlist.append(lowerchar)
            if len(pwdlist) < length:
                lowerchar2 = #generate a char
                pwdlist.append(lowerchar2)
                if len(pwdlist) < length:
                    char3 = #generate a char
                    pwdlist.append(char3)

Posting my first question here so if you need anything more please ask me.


Solution

  • Assuming you are always generating a character the same way, then this would work

    pwdlist = []
    while len(pwdlist) < length:
        pwdlist.append(generate_char())
    

    Or

    pwdlist = [generate_char() for _ in range(length)]
    

    Then you can add logic into this generate function to return something based on random values, for example

    def generate_char():
        from random import randrange
        x = randrange(4)
        if x == 0:
            return 'value a-z'
        elif x == 1:
            return 'value A-Z'
        elif x == 2:
            return 'value 0-9'
        elif x == 3:
            return 'punctuation'