hudumudu
hudumudu

Reputation: 45

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")

Upvotes: 1

Views: 190

Answers (3)

Nurjan
Nurjan

Reputation: 6073

Change

mode.lower().split() 

to

mode.lower()

Upvotes: -1

gowrath
gowrath

Reputation: 3224

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")

Upvotes: 0

Anton
Anton

Reputation: 504

Your condition is not good:

if mode.lower().split() not in commands:
    print("Couldn't recognize commands...")

Replace it by (for example):

args = set(mode.lower().split())
if not set(args).issubset(set(commands)):
    print("Couldn't recognize commands...")

http://python.6.x6.nabble.com/Test-if-list-contains-another-list-td1506964.html

Upvotes: 2

Related Questions