Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

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.

2 Answers

0 votes
by (106k points)

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

0 votes
by (20.3k points)

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'

'true'

>>> 'true' if False else 'false'

'false'

Browse Categories

...