0

It keeps printing 'found' although there is no 'jpg 'or 'jpeg' or 'png' or 'bmp' or 'gif' in 'asduas'. What am i doing wrong? :s

if 'jpg 'or 'jpeg' or 'png' or 'bmp' or 'gif' in 'asduas':
    print('found')

else:
    print('not found')
Nabila Shahid
  • 419
  • 1
  • 6
  • 13
  • 1
    Also see http://stackoverflow.com/q/20002503/1903116 – thefourtheye Apr 28 '14 at 06:40
  • You can try just putting all values you want to compare in a list. >>> if 'asduas' in ['jpg', 'jpeg', 'png', 'bmp', 'gif']: ... print 'found' ... >>> if 'jpg' in ['jpg', 'jpeg', 'png', 'bmp', 'gif']: ... print 'found' ... found – Tanveer Alam Apr 28 '14 at 06:55

4 Answers4

2

Another way:

if any(x in 'asudas' for x in ('jpg','jpeg','png','bmp','gif')):
    print('Found')
mshsayem
  • 17,557
  • 11
  • 61
  • 69
  • 1
    perhaps it would be even better with `asudas.endswith(x)` since you are checking for file name extensins (most likely) – Jasper Apr 28 '14 at 06:55
1

The correct way to do this is for example:

if 'jpg' in 'asduas'  or 'jpeg' in 'asduas' or 'png' in 'asduas' or 'bmp' in 'asduas' or 'gif' in 'asduas':
    print('found')
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
1

Your if evaluates if either of the following results in True:

'jpg'
'jpeg'
'png'
'bmp'
'gif' in 'asduas'

Because 'jpg' evaluates to True it wil enter the if always.

What you probably want

if any(x in 'asduas' for x in ('jpg', 'jpeg', 'png', 'bmp', 'gif')):
Tim
  • 41,901
  • 18
  • 127
  • 145
0

You misunderstand how boolean expressions work. You are looking for:

if 'jpg' in 'asduas'  or 'jpeg' in 'asduas' or 'png' in 'asduas' or 'bmp' in 'asduas' or 'gif' in 'asduas':
    print('found')

else:
    print('not found')

You can even shorten it:

if any(x in 'asduas' for x in ('jpg','jpeg','png','bmp','gif')):
    print('found')

else:
    print('not found')

Because jpg gives True the if statement will always return true.