You may not know but it’s absolutely possible to write Python IF-ELSE code in one line! Do you want to know how?
Let’s find out together! HOW?
There are many curious people like you want to know how to write a simple one liner Python IF ELSE code. Because of indentation in Python space has its own value and one extra space can crash your program.
To make your lengthy code looks short and easy human readable, you can write IF-ELSE in one line too.
Python: if – else Statement
Observe the syntax specified in this example. You can’t re-arrange anything, not even single space here and there! This is ordinary Python if-else statement.
Syntax:
if expression:
statement(s)
else:
statement(s)
For example,
This program will ask you to enter your age and check for the eligibility to print whether you are eligible for voting or not!
age=int(input("Enter your age:"))
print("Your age is ", age)
if age>18:
print("You are eligible to vote")
else:
print("You are NOT eligible to vote")
Output:
#Check for eligibility
print("You are eligible to vote") if age>18 else print("You are NOT eligible to vote")
Observe the arrows marked in below screenshot indicates position of “if” & “else” in one liner code.
Few more examples to understand how you can implement one liner IF-ELSE Statements.
1. Set value for variable “b”
IF a=25 then set b=20 ELSE set b=10
>>> a=10
>>> b=20 if a==25 else 10
>>> print(b)
10
2. Set value for variable “b”
IF var=”OneLineCode” then set b=20 ELSE set b=10
>>> var=”OneLineCode”
>>> b=20 if var==”OneLineCode” else 10
>>> print(b)
20
3. Set value for variable “b”
IF var=”not_matching_str” then SET b=”New str” ELSE Set b=”TheEnd”
>>> var=”matching”
>>> b=”New str” if var==”not_matching_str” else “TheEnd”
>>> print(b)
TheEnd
>>> print(var)
matching
Tip: The one liner Python IF-ELSE code can be used in the multiple loop statements to make your code easily readable.
Interesting read,