if-elif-else statement in one single line in Python
Writing if-elif-else in multiple lines is old fashion. Everyone will write, so how about writing it in a single line.
In this tutorial, we learn how to write if-elif-else statements in one single line in Python.
For writing if-elif-else in one line in python we use the ternary operator. The ternary operator is also known as a conditional expression. This operator evaluates something based on a condition being true or false. It replaces multiple line if-else statements with single lines.
syntax:
[True] if [expression] else [False]
let’s write a simple program
a. Using python if-else statement
age=15 if age>18: print('major') else: print('minor')
output: minor
b. Using the ternary operator
age=15 x='minor' if age<18 else 'major' print(x)
output: minor
let’s try some nested if-else statements
a. Using python if-else statement
age= int(input()) if age<12: print('child') elif age<20: print('teen') elif age<30: print('young') elif age<50: print('middle age') else: print('old')
output: 11 child 15 teen
b. Using the ternary operator
age=int(input()) x='child' if age<12 else 'teen' if age<20 else 'young' if age<30 else 'middle age' if age<50 else 'old' print(x)
output
11 child 15 teen
Note: Writing multiple-line code in a single line reduces the code readability. So if the conditions are a little complex then it is suggested to write the code in normal format. If the code is easy then follow this ternary operator.
Leave a Reply