Is there an easier way of writing an if-elif-else statement so it fits on one line?
For example,
if expression1: statement1 elif expression2: statement2 else: statement3 Or a real-world example:
if i > 100: x = 2 elif i < 100: x = 1 else: x = 0 I just feel if the example above could be written the following way, it could look like more concise.
x = 2 if i>100 elif i<100 1 else 0 # [WRONG] I have read the link below, but it doesn't address my question.
- Does Python have a ternary conditional operator? (the question is about condensing an if-else statement to one line)
elifis just syntactic sugar forelsewith a nestedif. Your example assigns expressions to the same variable; the assignment can be factored out. If the question is supposed to be about arbitrary statements then a) it needs an example that doesn't refactor so simply and b) no, obviously not.