Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"For example, someone recently told me that in Python you can't have conditionals within math expressions."

You can, but until Python 2.5 you needed to use a somewhat opaque idiom:

x + (foo and 1 or 2)

This works because the short-circuiting boolean operators return their second operand. So if foo is true, it'll evaluate 1, find that it's true, and return 1. If foo is false, it short-circuits over the 1, evaluates the 2, finds that that is a true value, and so returns 2. It's not intuitive at all, but most serious Pythonistas are familiar with it.

I agree that this is gratuitously restrictive, and evidently the Python developers did too. As of Python 2.5, you can do this:

x + (1 if foo else 2)

It's a shame that it took so long for them to add it, though.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: