Skip to content

Python one line if elif statement | Example code

  • by

Python If elif statement is used for decision-making logic. You can validate multiple expressions using if-elif-else Statements.

We can write this if..elif..else block in one-line using this syntax:

expr1 if condition1 else expr2 if condition2 else expr

Write If elif else in one line python

Evaluate test expression and execute the statements only if the given test expression is true.

One Liner for Python if-elif-else Statements example code.

b = int(input("Enter value for b: "))
a = "neg" if b < 0 else "pos" if b > 0 else "zero"

print(a)

Output:

Python one line if elif statement

The same code in the multiline form

b = int(input("Enter value for b: "))

if b < 0:
   a = "neg"
elif b > 0:
   a = "pos"
else:
   zero

print(a)

One-line different expressions for different cases with if else

Without user input.

num = 10

res = "Neg" if num < 0 else "Pos" if num > 0 else "Zero"

print(res)

Output: Pos

Note: Use ternary operator in one-liner if and else condition with Python.

Do comment if you have any doubts and suggestions on this Python if elif example 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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading