If statements are important in any programming language. Python provides if statements, in this article we will discuss single line if statements.
Let’s first understand the syntax of single line if statement in python.
some_expression if condition else other_expression
total_mark = 70 # One line if-else statement result = "Passed" if total_mark > 60 else "Failed" print(result)
Singe line statements reduces number of lines but still maintains code quality, but don’t over use it; long and complex statements can reduce code readability.
One line if statements in Python
Python provides conditional expressions . Sometimes it is also known as ternary operator.
[on_true] if [expression] else [on_false]
x if Condition else y
In one line if statement first the “Condition” is evaluated,
- If it is true then x is evaluated and its value is returned
- If it is false then y is evaluated and its value is returned
Let’s understand with an example.
In the following case we need to check student mark if it is greater than 60 then student passed.
total_mark = 70 result = None if total_mark > 60: result = "Passed" else: result = "Failed" print(result)
Instead of this long if else statements we can use single line if statement as shown below
total_mark = 70 result = "Passed" if total_mark > 60 else "Failed" print(result)
See the difference, the number of lines of code is reduced and code is readable.
As a word or precaution don’t over use one line if statements.
When to use one line if statement?
One line if statements best suited for when an if else returns boolean value. For example.
is_high = False temperature = 50 if temperature > 100: is_high = True else: is_high = False print(is_high)
We can use one line as shown below
temperature = 120 is_high = True if temperature > 100 else False print(is_high)
As we can see it is only three lines of code to check to do the operation.
Why one line if-elif-else is not supported?
Fitting everything in a single line is not a good practice. As per PEP 8 standard, a python code line should not exceed 80 characters,this is why Python does not support the if-elif-else statements as one-liner expressions.
In conclusion, we can turn Python if else statement to ternary operator/conditional expression and it reduces the number of lines of code.