简体   繁体   中英

Python ternary order of operations

[on_true] if [expression] else [on_false]

If expression is False , does [on_true] still get evaluated?

Reason I ask is because I have a django ORM query as the [on_true] and will write this another way if it evaluates every time this line is run.

After the truthiness of the condition is checked, only one side of the conditional expression will be evaluated. This is guaranteed and documented in the language reference: https://docs.python.org/3/reference/expressions.html#conditional-expressions

You can put whatever garbage expression there to convince yourself of the fact:

>>> wtf.errorerror - error + 1/0 if False else "potato"
'potato'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM