One Line If Elif Else Statements in Python 3


Python If Else Elif One Line

If statements are present in all our code and can in fact be written efficiently in a single line. A condition-less code will be monotonous and one couldn’t do much with such a linear flow. If statements or conditional statements are an indispensable part of a programming flow to make decisions and also to direct the program flow. If... elif... else conditions steer and guide your code based on the conditions that you provide. In this article, you will learn and master the usage of If... elif... else statements in your code.

The Normal If Else Syntax

There are multiple ways to design your control flow using the If clause. Based on the use cases, simplicity, and readability, any of the following syntaxes can be used. And it is important to note that whenever a condition is used, it is used in a boolean context i.e.) Evaluation of a condition results in a boolean value, based on which the decision is take, whether to execute the expression or not to.

a) If Statement In Python

if <condition>:
    expression

A standard if block contains a condition and an expression. If the condition is tested to be True, the expression gets executed. If the condition is tested to be False, the expression won’t be executed.

'''
Snippet to check if the provided number is positive - If clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if numberInput >= 0:
    print ("The number {} is positive".format(numberInput))

if numberInput < 0:
    print ("The number {} is negative".format(numberInput))
Positive/negative number Program Output: Native If clause Demonstration

b) If… else Statement In Python

if <condition>:
    expression 1
else:
    expression 2

In the case of two conditions, either of the two conditions may hold True. In this case, the expression belonging to the condition which is tested to be True, gets executed and if this condition is tested to be False, the expression belonging to the else block gets evaluated.

'''
Snippet to check if the provided number is positive - If... else clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if a>=0:
    print ("The number {} is positive".format(numberInput))
else:
    print ("The number {} is negative".format(numberInput))
Positive/negative number Program Output: Native If-Else clause Demonstration

c) If… elif… else Statement In Python

if <condition 1>:        # If True, Execute this block and exit
    expr1
elif <condition 2>:      # If True, Execute this block and exit
    expr2
elif <condition 3>:
    expr3
else:
    do = 'this and that'

The snippet above shows the skeleton of an if... elif... else block. The block under each condition gets executed only if the condition returns True and a summary of it can be given as:

  • Each condition ends with a colon (:)
  • The statements under each condition is a block with an indentation.
  • Don’t have more than a single condition? You may avoid elif block!
  • An else condition is optional; Yes, you heard that right!

Maybe python is a new language to you or you have transitioned from another language, getting the hang of scripting in python and you might be wondering, why is else if being written as elif? Python is well known for its code readability with mandatory indentations. In fact, that’s the reason why, for better readability and to avoid excessive indentation, else if is referred to as elif.

Let’s get our hands dirty with a practical example for an ‘if-else-if’ use case:

'''
Snippet to check if the provided number is odd or even - If... Elif... Else... demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if numberInput%2 == 0: 
             # Even numbers are divisible by 2
    print ("The number {} is even".format(numberInput))
elif numberInput%2 != 0:
             # Odd numbers are not divisible by 2
    print ("The number {} is odd".format(numberInput))
else:
    print ("You have entered an invalid Number")
Odd/Even number Program Output: Native If-Elif-Else Demonstration

Checking for Multiple Conditions

In the previous section, we examined the skeleton of an If-Elif-Else block, in which each block contains a single condition. What if we wanted to have multiple conditions in a single if statement to be validated for each block? This can be done using logical operators: and, or.

if <condition 1> and <condition 2>:  # If True, Execute this block and exit
    expr1
elif <condition 3> or <condition 4>: # If True, Execute this block and exit
    expr2
elif <condition 5>:
    expr3
else:
    do = 'this and that'

condition 1 and condition 2 ==> both the conditions must be True

condition 3 or condition 4 ==> Either of the conditions must be True

For an and logical operator, if the first condition fails, the execution skips the second condition, since the validation depends on both the conditions. Let’s observe a practical example to demonstrate the usage of multiple conditions in an If Statement as follows:

'''
Snippet to find the biggest of three numbers - If Elif Else multiple conditions demonstration
'''

number_input = input("Enter three numbers separated with spaces: ")
a, b, c = number_input.split(' ')

if (a>=b) and (a>=c):
    print ("{} is the biggest".format(a))
elif (b>=a) and (b>=c):
    print ("{} is the biggest".format(b))
else:
    print ("{} is the biggest".format(c))

A Pythonic take on the If Else condition

Now that we have an understanding of how an if... elif... else conditional blocks work, let’s learn how the cool kids write the same as a one-liner. In the following sections, the examples are rewritten based on the pythonic take on the if... elif... else block.

a) One line if statements

if condition: expr

An one-liner if statement contains both the condition and the expression on a single line. This is a time saving way of writing an if statement with a single condition. Few things to note:

  • The colon (:) differentiates your condition from the expression. The space between the colon (:) and the expression (expr) need not be confined to just a single space, the indentation between them is not strict.

The following example is the one-line version of the normal if syntax.

'''
Snippet to check if the provided number is positive - If clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

if numberInput >= 0: print ("The number {} is positive".format(numberInput))
if numberInput < 0: print ("The number {} is negative".format(numberInput))
Positive/negative number Program Output: One Line If clause Demonstration

b) One line if… else

expr if condition else expr

An one line if...else statement contains both the condition and the expression on a single line and the returning value needs to be assigned to a variable or passed to a function.

The following example is the one-line version of the normal if... else syntax.

'''
Snippet to check if the provided number is positive - If... else clause demonstration
'''

print ("Enter your number: ")
numberInput = int(input())
#The input is received as string, hence we convert it to an integer

print ("The number {} is positive".format(numberInput) if numberInput>=0 else "The number {} is negative".format(numberInput))
Positive/negative number Program Output: One Line If-Else clause Demonstration

c) One line if… else… if… else

expr1 if condition1 else expr2 if condition2 else expr

This lets you wrap up things pretty quickly. However, a few aspects contradict what you have learned so far when you write it as a one-liner:

  • The else after the last condition is mandatory with a value to be returned.
  • Each condition and expression is split by an else clause and not by an elif.

Time for a demonstration on the learnings from above:

'''
Snippet to check if the provided number is odd or even - If Elif Else demonstration
'''

print ("Enter your number: ")
numberInput = int(input())

# An if-else-if clause in a single line; how cool is that?

print ("Number is Even" if numberInput%2 == 0 else "Number is Odd" if numberInput%2 != 0 else "Invalid")
Odd/Even number Program Output: One Line If-Else If-Else Demonstration

Wait, but where is the switch statement?

No, we don’t have any switch statements or switch cases in Python. You can use a if..elif..else statement to do the same thing (and in some cases, use a python dictionary to do it even faster).

Summary

Practicing the above given examples, you can master the aspects of using the flow structure if... elif... else clause in your script, effectively. Although one-line conditions are time-saving, it gives poor readability to the code. It is a tradeoff between the time and the readability and it’s up to you to decide on the syntax. Some of the other commonly used control flow statements include: while and for loop with break and continue statements.

Subscribe to our newsletter

Get new tips in your inbox automatically. Subscribe to our newsletter!

Leave a Reply

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

Recent Content