How to use 'if' in Python

Learn how to use if statements in Python. This guide covers different methods, tips, real-world examples, and common errors to help you code.

How to use 'if' in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

The if statement is a cornerstone of Python. It allows your code to make decisions and execute different actions based on whether a condition is true or false.

In this article, you'll explore techniques and real-world applications. You will also get practical tips and debugging advice to help you master Python's conditional logic.

Basic if statement

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

In this example, the code first assigns the value 10 to the variable x. The if statement then checks whether the condition x > 5 is true. Because 10 is greater than 5, the expression evaluates to true, causing the indented code block to execute.

This demonstrates the core purpose of an if statement: to control the program's flow. The print() function only runs because the condition was met. If the condition had been false, the interpreter would have skipped that line of code entirely.

Basic conditional techniques

Building on the simple if statement, you can handle more complex scenarios by adding else and elif blocks or combining conditions with logical operators.

Using if-else statements

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

The else statement gives you a fallback option. It runs a block of code only when the if condition evaluates to false. In this case, because the condition age >= 18 is false, the code inside the else block is executed, printing "You are a minor".

  • This structure guarantees that one of the two code blocks—either the if or the else—will always run.
  • Think of else as the default action when the specific condition you're checking for isn't true.

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")--OUTPUT--Grade: B

When you need to check several conditions in order, the if-elif-else chain is your tool. The elif keyword lets you add more checks after the initial if. Python evaluates each condition sequentially until one returns True.

  • Once a condition is met, its code block runs, and the interpreter skips the rest of the chain.

In the example, since score is 85, the first condition (score >= 90) is false. The next one, score >= 80, is true, so the program prints "Grade: B" and stops. The final else acts as a default if no conditions are satisfied.

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")--OUTPUT--Either hot or humid

Logical operators like and and or let you test multiple conditions at once. The and operator is strict, requiring all conditions to be true. In contrast, the or operator is more lenient, needing only one condition to be true for the expression to pass.

  • In the example, the first check temperature > 30 and humidity > 60 fails because the temperature isn't high enough.
  • The program then moves to the elif condition, temperature > 30 or humidity > 60. This passes because the humidity is over 60, making the whole expression true and causing its code to run.

Advanced conditional patterns

Building on if-elif-else chains, you can tackle more intricate scenarios with advanced patterns that make your conditional logic cleaner and more efficient.

Conditional expressions (ternary operator)

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

This one-liner is a conditional expression, often called a ternary operator. It’s a compact way to handle a simple if-else assignment. The expression evaluates the condition age >= 18 first. Since it's true, it assigns the value before the if—in this case, "adult"—to the status variable.

  • Think of it as a shortcut with the structure: value_if_true if condition else value_if_false.
  • It's best used for straightforward assignments where you want to make your code cleaner and more readable.

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")--OUTPUT--Positive odd number

You can nest if statements inside one another to handle more complex, layered logic. The outer if acts as a gatekeeper. In the example, it first confirms that num is positive before allowing the program to proceed to the inner conditional.

  • This nested if-else block then performs a more specific check, using the modulo operator (%) to see if the number is even or odd.
  • This pattern is useful when you need to evaluate a sub-condition only after a primary condition is true.

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")--OUTPUT--All numbers are even
At least one number is greater than 10

The all() and any() functions are powerful shortcuts for checking conditions across collections like lists. They let you test every item without writing a full loop, making your code more concise.

  • The all() function returns True only if every element meets the condition. In the example, all(num % 2 == 0 for num in numbers) confirms that all numbers are even.
  • The any() function is more lenient. It returns True if at least one element satisfies the condition, which is why any(num > 10 for num in numbers) passes.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. While mastering conditional logic is key, the next step is applying it. Agent 4 helps you move from piecing together techniques to building complete apps.

Instead of just writing snippets, describe the tool you want to build. The Agent handles everything from writing the code to connecting databases and APIs. You can build practical tools like:

  • A grade calculator that uses an if-elif-else chain to assign letter grades based on numerical scores.
  • A user access tool that uses nested if statements to check if a user is an adult and has an active account before granting entry.
  • A data validation utility that uses all() to confirm every entry in a dataset is valid or any() to flag lists containing at least one error.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with a solid grasp of the basics, you can run into pitfalls with conditional logic, but these common mistakes are easy to avoid.

Forgetting to use == for equality comparison

One of the most frequent slip-ups is using the assignment operator (=) instead of the equality operator (==) for comparisons. While you might intend to check if x == 10, writing if x = 10: tries to assign the value 10 to x inside the condition. Luckily, Python usually catches this and raises a SyntaxError, but it's a classic bug in many other languages where it can fail silently.

Confusing and/or operator precedence

The order in which Python evaluates logical operators can also cause confusion. The and operator has a higher precedence than or, meaning it gets evaluated first. A condition like A or B and C is interpreted as A or (B and C), which might not be what you intended.

  • To prevent ambiguity and ensure your logic runs as expected, always use parentheses to group your conditions explicitly. For example, writing (A or B) and C makes your intention perfectly clear to both the interpreter and other developers.

Improper indentation in nested if blocks

Since Python uses whitespace to define structure, improper indentation is a common source of errors, especially in nested if statements. A misplaced else block, for instance, can attach to the wrong if statement, completely altering your program's flow.

This isn't just a matter of style; it's fundamental to the language's syntax. An indentation error can lead to code executing under unintended conditions, creating bugs that are often tricky to spot.

Forgetting to use == for equality comparison

It's a classic mix-up: using the assignment operator (=) when you mean to check for equality with ==. Instead of comparing values, this tries to assign one, which isn't allowed inside a condition. The code below demonstrates this common SyntaxError.

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

This code produces a SyntaxError because an assignment like x = 5 doesn't evaluate to a true or false value for the if statement to check. The corrected version shows how to perform a valid comparison.

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

The corrected code works because it uses the double equals operator (==) to perform a comparison. This operator checks if x is equal to 5 and returns a boolean value—True or False—which is what an if statement needs to function correctly. It's a simple but crucial distinction from the assignment operator (=). Be mindful of this common typo, especially when writing conditions quickly or switching between programming languages.

Confusing and/or operator precedence

The order in which Python evaluates logical operators can trip you up. The and operator has higher precedence than or, meaning it's checked first, which can lead to unexpected results. The code below shows how this subtle rule can change an outcome.

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

Python evaluates the and operator first, so the loan is approved simply because age > 18 is true, which may not be the intended logic. The corrected version below ensures the conditions are evaluated as expected.

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

By wrapping the or condition in parentheses, you force it to be evaluated first. The expression (age > 18 or income > 25000) resolves to a single boolean value before the and operator checks the credit_score. This guarantees the credit score is always a required condition. It’s a good habit to use parentheses whenever you combine and and or to prevent ambiguity and make your logic explicit.

Improper indentation in nested if blocks

Python's reliance on whitespace means even a small indentation mistake can break your code. A misplaced line can cause an IndentationError or, worse, make your logic behave unexpectedly. The code below shows how a simple error can stop a program cold.

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

The first print() statement isn't indented, so it doesn't belong to the if block above it. This breaks Python's structural rules and causes an IndentationError. The corrected version below shows how to fix this.

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

The fix is simple: indenting the print() statement places it inside the if temp < 20: block, resolving the IndentationError. This ensures the code follows Python's structural rules, where whitespace dictates logic. The outer if now correctly contains both the print call and the nested conditional. Always double-check your indentation with nested blocks—it’s a common tripwire that can create subtle, hard-to-find bugs in your program's flow.

Real-world applications

Beyond syntax and debugging, conditional logic is what powers practical tools, from calculating discounts in an online shop to issuing weather advisories.

Calculating discounts in an online shop

Conditional logic allows you to build a dynamic discount system, applying different rates based on a customer's purchase amount and membership status.

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 snippet calculates a final price by first determining a discount. The if-elif-else structure evaluates conditions in order until one is met.

  • The first condition, is_member and purchase_amount >= 100, evaluates to true because both parts of the and expression are satisfied.
  • As a result, the discount is set to 0.15, and the program immediately skips the rest of the conditional chain.

This demonstrates how Python efficiently handles tiered logic. The final price is then calculated using the assigned discount value.

Weather advisory system with if statements

By combining multiple conditions with if, elif, and else, you can build a practical tool that issues weather advisories.

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 code models a simple weather advisory system, using an if-elif-else chain to evaluate several conditions. It checks temperature, precipitation, and wind_speed to provide tailored advice based on the combination of factors.

  • The first two conditions for extreme cold fail because the temperature is not less than 0.
  • The third condition, elif temperature < 10 and precipitation in ["rain", "snow"], evaluates to True. This is because the temperature is 5 and the precipitation is "snow", satisfying both parts of the check and triggering its specific print() statement.

Get started with Replit

Now, turn your knowledge of conditional logic into a working application. Describe what you want to build to Replit Agent, like “a shipping cost calculator based on weight and destination” or “a validator for user sign-up forms.”

The Agent writes the code, tests for errors, and helps you deploy your app directly from your browser. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.