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)
Can we write if/else into one line in python?
Answer: In if statements, the
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.
Do comment if you have any doubts and suggestions on this Python if-else code.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.