-3

When I run the following code:

i = None
O = ['n', 'y', 'No', 'Yes']
while i not in O:
    i = input('Yes or No?\n')
    if i == 'y' or 'Yes':
        print('Yes')
    if i == 'n' or 'No':
        print('No')

The output is n Yes No

Should the code only be displaying No as the output since the first if statement was false? Or am I not understanding something?

Thank you

BlackCode
  • 5
  • 4

3 Answers3

2

You need to explicitly state i == in your second check; if i =='y' or i == 'Yes'

What you have done is

i == 'n' or 'No'
'No'

i is equal to n or No < This outputs No as is it not equal to n

i == 'n' or i == 'No'
False
PacketLoss
  • 5,561
  • 1
  • 9
  • 27
2

You have this in your code:

if i == 'y' or 'Yes':

The meaning of this in Python (and in most programming languages) is:

if (i == 'y') or ('Yes'):

Clearly not what you intended. Since 'Yes' evaluates to true, and anything OR true is true, your ifs body will execute.

To get what you want, you should write:

if i == 'y' or i == 'Yes':

Same for the "no" branch.

shinjin
  • 2,858
  • 5
  • 29
  • 44
1

Here's the problem, you can't do:

if i == 'y' or 'Yes':

as it is testing if i == 'y' or just plain yes. Since non-empty strings always return true, the first if statement will always run. Then the same goes for the second if statement.
So try changing:
if i == 'y' or 'Yes': and if i == 'n' or 'No':
to
if i == 'y' or i == 'Yes': and if i == 'n' or i == 'No':
like so:

i = None
O = ['n', 'y', 'No', 'Yes']
while i not in O:
    i = input('Yes or No?\n')
    if i == 'y' or i == 'Yes':
        print('Yes')
    if i == 'n' or i == 'No':
        print('No')



Here is an example: click

Mr PizzaGuy
  • 410
  • 6
  • 19