Open In App

Python If Else on One Line

Last Updated : 08 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The if-elif-else statement is used in Python for decision-making i.e. the program will evaluate the test expression and execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions. This article will show how the traditional if…elif…else statement differs from If Elif in Python.

Python Shorthandf If Else

In the traditional if elif else statement in Python, the conditions are written in different blocks of code, and each block of code is indented according to the parent if condition. It is mostly used when there is a multiple-line code, which makes it easier to understand.

Syntax of if elif else statement

if (condition):
    statement
elif (condition):
    statement
else:
    statement

Example: In this example, we will find if a number if positive, negative or zero using the if-elif-else statement.

Python
x = 0

# traditional python if elif else statement
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

Output:

Zero

The concept can also be implemented using the short-hand method using Python Ternary Operation.

One Liner if elif else Statements

The one-liner if elif else statement in Python are used when there are a simple and straightforward conditions to be implemented. This means that the code can be fitted in a single line expression. It uses a Python dictionary like structure along with Python dictionary get() method.


Python If Else on One Line

Python if elif else statement structure


Syntax of Python one-liner if elif else Statement:

This can be easily interpreted as if condition 1 is True run code 1 if condition 2 is True run code 2 and if both of them are false run the third code.

{(condition1 :  <code1>) , (condition2 :  <code2>) }.get(True, <code3>)

Example: In this example, we will find if a number if positive, negative or zero. First, we declared a number in ‘x’ variable. Then we used one liner python if elif else statement to check the three conditions.

Python
x = 0

# Python one liner if elif else statement
result = {x > 0: "Positive", x < 0: "Negative"}.get(True, "Zero")

print(result)

Output:

Zero

Note: There are a few important things to keep in mind while using one liner for python if elif else statement. One of them is that, it works on the concept of python dictionary. This means the conditions are stored in the form of dictionary keys and the statement to be executed is stored in the form of dictionary values. One the keys, that is the condition returns True, only then the value of the corresponding key is executed.

Example: In this code we provide conditions as the dictionary keys, and the code to execute as the values. But this code won’t get you the desired results for this syntax of if-elif-else in Python. It will evaluate all three conditions and perform its corresponding action.

Python
x = 0

{x > 0: print("Positive"), x < 0: print("Negative")}.get(True, print("Zero"))

Output:

Positive
Negative
Zero

Similar Reads

Compare two Files line by line in Python
In Python, there are many methods available to this comparison. In this Article, We'll find out how to Compare two different files line by line. Python supports many modules to do so and here we will discuss approaches using its various modules. This article uses two sample files for implementation. Files in use: file.txt file1.txt Method 1: Using
3 min read
Read a file line by line in Python
Prerequisites: Open a file Access modes Close a file Python provides inbuilt functions for creating, writing, and reading files. There are two types of files that can be handled in python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file. Method 1: R
7 min read
Using Else Conditional Statement With For loop in Python
Using else conditional statement with for loop in python In most of the programming languages (C/C++, Java, etc), the use of else statement has been restricted with the if conditional statements. But Python also allows us to use the else condition with for loops. The else block just after for/while is executed only when the loop is NOT terminated b
2 min read
Python Else Loop
Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let's see the example of while loop and for loop with else below. Else with While loop Consider the below example. C/C++ Code i=0 while i&lt;5: i+=1 print(&quot;i =&quot;
3 min read
Lambda with if but without else in Python
In Python, Lambda function is an anonymous function, which means that it is a function without a name. It can have any number of arguments but only one expression, which is evaluated and returned. It must have a return value. Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we a
3 min read
How to use if, else &amp; elif in Python Lambda Functions
Lambda function can have multiple parameters but have only one expression. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to use if, else &amp; elif in Lambda Functions. Using if-else in lambda function The lambda function will return a value for every valida
2 min read
Try, Except, else and Finally in Python
An Exception is an Unexpected Event, which occurs during the execution of the program. It is also known as a run time error. When that error occurs, Python generates an exception during the execution and that can be handled, which prevents your program from interrupting. Example: In this code, The system can not divide the number with zero so an ex
4 min read
Python While Else
Python is easy to understand and a robust programming language that comes with lots of features. It offers various control flow statements that are slightly different from those in other programming languages. The "while-else" loop is one of these unique constructs. In this article, we will discuss the "while-else" loop in detail with examples. Wha
6 min read
Python List Comprehension Using If-Else
List comprehension in Python is a way to make the elements get added to the list more easily. We can use if-else with List Comprehension which makes the code smaller and more modular instead of using long if-else conditions making it very unstructured. In this article, we will see how we can use list comprehension with Python if-else. List Comprehe
3 min read
Python If Else Statements - Conditional Statements
In both real life and programming, decision-making is crucial. We often face situations where we need to make choices, and based on those choices, we determine our next actions. Similarly, in programming, we encounter scenarios where we must make decisions to control the flow of our code. Conditional statements in Python play a key role in determin
6 min read