Python if-else one line can be used as a ternary operator. There is the conditional expression.
a if cond else b
but this is an expression, not a statement.
Example code if..else in a single line in Python
In python need to convert the if…else statement to a one-line conditional expression.
value_1 if condition else value_2
Example of if…else in one line
x = 10
res = 'High' if x > 10 else 'Low'
print(res)
Output:
Can we write if/else into one line in python?
Answer: In if statements, the if
(or elif
or else
) can be written on the same line as the body of the block if the block is just one like:
if something: somefunc()
else: otherfunc()
but this is discouraged as a matter of formatting style.
Source: stackoverflow.com
Do comment if you have any doubts and suggestions on this Python if-else code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.