Python Multiple if Statements on One Line

Python Multiple if Statements on One Line

Whenever we write an if-elif-else block, we write them in separate lines. But there is a way to write those statements in one line too. However, it’s not recommended because it reduces the readability and understandability of the code. But for general knowledge, we can write those statements in one line of code too.

Example Code:

# python 3.x
a=2
b=3
if a<b:
    print("a is less than b")
elif a==b:
    print("a is equal to b")
else:
    print("a is greater than b")
    

Output:

a is less than b

Write Multiple if Statements on One Line in Python

Now if we want to write the same if-elif-else block of code in a single line. We have to write the code as follows.

In this code, first, we print a message to show when the condition a<b is true, if not, the code will print the second message if the condition a==b is true. And again, if none of the above conditions is true, then the print statement within the else part will be executed.

Example Code:

# python 3.x
a=2  
b=3
print("a is less than b") if a<b else ("a is equal to b" if a==b else "a is greater than b")

Output:

a is less than b
Author: Fariba Laiq
Fariba Laiq avatar Fariba Laiq avatar

I am Fariba Laiq from Pakistan. An android app developer, technical content writer, and coding instructor. Writing has always been one of my passions. I love to learn, implement and convey my knowledge to others.

LinkedIn

Related Article - Python Statement

  • Nested try...except Statements in Python
  • Python Multi-Line if Condition
  • if...else in One Line Python
  • The for...else Statement in Python