How to write an if-else statement in one line in python
In this article, we will discuss how we can implement the if-else statement in python in a single line. This is also called the ternary operator. In python, the ternary operator doesn’t have syntax like that in c++ or java but working is the same. Let us see this concept with some examples.
Syntax: val1 if [expression] else val2
Explanation: If our if the statement becomes true then we get output as val1 otherwise we get output as val2.Let us see this with an example.
a=10 print(1 if a%2==0 else 0) a=9 print(1 if a%2==0 else 0)
Output
1 0
Here we see that we get output 1 when our number is even else we get output as 0. When the condition evaluates to True, then the result of this one-liner if..else expression will be val1 in this case 1. Whereas, if the condition evaluates to False, then the result of this one-liner expression will be val2 in this case 0.
Here we use integer with our if-else statement. Let us see an example of how to deal with a string.
a=10 print("Number is even" if a%2==0 else "Number is odd")
Output
Number is even
Here we see that how we easily deal with string with this ternary operator or one-liner if-else statement. In a similar way, we can deal with different data types.
With the increase in the simplicity of code, we also have to take some precaution otherwise a situation may arise in which we understand the code in a different way while the code work in a different way. As different operator have different associativity and precedence which increase the responsibility of the programmer to use this operator in a correct way. Let us understand the concept with help of an example.
a=10 b=5 print(a/b*3 if a%2==0 else 1) print(a/(b*3 if a%2==0 else 1))
Output
6.0 0.6666666666666666
Here we see with change in one bracket our output differ but code seems to be similar.This confusion tend to be increase when we write big and complex code.Hence we have to use operator in a proper way.
Note: Conditional expressions have the lowest priority amongst all Python operations.
Nested if-else in one line
We see that we can execute single if-else in a single line easily.Now we see how we can execute multiple if else statement in a single line with the help of an example.
a=10 print("a is negative" if a<0 else "a is positive" if a>0 else "a is 0") #above code is similar as if(a<0): print("a is negative") else: if(a>0): print("a is positive") else: print("a is 0")
Output
a is positive a is positive
Both the code give a similar result. We see how we save 5-6 lines by using the ternary operator.
So in this article, we see how to use the if-else and nested if-else statement in one line and with that, we see how to use the operator effectively otherwise the result may differ.