Python IF ELSE Code Write in One Line

python if else one line code

 

There are many people like you very curious to know how to write simple one liner Python IF ELSE statements. 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 understandable you can write IF-ELSE in one line too.

 

python if-else statements

 

Observe the syntax specified in this example. You can’t re-arrange anything, not even single space! This is ordinary Python if-else statements.

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”)



If Else in one line!

Let’s try to put all IF-ELSE statements in ONE LINE without having any issue with the indentation and generates the same result.

python IF ELSE one liner code

Output

python IF ELSE one liner code output


Few more examples to understand how you can implement one liner IF-ELSE Statements.

  • 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

  • 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

  • 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

>>> 

 

The one liner IF-ELSE code can be used in the loop statements to make your code easily readable.

Read More: Python – IF-ELSE;  For-Loop;  While-Loop
Spread the love

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *