Back
Is there a way to compress an if/else statement to one line in Python?
I oftentimes see all sorts of shortcuts and suspect it can apply here too.
To condense if/else into one line in Python an example of Python's way of doing "ternary" expressions:-
i = 5 if a > 7 else 0
Translates into:-
if a > 7: i = 5 else: i = 0
if a > 7:
i = 5
else:
i = 0
Python's if can be used as a ternary operator:
>>> 'true' if True else 'false''true'>>> 'true' if False else 'false''false'
>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'
31k questions
32.8k answers
501 comments
693 users