-1

Let's say I have a conditional check like:

if a > b:
    m = a
else:
    m = b

Then I know it could be written in one line as:

m = a if a > b else b

How to write similar one liner expression if elif statements are also present in conditional check? For something like:

if a > b:
   m = a
elif a > c:
   m = c
else:
   m = b
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
Luismaia1994
  • 143
  • 1
  • 8
  • see this: https://www.pythoncentral.io/one-line-if-statement-in-python-ternary-conditional-operator/ – Pygirl Jan 16 '21 at 13:43
  • I didn't downvote but I guess this question has been asked so many times in SO that's why someone downvoted the answers. – Pygirl Jan 16 '21 at 13:52
  • 1
    Its not by bad intention that I did the question but sometimes the title don't help that's why I did not found an equal question. Also when I was review my question this site did not ask me to look for another question that would be equal – Luismaia1994 Jan 16 '21 at 13:55
  • 1
    I understand :) Try to search by keywords (not by a sentence) like this `if elif else one line python` – Pygirl Jan 16 '21 at 14:02

4 Answers4

1

Let's say if your conditional statement is like:

if a > b:
   m = a
elif a > c:
   m = c
else:
   m = b

You can put it in nested if-else in single line as:

m = a if a > b else (c if a > c else b)

In above statement you can even skip the usage of brackets (..). I added it for explaining the execution order. Below code without brackets will return the same answer:

m = a if a > b else c if a > c else b

In general, for code like this:

if COND_1:
    m = A
elif COND_2:
    m = B
elif COND_3:
    m = C
else:
    m = D

You can make your one liner nested conditional statement as:

 m = A if COND_1 else (B if COND_2 else (C if COND_3 else D))
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

See this answer

value_when_true if condition else value_when_false

'Yes' if fruit == 'Apple' else 'No'
thehand0
  • 1,123
  • 4
  • 14
0

Syntax for elif condition we will as followed.

a = 34
b = 42
c = 54

m = a if a > b else (b if b > c else c) 
print(m)

Result: 54

Rorschach
  • 62
  • 7
-1

You can chain conditions just like this:

m = "a" if CONDITION_1 else "b" if CONDITION_2 else "c"
Marc Dillar
  • 471
  • 2
  • 9