Python One Line if Statement

In our daily life whenever we are trying to solve any real life problems then we may have to write some conditional statements very often. A simple if condition takes 2 or 3 lines if we want to process a statement in it. Suppose we have to write more than 10 conditions in a program. We can see it will take approx 40 to 50 lines of code where we are just repeating the things.

So, python allows us to write the if conditions in a single line which is often called one liner if in Python. This will make our code more readable and less redundant. By using this functionality, we can reduce some spaces in our python code.

Now we will see all the types by using which we can write a one liner if condition in python.

Also Read: Python One Line for Loop

First, we will see a general method of if condition and its output.

Output:

In the above example, we are trying to write a condition to print “Even” if the input number is Even. We can see that if takes 2 lines of code to write this single condition.

Now we will see how we can write the same example in a one liner. There are 2 ways to write it. We will go through both ways one by one.

Python One Line if Statement

Method 1:

Output:

Explanation:

In the above one liner we can see that it is the same as general method, the only difference is there that we did not give the indentation in the code.

Method 2:

Explanation:

In this type of one liner first, we write the statement we want to perform when the conditions are met and after that, we write the condition. We are also writing the else block as Node because in this type of one liner only if statements are not supported, we have to write else statement also. If we do not want to perform any operation in the else block we simply write None after else.

We can use one liner to assign a value to a variable when certain conditions are met.

Example 1:

Output:

Example 2:

Output:

If we input age less than 18 then it will print None.

Explanation:

In above example, we can see that we can use one liner to assign a value to the variable if the certain conditions are met. In the example we are setting the salary value to 10000 if the age is greater than 18 otherwise, we are setting the value of salary to None.

Conclusion

In python, we can use one liner if conditions to write some conditions in a better way in our programs. These one liners will helps us to make our code less redundant and more readable.

We can also use one liners to assign a value to a variable if a certain condition is met otherwise we can set it to None value.

Leave a Comment

Your email address will not be published.