On 03/11/14 17:33, Albert-Jan Roskam wrote:
I sometimes do something like
ifelse = "'teddybear' if bmi > 30 else 'skinny'"
weightcats = [eval(ifelse) for bmi in bmis]
Would this also be a *bad* use of eval? It can be avoided, but this is so
concise.
eval etc are worst where the code to be evaluated is
coming from outside your program (eg a file, user
input etc)
So in your use case its not quite so dangerous since
the code is hard coded into your program. But its is still easily
avoided by putting the ifelse bit into a function
def getWeight(bmi):
return 'teddybear' if bmi > 30 else 'skinny'
weightcats = [getWeight(bmi) for bmi in bmis]
You could use the expression directly in the comprehension but I'm
assuming the real examples are more complex...
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor