Python if, elif, and else Statements

By 

Updated on

7 min read

Python if..else Statement

Decision-making is one of the most fundamental concepts of computer programming. Python supports the common flow-control statements found in other languages, with a few syntax differences. The if statement is one of the most basic and widely used ways to execute code based on a condition.

This article explains how to use Python if, elif, and else statements with practical examples.

Python if Statement

The most basic form of the if statement in Python is as follows:

py
if EXPRESSION:
  STATEMENT

The if statement starts with the if keyword followed by a conditional expression.

The EXPRESSION must be followed by a colon (:). If the EXPRESSION evaluates to True, the STATEMENT is executed. If the EXPRESSION evaluates to False, nothing happens and the STATEMENT is skipped. STATEMENT can be any statement, including multiple statements or further nested if statements. To execute no statements, use the pass statement.

The STATEMENT block starts with an indentation and ends with the first unindented line. Most people choose to use either 4-space or 2-space indentation. The official Style Guide for Python Code recommends using 4-spaces per indentation level and avoiding mixing tabs and spaces for indentation.

Let us look at the following example script that checks whether a given number is greater than 5.

py
number = int(input('Enter a number: '))

if number > 5:
    print(number, 'is greater than 5.')

Save the code in a file and run it from the command line:

Terminal
python test.py

The script will prompt you to enter a number. For example, if you enter 10, the conditional expression will evaluate to True (10 is greater than 5), and the print function will be executed.

output
10 is greater than 5.

Python supports standard comparison operations:

  • a == b - True if a and b are equal.
  • a != b - True if a and b are not equal.
  • a > b - True if a is greater than b.
  • a >= b - True if a is equal or greater than b.
  • a < b - True if a is less than b.
  • a <= b - True if a is equal or less than b.

You can also use the in keyword to check if a value is present in an iterable (string, list, tuple , dictionary , etc.):

py
s = 'linuxize'
if 'ze' in s:
    print('True.')

Here is another example using a dictionary:

py
d = {'a': 2, 'b': 4}
if 'a' in d:
    print('True.')

When used on a dictionary, the in keyword checks whether the dictionary has a specific key.

To negate the conditional expression use the logical not operator:

py
number = int(input('Enter a number: '))

if not number < 5:
    print(number, 'is greater than 5.')

if..else Statement

An if..else statement evaluates a condition and executes one of the two statements depending on the result.

The Python if..else statement takes the following form:

py
if EXPRESSION:
    STATEMENT1
else:
    STATEMENT2

If EXPRESSION evaluates to True, STATEMENT1 is executed. Otherwise, STATEMENT2 is executed. You can have only one else clause in the statement.

The else keyword must end with a colon (:) and be at the same indentation level as the corresponding if keyword.

Let us add an else clause to the previous example script:

py
number = int(input('Enter a number: '))

if number > 5:
    print(number, 'is greater than 5.')
else:
    print(number, 'is equal or less than 5.')

If you run the code and enter a number, the script will print a different message based on whether the number is greater or less/equal to 5.

if..elif..else Statement

The elif keyword is short for else if.

The Python if..elif..else statement takes the following form:

py
if EXPRESSION1:
    STATEMENT1
elif EXPRESSION2:
    STATEMENT2
else:
    STATEMENT3

If EXPRESSION1 evaluates to True, STATEMENT1 is executed. If EXPRESSION2 evaluates to True, STATEMENT2 is executed. If none of the expressions evaluate to True, STATEMENT3 is executed.

The elif keyword must end with (:) colon and be at the same indentation level as the corresponding if keyword. You can have one or more elif clauses in the statement. The else clause is optional. If the else clause is not used, and all the expressions evaluate to False, none of the statements is executed.

The conditions are evaluated sequentially. Once a condition returns True, the remaining conditions are not performed, and the program control moves to the end of the if statements.

Let us add an elif clause to the previous script:

py
number = int(input('Enter a number: '))

if number > 5:
    print(number, 'is greater than 5.')
elif number < 5:
    print(number, 'is less than 5.')
else:
    print(number, 'is equal to 5.')

Unlike most programming languages, Python does not have a traditional switch statement. Python 3.10 introduced the match/case statement for structural pattern matching, but for simpler branching a sequence of elif clauses is the standard approach. For comparison, see how Bash handles this with the case statement.

Nested if Statements

Python allows you to nest if statements within if statements. Generally, you should always avoid excessive indentation and try to use elif instead of nesting if statements.

The following script will prompt you to enter three numbers and will print the largest number among the numbers.

py
number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
number3 = int(input('Enter the third number: '))

if number1 > number2:
    if number1 > number3:
        print(number1, 'is the largest number.')
    else:
        print(number3, 'is the largest number.')
else:
    if number2 > number3:
        print(number2, 'is the largest number.')
    else:
        print(number3, 'is the largest number.')

Here is how the output will look like:

output
Enter the first number: 455 
Enter the second number: 567
Enter the third number: 354
567 is the largest number.

Multiple Conditions

The logical or and and operators allow you to combine multiple conditions in the if statements.

Here is another version of the script to print the largest number among the three numbers. In this version, instead of the nested if statements, we will use the logical and operator and elif.

py
number1 = int(input('Enter the first number: '))
number2 = int(input('Enter the second number: '))
number3 = int(input('Enter the third number: '))

if number1 > number2 and number1 > number3:
    print(number1, 'is the largest number.')
elif number2 > number3 and number2 > number1:
    print(number2, 'is the largest number.')
else:
    print(number3, 'is the largest number.')

Quick Reference

StatementUse
if condition:Execute block only when condition is True
if condition: ... else:Execute one of two blocks
if condition: ... elif condition2: ... else:Chain multiple conditions
andBoth conditions must be True
orAt least one condition must be True
notNegate a condition
inCheck membership in a sequence or dictionary
isCheck object identity (not equality)

FAQ

What is the difference between == and is in an if condition?
== checks whether two values are equal. is checks whether two variables point to the same object in memory. Use == for value comparisons and is only for identity checks such as if x is None:.

Can an if statement have more than one elif clause?
Yes. You can chain as many elif clauses as needed. Python evaluates them in order and executes only the first block whose condition is True.

What happens if no condition matches and there is no else?
Nothing. Python skips the entire if/elif chain and continues with the next statement after it.

What is the difference between if and elif in Python?
Use if for the first condition and elif for additional conditions that should be checked only if the previous ones were false. This lets you build a clean multi-branch decision chain.

What is a ternary expression in Python?
Python has a one-line conditional expression: value_if_true if condition else value_if_false. For example: label = 'big' if number > 5 else 'small'.

Can I use if inside a list comprehension?
Yes. You can filter items with a trailing if: [x for x in items if x > 0]. This is different from the ternary form, which replaces the value rather than filtering.

Conclusion

The if, if..else, and if..elif..else statements are the primary tools for controlling program flow in Python. Use elif to test multiple conditions in sequence and else to handle the default case when none of the conditions match.

Tags

Linuxize Weekly Newsletter

A quick weekly roundup of new tutorials, news, and tips.

About the authors

Dejan Panovski

Dejan Panovski

Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.

View author page