Glossary
HTML
CSS
JavaScript
Python

PYTHON

Python If Statement: Syntax, Usage, and Examples

In Python, conditional statements like the if statement are control flow statements that run (or skip) blocks of code based on specified conditions.

How to Use Python If Statements

Python If Statement

The most basic type of conditional statements are if statements, sometimes also referred to as if conditions in Python. An if statement executes a block of code only if a specified condition evaluates to True. The syntax of an if statement is simple:

if condition:
	# Execute this code if the condition is True
  • if: The keyword that initiates an if statement.
  • condition: A boolean expression that the if statement evaluates. If the condition evaluates to True, the if statement’s body executes. If the condition evaluates to False, the if statement’s body gets skipped.

Python If-Else Statement

An if statement can have an optional else clause to form an if-else statement in Python. The else clause of an if-else statement executes the block of code below the else clause only in case the if statement’s condition evaluates to False.

if condition:
	# Execute this code if the condition is True
else:
	# Execute this code if the condition is False
  • if: The keyword that initiates an if statement.
  • condition: A boolean expression that the if statement evaluates. If the expression evaluates to True, the if statement’s body executes. If the expression evaluates to False, the if statement’s body is skipped.
  • else: The keyword that initiates an else clause.

Python If-Elif-Else Statements

An if statement can have optional elif clauses to form an if-elif statement. Elif clauses can check for additional conditions. As soon as a condition evaluates to True, the block of code below that if or elif clause executes.

if condition1:
	# Execute this code if condition1 is True
elif condition2:
	# Execute this code if condition2 is True
else:
	# Execute this code if condition1 and condition2 are False
  • if: The keyword that initiates an if statement.
  • condition1: A boolean expression that the if statement evaluates. If the condition evaluates to True, the if statement’s body executes. If the condition evaluates to False, the if statement’s body gets skipped.
  • elif: The keyword that initiates an elif clause.
  • condition2: A boolean expression that the elif clause evaluates if the previous condition evaluated to False. If the expression evaluates to True, the elif clause’s body executes and any following elif and else clauses are skipped. If the expression evaluates to False, the elif clause’s body gets skipped.
  • else: The keyword that initiates an else clause.

When to Use Python If Statements

The primary use of Python if statements is to make decisions within a program. This decision-making capability is fundamental to creating dynamic and interactive programs.

Directing Program Flow

If statements allow your program to execute different blocks of code depending on various conditions. Therefore, conditional statements like an if-else statement can direct the flow of your program.

# Decision based on user input
user_input = input("Enter 'yes' to continue, anything else to quit: ")
if user_input.lower() == 'yes':
    print("Continuing...")
else:
    print("Exiting...")

Handling Different Scenarios

If statements enable programs to handle different scenarios. For instance, a program can display different messages based on the success or failure of an operation.

# Handling success or failure
operation_successful = False
if operation_successful:
    print("The operation was successful.")
else:
    print("The operation failed.")

Handling User Input

If statements are crucial for interacting with users, such as validating user inputs or choices and providing appropriate feedback.

# Validating user age
age = int(input("Enter your age: "))
if age < 0:
    print("Invalid age. Age cannot be negative.")
elif age < 18:
    print("You are underaged.")
else:
    print("You are an adult.")

Data Processing

In data-driven applications, if statements allow programs to respond to varying data, adjusting their behavior accordingly.

# Adjusting behavior based on data
stock_price = 150
if stock_price > 100:
    print("Stock price is high.")
elif stock_price > 50:
    print("Stock price is moderate.")
else:
    print("Stock price is low.")

Examples of Python If Statements

Conditions and conditional statements are an essential part of almost every Python program. Here are some common use cases for the different kinds of if statements:

E-commerce Checkout Processes

In an e-commerce platform, if-elif-else statements can determine the final price, including promotions, discounts, and shipping options.

# Applying a discount and calculating shipping
total_price = 150.00
is_member = True
if is_member:
    total_price *= 0.9  # Apply 10% member discount

if total_price > 100:
    shipping_cost = 0  # Free shipping for orders over $100
else:
    shipping_cost = 10

total_price += shipping_cost
print(f"Total price with applicable discounts and shipping: ${total_price:.2f}")

User Authentication

The conditional operator is handy for concise decision-making assignments.

# Authenticating a user
stored_password = "user123"
input_password = input("Enter your password: ")

if input_password == stored_password:
    print("Access granted.")
else:
    print("Access denied. Incorrect password.")

Environmental Monitoring Systems

As another example, consider environmental monitoring systems. If statements with elif and else clauses might trigger alerts based on sensor readings, such as temperature, air quality, or water levels.

# Triggering an alert based on sensor reading
water_level_sensor = 85  # in percentage

if water_level_sensor > 80:
    print("Warning: High water level detected!")
elif water_level_sensor < 20:
    print("Alert: Low water level detected.")
else:
    print("Water levels are normal.")

Automated Email Responses

Automation scripts, such as those for customer service, can use if-else statements, too. For example, they might generate automated email responses based on the subject or content of received emails.

# Automated email response
email_subject = "Refund Request"

if "refund" in email_subject.lower():
    print("Sending automated response for refund requests.")
else:
    print("Sending to the general inquiries queue.")

Learn More About Python Conditional Statements

Nested Conditional Statements

Python allows for conditional statements within conditional statements, enabling complex decision trees. Nesting conditional statements is particularly useful in scenarios where decisions depend on multiple conditions.

num = 15
if num > 10:
    if num % 2 == 0:
        print("Number is greater than 10 and even")
    else:
        print("Number is greater than 10 and odd")

Using Logical Operators in Python Conditional Statements

Logical operators allow you to construct more complex boolean expressions in Python. The three primary logical operators are and, or, and not.

The and operator allows you to combine multiple conditions. and requires all conditions to be True for the entire expression to evaluate to True. This makes it particularly useful when a decision depends on the fulfillment of several criteria.

# Both conditions need to be True
if is_adult and has_ticket:
    print("You can enter.")

or requires only one of the conditions to be True for the entire expression to evaluate to True. This makes it useful in scenarios where there are multiple potential paths to achieve a certain outcome.

# Only one condition needs to be True
if is_vip_member or purchase_amount > 100:
    print("You qualify for free shipping.")

The not operator inverts the truth value of its operand. If a condition is True, adding not in front of it makes it False, and vice versa. This can be particularly helpful for readability, making conditions as clear as possible.

# Inverts the truth value
if not is_form_complete:
    print("Please complete all required fields.")

Short-Circuit Evaluation

If statements and logical operators in Python adhere to the concept of short-circuit evaluation. If the first condition of an expression using the and operator is False, the second condition gets skipped. Similarly, for or, if the first condition is True, the entire expression already evaluates to True.

# If 'condition1' is False, Python won't evaluate 'condition2'
if condition1 and condition2:
    # Execute if both are true

If Statements and Loops

If statements often work in tandem with loops to control flow and logic. They are essential in filtering data, executing specific actions for certain items, and more.

numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        print(f"{num} is even")
    else:
        print(f"{num} is odd")

If Statements and Functions

In functions, if statements can return different outcomes based on the function's input parameters. Therefore, if statements can make functions more dynamic and versatile.

def check_temperature(temp):
    if temp > 30:
        return "It's a hot day."
    elif temp > 20:
        return "It's a nice day."
    else:
        return "It's cold."
print(check_temperature(25))  # "It's a nice day."

Truthy and Falsy Values

In Python, some non-boolean values evaluate to True or False, too. Such "truthy" or "falsy" values can be useful in a boolean context. For example, empty sequences and collections evaluate to False, while non-empty ones evaluate to True.

my_list = []
if not my_list:  # This evaluates to True because an empty list is considered False
    print("List is empty.")

Python Conditional Operator

Like many other programming languages, Python also supports conditional expressions, also known as ternary operators. Conditional expressions allow for simple conditional assignments in a single line of code.

age = 20
status = "Adult" if age >= 18 else "Minor"
print(status)  # Outputs: "Adult"
Learn to Code in Python for Free
Start learning now
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2023 Mimo GmbH