hudumudu hudumudu - 1 month ago 7
Python Question

Check if element in a list

I want to check if the string that is given through parameters in the function is in a list. The code itself doesn't produce any errors but it works the wrong way. If I give my function "-a" as parameter it still says that it's not in the list but it definitely is.

This is the code :

def generatePassword(pLength, mode):
password = str()
commands = ["-a", "-n", "-s", "-allupper", "-mixupper"]
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
specialCharacters = ["!", "?", "&", "@",
"-", "=", "#", "+", "*", "/", "%", "§"]
if mode.lower().split() not in commands:
print("Couldn't recognize commands...")
else:
for n in range(pLength):
i = random.randint(1, 2)
if "-a" in mode.lower().split():
password += alphabet[random.randint(0, 25)]
print("[+]", password)

generatePassword(30, "-a")

Answer

You can use the any command to check if any of the words in mode.lower().split() are not in commands:

def generatePassword(pLength, mode):
    password = str()
    commands = ["-a", "-n", "-s", "-allupper", "-mixupper"]
    alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
                "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
    specialCharacters = ["!", "?", "&", "@",
                         "-", "=", "#", "+", "*", "/", "%", "§"]

    if any(x not in commands for x in mode.lower().split()):
        print("Couldn't recognize commands...")
    else:
        for n in range(pLength):
            i = random.randint(1, 2)
            if "-a" in mode.lower().split():
                password += alphabet[random.randint(0, 25)]
        print("[+]", password)

generatePassword(30, "-a")