Home > Software design >  I'm trying to generate two UPPERCASE letters in password generator at python by upper function
I'm trying to generate two UPPERCASE letters in password generator at python by upper function

Time:09-23

I created a function starts with

def letter_def(letter):
letter_ = randint(1, 26)
if letter_ == 1:
    letter = "a"
elif letter_ == 2:
    letter = "b"

and ends with

elif letter_ == 25:
    letter = "y"
elif letter_ == 26:
    letter = "z"
return letter

then i tried to call this function by

password = {symbol_def(symbol_1), symbol_def(symbol_2), number_def(number_1), number_def(number_2),
                letter_def(Capital_1.upper()), letter_def(Capital_2.upper()), letter_def(letter_1),
                letter_def(letter_2), letter_def(letter_3), letter_def(letter_4)}
    password = list(password)
    print("\nyour password is: "   str(password[0])   str(password[1])   str(password[2])   str(password[3])  
          str(password[4])   str(password[5])   str(password[6])   str(password[7])   str(password[8])  
          str(password[9])   "\n")

and focus on this line

letter_def(Capital_1.upper()), letter_def(Capital_2.upper())

but there isn't any UPPERCASE letters in the generated password as

your password is: 9fk)b4}qoa

so should I make another function for upper cases or there is solution for this problem

CodePudding user response:

In case you want to generate a random password with two and only two random uppercase letters in it somewhere, you can do this:

import random
import string


def generate_password(length=10):
    two_random_uppercase = random.choices(string.ascii_uppercase, k=2)
    other_random_characters = random.choices(
        string.ascii_lowercase   string.digits   string.punctuation,
        k=length - 2,
    )

    password = "".join(
        random.sample(two_random_uppercase   other_random_characters, k=length)
    )

    return password


print(generate_password())

First you take two random uppercase letters, then you take a number of random characters consisting of lowercase, digits and specials.

Then you add them together and get a randomly shuffled sample from them, join the random sequence of characters together, and your password is ready.

CodePudding user response:

I'm not entirely sure why you are trying to generate a random password this way. However I believe to fix your problem you probably need to call letter_def(Capital_1).upper()
That will make the letter capitalise after you randomly pick a letter.

If you just want to generate a random password something like this would work:

import string
import random

def gen_password(stringLength=10):
    lettersAndDigits = string.ascii_letters   string.digits
    password = ''.join(random.choice(lettersAndDigits) for i in range(stringLength))
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))
  • Related