If - Or statements
Robert Kern
rkern at ucsd.edu
Sat Jun 4 06:19:55 EDT 2005
Ognjen Bezanov wrote:
> 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
It works just fine for me. Note that you could (and probably should)
write the if statement as
if ext[1] in ('mp3', 'mp4', 'ogg', 'aac', 'wma'):
but I really don't think that's your problem. Could you also post the
output, too?
In [1]:filelist = os.listdir('./')
In [2]:for thefile in filelist:
...: if '.' in thefile:
...: ext = thefile.split('.')
...: ext[1] = ext[1].lower()
...: print ext[1]
...: 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: %s' % ext[1]
...:
ogg
We have a valid extension: ogg
[etc.]
--
Robert Kern
rkern at ucsd.edu
"In the fields of hell where the grass grows high
Are the graves of dreams allowed to die."
-- Richard Harter
More information about the Python-list
mailing list