-3

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.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

1 Answers1

0

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'
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I want my generate_char() to return/generate different chars. For example : 1st iteration should generate upper char, 2nd -> lower 3rd-> digit and so on in a random fashion . How do i write that? Thanks for all your help – Developing_brain Oct 23 '20 at 18:02
  • You could use a separate list of elements like `[0, 1, 2, 2, 1, 3]` would create a lower letter, upper letter, two digits, upper letter, and a punctuation character, for example, then instead of `length`, you would use `len(character_mapping_list)` – OneCricketeer Oct 23 '20 at 18:05
  • If you want it to be random, then `import random` and `random.randrange()` can be used – OneCricketeer Oct 23 '20 at 18:07
  • Cool, I'll try using the 2nd option you provided - separate list of elements like [0, 1, 2, 2, 1, 3] .. – Developing_brain Oct 23 '20 at 18:11