-2
name_input = 'abc'
password_input = 123

names = ['abc', 'root']
passwords = [123, 456]

for name, password in names, passwords:
    if name == name_input and password == password_input:
        print('Valid')
    else:
        print('Invalid')

Output:

Invalid 
Invalid

Expected output:

Valid 
Invalid

What's the problem with this code?

accdias
  • 5,160
  • 3
  • 19
  • 31

1 Answers1

1

As pointed by enke, you need zip():

name_input = 'abc'
password_input = 123

names = ['abc', 'root']
passwords = [123, 456]

for name, password in zip(names, passwords):
    if all({name == name_input, password == password_input}):
        print('Valid')
    else:
        print('Invalid')

The code above outputs:

Valid
Invalid

As you expected.

Another option is to have a list or a dictionary of name and password pairs:

name_input = 'abc'
password_input = 123

names_and_passwords = [
    ('abc', 123),
    ('root', 456)
]

for name, password in names_and_passwords:
    if all({name == name_input, password == password_input}):
        print('Valid')
    else:
        print('Invalid')
name_input = 'abc'
password_input = 123

names_and_passwords = {
    'abc': 123,
    'root': 456
}

for name, password in names_and_passwords.items():
    if all({name == name_input, password == password_input}):
        print('Valid')
    else:
        print('Invalid')

Which gives you the same result.

accdias
  • 5,160
  • 3
  • 19
  • 31
  • Is there any reason you used *set* instead of a *tuple* inside `all()` ? – S.B Jan 09 '22 at 10:45
  • I have used a [`set()`](https://docs.python.org/3/library/stdtypes.html#types-set) because it is more efficient, IMHO. I think it is better because it will remove all duplicated values. – accdias Jan 09 '22 at 10:49
  • Yes I know but I asked, why did you prefer a set over a tuple as your iterable ? – S.B Jan 09 '22 at 10:52
  • *set* is more efficient when you are doing a membership testing, **not always**. sets are bigger than tuples in memory. Also creation of sets takes longer than a tuple since the items inside of it are needed to be hashed first. In your case, sets are not helping you. – S.B Jan 09 '22 at 10:54
  • @SorousHBakhtiary, thanks for the explanation. Do you think it is a less efficient option when used in `all()`? – accdias Jan 09 '22 at 10:56
  • 1
    Actually I asked this out of curiosity, I wanted to know if you had any specific reason to so. They are just 2 values that we're dealing with so either way, it doesn't matter really. I upvoted you – S.B Jan 09 '22 at 10:59
  • 1
    No worries. It is always good to learn new stuff and discussing it here is always a good way to achieve that. :-) Thanks for the upvote. – accdias Jan 09 '22 at 11:03