[Tutor] Simpler way to do this (for-loop)?

Andreas Kostyrka andreas at kostyrka.org
Tue Nov 16 18:43:15 CET 2004

Am Di, den 16.11.2004 schrieb Olli Rajala um 12:34:
> Okay, I've been coding my own photogallery and in admin-site I have
> this kind of code. Well, to put it short, it works but is anything
> but goodlooking... And I have no idea how to make it better, so I
> thought to ask here.
> So, 'categories' is just a list with names of categories and I'd like
> to set the default value of the select in html the value found in
> 'category'. Sorry the not so good English. :( 
> So, any ideas how to refactor that part of code?
> ************************************************************
> print 'Category: <select name="category">'
> if not category:
> 	print '<option selected>(Choose the category)</option>'
> 	for line in categories:
> 		print '<option>%s</option>\n' % (line)
> else:
> 	print '<option>(Choose the category)</option>'
> 	for line in categories:
> 		if line == category:
> 			print '<option selected>%s</option>\n' % (line)
> 		else:
> 			print '<option>%s</option>\n' % (line)
> print '</select><br />'
> ************************************************************
Untested code:
print 'Category: <select name="category">'
for cat in categories:
    print '<option%s>%s</option>' % ((cat == category) and " selected" or "", cat)
print '</select><br />'

Alternativly (still untested):
print 'Category: <select name="category">'
for cat in categories:
    if cat == category:
        selected = " selected"
        selected = ""
    print '<option%s>%s</option>' % (selected, cat)
print '</select><br />'

Important things to point out:
      * You can compare None in Python with any other object. It's just
        usually not equal ;)
      * You do not need to write '% (line)', either '% line' is enough,
        because you know that line will never ever be a tuple, or you
        should use '% (line, )'. The comma at the end signals it as a

> TIA, 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
Url : http://mail.python.org/pipermail/tutor/attachments/20041116/e4e7a152/attachment.pgp

More information about the Tutor mailing list