How to use 'if' in Python

Learn how to use if statements in Python. Discover different methods, tips, real-world applications, and how to debug common errors.

How to use 'if' in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Tue
Feb 24, 2026
The Replit Team Logo Image
The Replit Team

The if statement is a core part of Python for conditional logic. It lets your code make decisions and execute actions based on whether a specific condition proves true or false.

Here, you'll explore essential techniques and practical tips. You'll find real-world applications and advice for common bugs, so you can master conditional logic with confidence.

Basic if statement

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

In this example, the if statement checks whether the condition x > 5 is true. Since x is 10, the condition passes, and the indented code block executes. This is the core of conditional logic—code runs only when specific criteria are met.

  • The condition is evaluated using the greater-than operator >.
  • Python's strict indentation rules determine which lines of code belong to the if block.

This structure is what allows your program to make decisions and follow different paths based on input or changing state.

Basic conditional techniques

Once you've got the basic if statement down, you can expand your conditional logic using if-else, if-elif-else, and logical operators to manage multiple outcomes.

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 if-else statement provides a fallback option. When the initial if condition is false, the code inside the else block runs instead. This structure guarantees that one of the two blocks will always execute, giving you a way to handle both true and false outcomes.

  • Since age is 17, the condition age >= 18 is false.
  • As a result, the program skips the if block and runs the code within 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")--OUTPUT--Grade: B

For handling more than two possibilities, you can chain conditions using elif. This structure lets you test a series of conditions in a specific order. Python checks each one sequentially until it finds a true statement, at which point it executes the corresponding code and skips the rest of the chain.

  • In this example, the condition score >= 80 is the first one to evaluate to true.
  • Its code block runs, and the program immediately exits the chain, ignoring the remaining elif and else statements.

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 combine multiple conditions in a single statement, giving you more granular control over your program's flow.

  • The and operator is strict—it requires both conditions to be true. Since temperature > 30 is false, the first if statement fails.
  • The or operator is more flexible, needing only one condition to pass. The elif block runs because humidity > 60 is true, even though the temperature condition isn't met.

Advanced conditional patterns

As you move beyond the basics, you can use advanced patterns to write more compact and expressive conditional logic for handling complex scenarios.

Conditional expressions (ternary operator)

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

Conditional expressions, often called the ternary operator, let you write a simple if-else statement in a single, compact line. It's a clean way to assign one of two values to a variable based on a condition.

  • The syntax is straightforward: value_if_true if condition else value_if_false.
  • In this example, because age >= 18 is true, the variable status is assigned the string "adult". If the condition were false, it would receive "minor" instead.

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 to create more complex decision-making logic. This pattern is useful when a follow-up condition only makes sense after a primary condition is met. It allows you to build a hierarchy of checks.

  • The outer if statement first checks if num > 0.
  • Only if that condition is true does the program run the inner if statement, which checks if the number is even using the modulo operator (num % 2 == 0).

This layering lets you handle specific sub-cases, like distinguishing between positive even and odd numbers, while managing other possibilities separately.

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

You can use the all() and any() functions to cleanly check conditions across iterables like lists. They work with generator expressions to test each item, so you don't have to write a full loop. This makes your conditional logic more concise and readable, especially with collections of data.

  • The all() function returns True only if every item meets the condition. Here, it confirms all numbers are even.
  • The any() function returns True if at least one item meets the condition. It finds that at least one number is greater than 10.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the conditional logic techniques we've explored, Replit Agent can turn them into production-ready tools. You can use it to build:

  • A user access system that uses if-else logic to grant or deny entry based on credentials.
  • A shipping cost calculator that applies different rates using an if-elif-else chain based on package weight and destination.
  • A data validation tool that uses all() to confirm that all fields in a user submission meet specific criteria before processing.

Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser. Try Replit Agent to bring your concepts to life.

Common errors and challenges

Even with a firm grasp of the basics, a few common errors in Python's conditional logic can lead to unexpected bugs.

Forgetting to use == for equality comparison

One of the most frequent slip-ups is using the assignment operator (=) when you mean to use the equality operator (==). The first assigns a value to a variable, while the second checks if two values are equal.

Using if x = 10: instead of if x == 10: won't always cause an error. Instead, the assignment happens, and the if statement evaluates the assigned value. Since non-zero numbers are "truthy," the condition passes, and your code runs when it shouldn't, creating a subtle and frustrating bug.

Confusing and/or operator precedence

Logical operators don't always execute in the left-to-right order you might expect. Python's and operator has a higher precedence than or, meaning it gets evaluated first. This can lead to logical errors if you're not careful.

For example, a condition like is_admin or is_editor and has_permission is interpreted as is_admin or (is_editor and has_permission). If your intent was to check the user's role first, you need to use parentheses to group the logic explicitly: (is_admin or is_editor) and has_permission. When in doubt, parentheses make your intention clear and your code more robust.

Improper indentation in nested if blocks

Python's reliance on indentation for structure is one of its defining features, but it's also a common source of errors, especially in nested conditionals. A misplaced space can attach a block of code to the wrong condition, completely changing your program's flow.

This can be particularly tricky to debug because the code might still run without a syntax error—it just won't do what you expect. The best defense is to be meticulous. Always use a consistent number of spaces (the community standard is four) for each level of indentation and let your code editor help you keep track of alignment.

Forgetting to use == for equality comparison

A single misplaced character can create one of Python's most subtle bugs. Using the assignment operator (=) where the equality operator (==) belongs doesn't cause a crash. Instead, it silently changes your variable's value, making the condition unexpectedly pass.

The following example shows this in action, leading to a misleading output.

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

Here, the if statement doesn't compare values. Instead, x = 5 assigns 5 to x. Since 5 is treated as true, the wrong code block executes. See the corrected implementation below for the proper comparison.

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

The corrected version uses the equality operator (==) to properly compare x and 5. Since x is 10, the condition x == 5 evaluates to false, so the else block executes as intended. This fix ensures your logic performs a comparison instead of an accidental assignment.

  • This is a common slip-up, especially in if statements.
  • Using a single = won't raise an error, which makes the bug hard to spot.

Confusing and/or operator precedence

Python evaluates the and operator before the or operator, which can trip you up if you assume a left-to-right order. This precedence rule can make your condition pass or fail unexpectedly. The following loan approval script demonstrates this common pitfall.

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 approves the loan if age > 18, ignoring the credit score, because the and condition is evaluated first. This creates a logical flaw. The corrected version below shows how to group the conditions properly.

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 corrected code uses parentheses to group the or condition, ensuring it's evaluated before the and. This forces Python to check if (age > 18 or income > 25000) is true as a single unit before considering the credit_score.

  • When combining and and or, use parentheses to make your logic explicit and prevent unexpected outcomes.

Improper indentation in nested if blocks

Python's strict indentation is what makes it readable, but it's also a common source of bugs. A single misplaced space in a nested if statement can completely change your program's logic without causing a crash. See how this plays out below.

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

The print("It's cool outside") line lacks proper indentation, which causes an IndentationError. Python requires this alignment to understand the code's structure. The corrected version below demonstrates how to properly nest these statements.

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

The corrected code fixes the IndentationError by properly aligning the print statement and the nested if block. Both are now indented under the outer if temp < 20: condition, creating the correct logical structure. This ensures the inner check for temp < 10 only runs after the first condition passes.

  • Always double-check indentation in nested logic, as it's fundamental to Python's execution flow and easy to get wrong.

Real-world applications

Beyond theory and debugging, if statements are the backbone of practical applications you interact with daily.

Calculating discounts in an online shop

Online shops often use if-elif-else logic to create tiered discount systems that reward customers based on their membership status and how much they spend.

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 script determines a customer's discount by evaluating a series of conditions in order. The logic prioritizes the most valuable discount first.

  • The initial if statement checks if is_member is true and the purchase_amount is at least 100. Since both conditions are met, the 15% discount is applied.
  • Because the first condition passed, Python skips the remaining elif and else blocks.

This structure ensures that only the first true condition in the chain executes, making the order of your checks critical for the logic to work as intended.

Weather advisory system with if statements

An if-elif-else chain is also ideal for building a weather advisory system that checks a series of conditions to determine the best safety recommendation.

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 script uses an if-elif-else chain to provide weather advice. It’s a structure that checks conditions sequentially, running the code for the first true condition it finds before exiting the block.

  • The logic combines multiple checks using the and operator to test for a specific event like a blizzard.
  • It also uses the in operator to efficiently check if precipitation is one of several possible values.
  • The order of the conditions is critical. More specific checks, like for a blizzard, must come before broader ones to ensure they’re evaluated correctly.

Get started with Replit

Put your knowledge of conditional logic to work. Describe a tool to Replit Agent, like "a tax calculator for different income brackets" or "a script that validates a list of user emails".

The agent writes the code, tests for errors, and deploys your application from a single prompt. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.