Home > Software design >  How do I avoid generating 3 numbers instead of generating 3 letters and numbers together
How do I avoid generating 3 numbers instead of generating 3 letters and numbers together

Time:12-19

This is a code that generates 3 random letters, numbers, and symbols. I tried to put the "if" formula to avoid the dot at the end of the 3-letter word, and it worked for me:

if password[length-1] == dot:
        dot_password = password.replace(password[length-1],"" .join(random.sample(alll,new_length)))
        file.write(dot_password "\n")

But when I tried to avoid generating 3 numbers only, I failed to do so:

elif password == NUMBERS:
        number_password = password.replace(password,"" .join(random.sample(allll,length)))
        file.write(number_password "\n")

That's why I'm here to find a solution with you. For information, this is the Python language

This is the complete code:

import random

file = open(r"C:\******\******\******\******\******\******\******\Users.txt", "r ")

for i in range(10000): # I set it to 10000 to test only.
    lower = "abcdefghijklmnopqrstuvwxyz_"
    NUMBERS = "0123456789"
    dot = "."

    all = lower   NUMBERS   dot
    alll = lower   NUMBERS
    allll = lower   dot
    length = 3
    new_length = 1
    password = "".join(random.sample(all,length))

    if password[length-1] == dot:
        dot_password = password.replace(password[length-1],"" .join(random.sample(alll,new_length)))
        file.write(dot_password "\n")
    elif password == NUMBERS:
        number_password = password.replace(password,"" .join(random.sample(allll,length)))
        file.write(number_password "\n")
    else:
        file.write(password "\n")

CodePudding user response:

NUMBERS = '0123456789' here NUMBERS is a string that is numeric

elif password == NUMBERS: here password must be '0123456789' for this condition to be true

This is why the above code is not working.

Could try

   elif password.is_numeric():

to test if the whole password just contains numbers

CodePudding user response:

I assume that you want to know if the generated password contains only numbers:

def is_all_number(password):
    numbers = '1234567890'
    for i in password:
        if not i in numbers:
            return False
    return True

Then you can use it inside your condition:

if is_all_number(password):
    ...

    

Or you can use password.isdecimal() as the condition.

  • Related