0

I am a beginner to programming(only 9 days).

I recently learned if, else statements. But I am facing a problem when applying it.

When I use code

    y=input('ans>>')
    if y=='c':
        q=5
    elif y=='a'or'b'or'd':
        q=-1
    else:
        q=0
    print(q)

when I input c it gives me 5, when i input a it gives me -1 but

when I input no other than a,b,c,d it still gives me -1 every time but it is suppose to give 0

how do I fix this?

3 Answers3

1
y=input('ans>>')
if y=='c':
    q=5
elif y in ['a', 'b', 'd']: //similar to y=='a' or y=='b' or y=='d'
    q=-1
else:
    q=0
print(q)
Rupak
  • 99
  • 2
  • 6
1

The problem is in the elif condition. The order of evaluation of the ors is not as you expect. Python reads it as:

((y == 'a') or 'b') or 'd')

If y == 'a' is False, then it evaluates to (False or 'b') or 'd'. False or 'b' evaluates to 'b', and finally 'b' or 'd' evaluates to 'b', which is not zero or None, so the elif will consider this to be True.

As suggested by others, either write:

elif y == 'a' or y == 'b' or y == 'd':

Or write:

elif y in ['a', 'b', 'd']:

G. Sliepen
  • 7,637
  • 1
  • 15
  • 31
1

I may recommend you to learn about boolean type and operation with it like "or","and". To be short - you have to operate with "and" and "or" on the logical expression of comparison:

y=='a'

y=='b'

y=='d'

All three should be the different comparison that produces True or False AND THEN you may test logical "or" "and" with results. ''' if y=='a' or y=='b' or y=='d':

Keep in mind that logical operations over boolean values produces the following result:

True or False is True

True and False is False

False and False is False

False or False is False

I hope this will help