Python if...else Statement

In Python, the if statement allows us to run or skip a block of code based on a specified condition. This enables us to create programs that respond differently depending on the situation.

For example, a gambling website should grant access to its content only if the user's age is 18 or above.


Python if Statement

Let's start with a simple if statement. Later in the tutorial, we'll cover if with the else and elif clauses.

The syntax of if is:

if condition:
    # This code runs only if condition is True

Here, condition is a boolean expression, such as age >= 18, that evaluates to either True or False.

The body of if (indented block of code just below it) is executed if condition is True and skipped if it's False.


Example: Python if Statement

age = int(input("Enter your age: "))

# Check if age is 18 or more
if age >= 18:
    print("Grant access to the website.")

print("Program complete.")

Output 1

Enter your age: 22
Grant access to the website.
Program complete.

Output 2

Enter your age: 17
Program complete.

As you can see, the "Grant access..." message is printed only when age is 18 or greater because of the age >= 18 condition.

The "Program complete." message is outside the if statement (no indentation). Hence, it's executed every time.

Note: To see how this program works step by step, click the Visualize button in the code examples to run the code visualizer.


Indentation in Python

Python uses indentation to define a block of code, such as the body of an if statement. Let's write the above code without indentation and see what happens.

age = int(input("Enter your age: "))

if age >= 18:
print("Grant access to the website.")

print("Program complete.")

Output

  File "main.py", line 4
    print("Grant access to the website.")
    ^^^^^
IndentationError: expected an indented block after 'if' statement on line 3

Here, Python treats the if statement as having an empty body because the code immediately after it is not indented. That's the reason for the error.

If you need to put multiple lines of code inside the body of the if statement, you should maintain the same indentation level. For example,

age = int(input("Enter your age: "))

if age >= 18:
    print("Grant access.")
    print("Show products.")

print("Program complete.")

Here, print("Grant access.") and print("Show products.") are both part of the if statement.


Python if...else Statement

An if statement can have an optional else clause, which is executed when the condition in the if statement evaluates to False. This enables us to run two different blocks of code depending on whether the condition is True or False.

The syntax of if...else is:

if condition:
    # Run this code if condition is True
else:
    # Run this code if condition is False

Example: Python if…else Statement

age = int(input("Enter your age: "))

if age >= 18:
    print("Grant access.")
else:
    print("Deny access.")

Output 1

Enter your age: 22
Grant access.

Output 2

Enter your age: 16
Deny access.

The else clause catches everything that doesn't match the previous conditions.


Example: Authenticate User Logic Using if...else

# Username and password stored in database
username_db = "admin"
password_db = "sparrow@123"

# Username and password entered by the user
username = input("Enter username: ")
password = input("Enter password: ") 

# Check if username & password in database matches user's input
if (username == username_db) and (password == password_db):
    print("Welcome back.")
else:
    print("Access denied.")

The logic here is that if username and password entered by the user matches data stored in the database, it's a valid login.


Python if…elif…else Statement

The if...else statement is used to execute a block of code among two alternatives.

However, if we need to make a choice between more than two alternatives, we can use the if...elif...else statement.

Syntax

if condition1:
    # Run this code if condition1 is True
elif condition2:
    # Run this code if condition1 is False but condition2 is True
else: 
    # Run this code if both condition1 and condition2 are False

Example: Python if…elif…else Statement

age = int(input("Enter your age: "))

if age < 0:
    print("Invalid age.")
elif age >= 18:
    print("Grant access.")
else:
    print("Deny access.")

Output 1

Enter your age: -5
Invalid age.

Output 2

Enter your age: 21
Grant access.

Output 3

Enter your age: 14
Deny access.

If you're having trouble following this program, click the Visualize button above to see exactly what happens at each step.

An if statement can have multiple elif statements but only one else clause at the end. Also, using else after elif is not mandatory. We could have written the above program as:

age = int(input("Enter your age: "))

if age < 0:
    print("Invalid age.")
elif age < 18:
    print("Deny access.")
elif age >= 18:
    print("Deny access.")

Nested if Statements

It is possible to include an if statement inside another, known as nested if. For example,

age = int(input("Enter your age: "))

# Condition to check if age is less than 18
if age < 18:

    # If age is less than 18, condition to check if it's negative
    if age < 0:
        print("Invalid age.")
    else:
        print("Deny access.")
else:
    print("Grant access.")

The output of this program is the same as the above programs. However, nested statements make logic a bit more complicated. That's why it's better to avoid nested if statements whenever possible.

If you're having trouble following this program, click the Visualize button to see exactly what happens at each step.


Short Hand if...else

You can write a simple if...else in a single line in some cases. For example,

age = 22
status = "Adult" if age >= 18 else "Minor"
print(status)

This is equivalent to:

age = 22

if age >= 18:
    status = "Adult"
else:
    status = "Minor"

Example: Largest of Three Numbers

The general logic of finding the largest number among n1, n2 and n3 is that:

  • If n1 is greater than both n2 and n3, n1 is the largest.
  • If n2 is greater than both n1 and n3, n2 is the largest.
  • Otherwise, n3 is the largest.
# Taking input from the user
n1 = float(input("Enter the first number: "))
n2 = float(input("Enter the second number: "))
n3 = float(input("Enter the third number: "))

if n1 >= n2 and n1 >= n3:
    largest = n1
elif n2 >= n1 and n2 >= n3:
    largest = n2
else:
    largest = n3

print("The largest number is:", largest)

Run and visualize this program to see the output for yourself.

Did you find this article helpful?