-3

How I can overcome an issue with conditionals in python? The issue is that it should show certain text according to certain conditional, but if the input was No, it anyway indicates the data of Yes conditional.

def main(y_b,c_y):
     ans=input('R u Phil?')
     if ans=='Yes' or 'yes':
             years=y_b-c_y
             print('U r',abs(years),'jahre alt')
     elif ans=='No' or 'no':
             print("How old r u?")
     else:
             print('Sorry')

main(2012,2016)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Sean
  • 59
  • 7
  • Also please do read the formatting help next time, SO uses markdown not raw HTML – jonrsharpe Jun 23 '16 at 08:41
  • `ans=='Yes' or 'yes'` is false, you knew why. But i think, it's better to convert the input to lowercase and compare with `yes`. – qvpham Jun 23 '16 at 09:02

3 Answers3

3

or is inclusive. So the yes test will always pass because when ans != 'Yes' the other condition yes has a truthy value.

>>> bool('yes')
True

You should instead test with:

if ans in ('Yes', 'yeah', 'yes'):
    # code
elif ans in ('No', 'Nah', 'no'):
    # code
else:
    # more code
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
2

When you write if statements and you have multiple conditionals, you have to write both conditionals and compare them. This is wrong:

if ans == 'Yes' or 'yes':

and this is ok:

if ans == 'Yes' or ans == 'yes':
Teemo
  • 449
  • 6
  • 23
1

It's not that different from other languages:

def main(y_b,c_y):
     ans = input('R u Phil?')
     if ans == 'Yes' or ans == 'yes':
             years = y_b-c_y
             print('U r', abs(years), 'jahre alt')
     elif ans == 'No' or ans == 'no':
             print("How old r u?")
     else:
             print('Sorry')

main(2012,2016)

However you might wish to use a simpler test:

if ans.lower() == 'yes':
cdarke
  • 42,728
  • 8
  • 80
  • 84