If - Or statements
rzed
jello at comics.com
Sat Jun 4 09:07:08 EDT 2005
Ognjen Bezanov <ognjen at mailshack.com> wrote in
news:mailman.483.1117877861.18027.python-list at python.org:
> Robert Kern wrote:
>
>> Ognjen Bezanov wrote:
>>
>>> Another newbie-ish question.
>>>
>>> I want to create an if statement which will check if a
>>> particular variable matches one of the statements, and willl
>>> execute the statement if the variable matches any of the
>>> statements.
>>>
>>> I have tried the following (the pass is just used for testing)
>>>
>>>
>>> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1] == "ogg" or
>>> ext[1] == "aac" or ext[1] != "wma":
>>> print "we have a valid extension: " + ext[1] #here
>>> would go the
>>> code for decoding the above
>>> pass
>>
>>
>> It works fine for me. Could you post the smallest complete
>> program (one that defines ext) that displays the behavior and
>> its entire output?
>>
>> As an aside, is 'ext[1] != "wma"' correct or should it be ==?
>> As written, you could collapse the whole thing to 'if ext[1] !=
>> "wma":' but I presume it is a typo.
>>
> filelist = os.listdir('/mnt/cdrom/') #get a list of files from
> the cdrom drive
> for thefile in filelist[:]: #for each file in the
> filelist
> if thefile.find(".") != -1: #if the file has an
> extenstion
> at all
> ext = thefile.split('.') #get the file extension
> ext[1] = ext[1].lower() #convert to lowercase
> print ext[1] #debugging, to see the variable
> before
> passed to if statement
>
> if ext[1] == "mp3" or ext[1] == "mp4" or ext[1]
> == "ogg"
> or ext[1] == "aac" or ext[1] == "wma":
> print "we have a valid extension: " + ext[1]
> #here
> would go the code for decoding the above
> pass
Though this may sidetrack the issue, another way of doing multiple
checks like that is to make a list and check for inclusion in the
list. Something like this:
exts = ['mp3','mp4','ogg','aac','wma']
if ext[1] not in exts:
# do whatever
or
if ext[1] in exts:
print 'we have a valid extension:',ext[1]
It's easier to add to the list than to add another explicit test,
particularly if the tests occur in several places.
--
rzed
More information about the Python-list
mailing list