user1457212
user1457212

Reputation: 11

Python "and if" equivalent

assume "mylist" can contain the values "video", "audio", "visual" or all three. I want my script to append the matching data to the list "files" if the string is found in"mylist" this works if there is only one string in "mylist", but if there is more than one string, only the first string in "mylist" gets matched. Is there something I could use instead of "elif" that is equivalent to "and if"?

 if request.method == 'POST':
    mylist = request.POST.getlist('list')
    files = []
    if 'video' in mylist:
      files.append('/home/dbs/public_html/download/codex/codex.html')
    elif 'audio' in mylist:
      files.append('/home/dbs/public_html/download/audio/audio_player.html')
    elif 'visual' in mylist:
      files.append('/home/dbs/public_html/download/visual/visual.html')
    return HttpResponse(files)
  else:
    return http.HttpResponseForbidden()

Upvotes: 0

Views: 194

Answers (2)

Nick
Nick

Reputation: 9154

Why not just if? You want each case if it occurs. There is no relationship between each clause. :)

Upvotes: 5

ThiefMaster
ThiefMaster

Reputation: 318688

Simply use if instead of elif.

if 'video' in mylist:
    files.append('/home/dbs/public_html/download/codex/codex.html')
if 'audio' in mylist:
    files.append('/home/dbs/public_html/download/audio/audio_player.html')
if 'visual' in mylist:
    files.append('/home/dbs/public_html/download/visual/visual.html')

You could also use a mapping object and a loop which would be nicer in case there were more than a few items since you don't have to repeat the `... in mylist code:

paths = {
    'video': '/home/dbs/public_html/download/codex/codex.html',
    'audio': '/home/dbs/public_html/download/audio/audio_player.html',
    'visual': '/home/dbs/public_html/download/visual/visual.html'
}

files += [path for key, path in paths.iteritems() if key in mylist]

Upvotes: 10

Related Questions