-1

I have a empty dictionary which I assign keys from a list of letters and values from user input

valuesDict = {}
letters = ['S', 'u', 'v', 'a', 't']
i = 0
while i < 5:
    newValue = input('Enter ' + letters[i] + ' ')
    if newValue != '':
        valuesDict.update({letters[i]: newValue})
    i = i + 1

and a cutdown if statement to show my problem which prints a number corresponding to the items in the dictionary

if 'S' and 'v' not in valuesDict.keys():
    print('1')
elif 'u' and 'v' not in valuesDict.keys():
    print('2')

If I enter values for u, a, and t it outputs '1' correctly

Enter S
Enter u 2
Enter v
Enter a 5
Enter t 7
1

However, when I enter values for S, a, and t for the elif part of the statement '1' is outputted when it is meant to be '2'

Enter S 2
Enter u 
Enter v 
Enter a 5
Enter t 7
1

Why is this happening, and how can I fix this and avoid it in the future?

Shinobi
  • 3
  • 2

2 Answers2

1

The syntax if 'S' and 'v' not in valuesDict.keys() is not logically equivalent to if 'S' not in valuesDict.keys() and 'v' not in valuesDict.keys().

Omni
  • 1,002
  • 6
  • 12
0

You get:

>>> 'S' and 'v'
'v'

and only check for v not S.

You need to check for both:

if ('S' not in valuesDict.keys()) and ('v' not in valuesDict.keys()):

Example:

>>> 'S' and 'v' not in 'xS'  # equivalent to: 'v' not in 'xS' 
True
>>> ('S' not in 'xS') and ('v' not in 'xS')
False
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
Mike Müller
  • 82,630
  • 20
  • 166
  • 161