How to use 'if' in Python

The if statement in Python enables conditional execution, forming the foundation of program logic and decision-making. This fundamental control structure lets developers create dynamic, responsive code that adapts to different scenarios and user inputs.

This guide covers essential techniques, practical tips, and real-world applications for mastering conditional statements. All code examples were created with Claude, an AI assistant built by Anthropic, to demonstrate effective implementation.

Basic if statement

x = 10
if x > 5:
    print("x is greater than 5")
x is greater than 5

The basic if statement demonstrates a straightforward condition that evaluates a boolean expression. In this example, the comparison operator > checks if the value of x exceeds 5. When this condition evaluates to true, Python executes the indented code block below it.

This pattern forms the basis for more complex conditional logic. The key benefits of this approach include:

  • Clear, readable syntax that maps directly to natural decision-making processes
  • Efficient execution since Python only runs the indented code when needed
  • Flexibility to handle both simple comparisons and complex boolean expressions

Basic conditional techniques

Building on the basic if statement, Python offers powerful conditional techniques that combine multiple decision paths and logical operators for sophisticated program control.

Using if-else statements

age = 17
if age >= 18:
    print("You are an adult")
else:
    print("You are a minor")
You are a minor

The if-else statement extends conditional logic by providing an alternative execution path. When the initial condition age >= 18 evaluates to false, Python automatically runs the code in the else block instead.

  • The else clause requires no condition. It simply executes when the if condition is false
  • This creates a binary decision structure. Exactly one code block will always run
  • The indentation clearly groups statements that belong to each execution path

In the example, Python evaluates if 17 is greater than or equal to 18. Since this comparison returns false, the program outputs "You are a minor" from the else block.

Working with if-elif-else chains

score = 85
if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
else:
    print("Grade: D")
Grade: B

The if-elif-else chain creates a sequence of conditions that Python evaluates from top to bottom. When it finds the first true condition, it executes that block and skips all remaining checks. In this example, since score is 85, Python skips the first condition but executes the second block because 85 is greater than 80.

  • Each elif adds a new condition to check, making the code more efficient than separate if statements
  • The optional else block serves as a catch-all for when no conditions are met
  • Python stops checking conditions after finding a match, preventing unnecessary comparisons

This structure works particularly well for grading systems, menu selections, or any scenario requiring multiple distinct conditions. The order matters—Python evaluates higher grade thresholds first to ensure accurate classification.

Combining conditions with logical operators

temperature = 28
humidity = 65
if temperature > 30 and humidity > 60:
    print("Hot and humid")
elif temperature > 30 or humidity > 60:
    print("Either hot or humid")
else:
    print("Pleasant weather")
Either hot or humid

Logical operators enable you to combine multiple conditions into a single expression. The and operator requires both conditions to be true, while or needs only one condition to be true.

  • In this weather example, the first condition checks if both temperature exceeds 30 and humidity tops 60%. Since neither condition is met (temperature is 28), Python moves to the next check
  • The second condition uses or to test if either value exceeds its threshold. Because humidity (65) is above 60%, this condition evaluates to true
  • The else block would only execute if both temperature and humidity stayed below their thresholds

This pattern works well for scenarios requiring multiple data points to make decisions. The order matters—Python evaluates the most specific condition first before moving to broader checks.

Advanced conditional patterns

Building on these foundational patterns, Python offers sophisticated conditional techniques like the all() function and ternary operators that streamline complex decision logic into elegant, maintainable code.

Conditional expressions (ternary operator)

age = 20
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}")
Status: adult

The ternary operator provides a concise way to write simple if-else statements in a single line. Python's syntax follows a natural language structure: value_if_true if condition else value_if_false.

  • The expression status = "adult" if age >= 18 else "minor" compresses what would normally require multiple lines into an elegant one-liner
  • Python evaluates the condition age >= 18 first. Based on the result, it assigns either the value before if or after else to the variable
  • This pattern works best for straightforward conditional assignments where you're choosing between two values

While ternary operators enhance code readability for simple conditions, traditional if-else blocks remain more suitable for complex logic or multiple statements.

Nested if statements

num = 15
if num > 0:
    if num % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")
else:
    print("Non-positive number")
Positive odd number

Nested if statements create hierarchical decision trees by placing one conditional block inside another. The outer if statement first checks if num is positive. Only when this condition is true does Python evaluate the inner condition to determine if the number is even or odd.

  • The modulo operator % checks for even numbers by testing if there's a remainder when divided by 2
  • This structure creates a logical flow: first determine if the number is positive then classify it further
  • The else statement at the inner level only executes for positive odd numbers
  • The outer else catches all non-positive numbers without checking if they're even or odd

While nesting enables precise control flow, too many levels can make code harder to follow. Consider flattening deeply nested conditions using compound logical operators when possible.

Using all() and any() with conditions

numbers = [4, 8, 12, 16]
if all(num % 2 == 0 for num in numbers):
    print("All numbers are even")
if any(num > 10 for num in numbers):
    print("At least one number is greater than 10")
All numbers are even
At least one number is greater than 10

The all() and any() functions streamline validation across iterables like lists. all() returns True only when every element meets the condition, while any() returns True if at least one element matches.

  • The first condition uses all() to verify that each number in the list is even by checking if the remainder after division by 2 equals 0
  • The second condition employs any() to detect if the list contains at least one number greater than 10
  • Both functions accept generator expressions, making them memory efficient for large datasets

These functions eliminate the need for explicit loops and multiple conditional checks. They transform complex validations into clear, readable statements that express intent directly.

Calculating discounts in an online shop

This example demonstrates a practical e-commerce discount system that combines membership status and purchase thresholds using if-elif-else logic to calculate personalized savings for customers.

purchase_amount = 120
is_member = True

if is_member and purchase_amount >= 100:
    discount = 0.15
elif is_member or purchase_amount >= 200:
    discount = 0.10
else:
    discount = 0.05

final_price = purchase_amount * (1 - discount)
print(f"Final price after {discount*100:.0f}% discount: ${final_price:.2f}")

This code implements a tiered discount system based on two key factors: membership status and purchase amount. The if-elif-else chain applies the highest discount (15%) when both conditions are met: the customer is a member and spends at least $100. A middle-tier 10% discount activates if either condition is true. All other scenarios receive a base 5% discount.

The final calculation uses the formula purchase_amount * (1 - discount) to apply the discount. The print statement formats the output with clear percentage and dollar values using f-string formatting.

  • Members spending $100+ get 15% off
  • Members or $200+ purchases get 10% off
  • All other purchases get 5% off

Weather advisory system with if statements

This weather advisory system demonstrates how nested if statements can process multiple environmental conditions to generate appropriate safety recommendations based on temperature, precipitation type, and wind speed measurements.

temperature = 5
precipitation = "snow"
wind_speed = 25

if temperature < 0 and precipitation == "snow" and wind_speed > 30:
    print("Stay home! Blizzard conditions.")
elif temperature < 0:
    print("Wear a heavy coat, gloves, and a hat.")
elif temperature < 10 and precipitation in ["rain", "snow"]:
    print("Bring an umbrella and wear a warm coat.")
else:
    print("Dress for mild weather.")

This weather advisory system uses nested conditions to determine appropriate clothing recommendations based on three environmental variables. The code evaluates temperature, precipitation type, and wind speed in decreasing order of severity.

  • The first condition checks for blizzard conditions by combining three requirements with the and operator
  • If temperatures drop below freezing but other conditions aren't severe, it suggests winter gear
  • For cool temperatures with rain or snow, it recommends weather protection

The in operator efficiently checks if precipitation matches either "rain" or "snow" in a list. The else statement serves as a catch-all for mild conditions when no warnings are needed.

Common errors and challenges

Even experienced Python developers encounter several common pitfalls when working with conditional statements that can lead to unexpected behavior or syntax errors.

Forgetting to use == for equality comparison

One of the most frequent syntax errors occurs when developers use a single equals sign = for comparison instead of the correct double equals == operator. The single equals performs assignment while double equals tests for equality. This distinction trips up both new and experienced programmers.

x = 10
if x = 5:
    print("x equals 5")
else:
    print("x does not equal 5")

The code will raise a SyntaxError because Python interprets the single equals as an attempt to assign a value within the conditional statement. The following example demonstrates the correct implementation.

x = 10
if x == 5:
    print("x equals 5")
else:
    print("x does not equal 5")

The corrected code uses == for comparison instead of =, which Python reserves for variable assignment. This distinction matters because == checks if two values are equal while = assigns a new value to a variable.

  • Watch for this error especially when copying code from text editors that auto-format punctuation
  • Python's error message will point to a syntax error near the = operator
  • Modern IDEs often highlight this issue before you run the code

A quick way to remember: think "equals equals" when you want to compare values. The single = means "becomes" or "gets assigned the value of."

Confusing and/or operator precedence

Python's logical operators and and or follow specific precedence rules that can create unexpected results in complex conditions. The order in which Python evaluates these operators often surprises developers who assume left-to-right evaluation.

age = 25
income = 30000
credit_score = 700
if age > 18 or income > 25000 and credit_score > 650:
    print("Loan approved")
else:
    print("Loan denied")

The code's ambiguous operator precedence means Python evaluates and before or. This creates a different logical flow than what many developers expect. The following example demonstrates the correct implementation using parentheses.

age = 25
income = 30000
credit_score = 700
if (age > 18 or income > 25000) and credit_score > 650:
    print("Loan approved")
else:
    print("Loan denied")

The parentheses in the corrected code explicitly define the order of operations, ensuring Python evaluates the loan criteria as intended. Without parentheses, Python evaluates and before or, which could incorrectly approve loans for applicants with good credit scores who don't meet age or income requirements.

  • Always use parentheses to group complex logical conditions
  • Remember that and has higher precedence than or
  • Test your conditions with edge cases to verify the logic works as expected

This pattern appears frequently in financial calculations, user authentication, and data validation. Watch for it when combining multiple boolean conditions with different operators.

Improper indentation in nested if blocks

Indentation errors frequently break Python code, especially in nested if statements where multiple levels of indentation control the program flow. Python uses whitespace to determine which code blocks belong to each conditional statement. The following example demonstrates a common indentation mistake.

temp = 15
if temp < 20:
print("It's cool outside")
    if temp < 10:
        print("It's very cold, wear a jacket")

The code fails because the first print statement lacks proper indentation under the initial if statement. Python requires consistent indentation to recognize which code belongs to each conditional block. The corrected version appears below.

temp = 15
if temp < 20:
    print("It's cool outside")
    if temp < 10:
        print("It's very cold, wear a jacket")

The corrected code properly indents all statements within their respective if blocks using consistent spacing. Python requires each nested level to align with its parent conditional statement. This creates a clear visual hierarchy that matches the logical flow of the program.

  • Each indented block must start at the same column position
  • Most Python developers use 4 spaces per indentation level
  • Modern code editors highlight indentation issues before execution

Watch for this error especially when copying code between different editors or when mixing tabs with spaces. Python's error messages will point to the exact line where indentation breaks the expected pattern.

FAQs

What is the basic syntax for writing an if statement in Python?

Python's if statement evaluates a condition and executes code when that condition is true. The basic syntax starts with if, followed by a condition, and ends with a colon. Python uses indentation to define the code block that should run when the condition is met.

  • The condition must evaluate to either True or False
  • Python reads indented code as part of the if statement
  • You can include an optional else clause to handle cases when the condition is false

This structure reflects Python's emphasis on readability. The required indentation makes code blocks visually clear and helps prevent common nesting errors.

How do you check multiple conditions using 'elif' in an if statement?

The elif statement lets you check multiple conditions in sequence, running different code blocks based on which condition evaluates to true. When Python encounters an elif, it only checks that condition if all previous conditions were false.

  • The code executes top to bottom. Python stops at the first true condition it finds
  • You can chain multiple elif statements to handle various scenarios efficiently
  • Each condition must evaluate to either true or false

This approach prevents unnecessary condition checking and creates cleaner, more maintainable code compared to nested if statements.

Can you use comparison operators like == and != in if statements?

Yes, you can use comparison operators like == and != in if statements to compare values and control program flow. These operators evaluate expressions to true or false, which determines whether the code inside the if block executes.

  • Use == to check if two values are equal
  • Use != to verify if values are different

The double equals == compares value equality while the triple equals === checks both value and type. This distinction matters when comparing different data types. The computer evaluates these comparisons before executing the conditional logic.

What happens when the condition in an if statement evaluates to False?

When an if statement evaluates to False, the program skips the indented code block beneath it and continues execution with the next unindented line. This behavior enables programs to make decisions and take different paths based on conditions.

  • The code inside the if block never runs
  • Program flow moves directly to the next statement after the if block
  • Any elif or else clauses will be checked next if they exist

This selective execution forms the foundation of program logic. It lets developers create flexible applications that respond differently based on varying inputs and states.

How do you write an if statement that checks if a value is in a list?

Python's in operator checks if a value exists within a list. The syntax follows a natural language pattern: if value in list_name. This operator searches through each element of the list until it finds a match or reaches the end.

The in operator returns True when it finds a match and False otherwise. This makes it perfect for conditional logic where you need to verify list membership before proceeding with specific actions.

🏠