How to end an if statement in Python
Learn how to properly end an if statement in Python. Explore different methods, tips, real-world examples, and common error debugging.

In Python, if statements control your code's execution flow. It's crucial to understand how to properly end them for clean, error-free scripts. Indentation, not a specific command, defines the block.
In this article, you'll learn techniques to structure conditional logic. We'll cover practical tips, real-world applications, and common debugging advice to help you master control flow in your projects.
Basic indentation to end an if statement
x = 10
if x > 5:
print("x is greater than 5")
print("This is outside the if statement")--OUTPUT--x is greater than 5
This is outside the if statement
In Python, whitespace is significant. The first print statement executes only when x > 5 is true because it's indented, creating a code block tied to the if statement.
The conditional block ends simply by removing the indentation. When the interpreter encounters the second print statement, which is aligned with the initial if, it recognizes that the conditional logic is complete. This line will execute regardless of the condition, as it's part of the main program flow.
Alternative control flow structures
Beyond ending a conditional block, you can extend it with else, elif, and the ternary operator to create more sophisticated control flow.
Using else to handle alternative cases
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
print("End of age check")--OUTPUT--You are a minor
End of age check
The else statement provides a fallback, executing a block of code only when the initial if condition evaluates to False. It’s a great way to handle mutually exclusive outcomes where one of two paths must be taken.
- In this example, since
ageis 15, the conditionage >= 18isn't met. - Consequently, the program skips the
ifblock and runs the code indented underelse. - This structure guarantees that your program will print one message or the other, but never both.
Using elif for multiple conditions
score = 75
if score >= 90:
print("Grade: A")
elif score >= 70:
print("Grade: B")
else:
print("Grade: C or below")--OUTPUT--Grade: B
The elif statement lets you chain conditions together, making using elif in Python a clean way to check for several possibilities without nesting multiple if statements.
- Python evaluates each condition in order, starting from the top.
- In this case, the first condition
score >= 90is false, so it moves to the next one. - The
elif score >= 70condition is true, so its code block runs, and the entire chain—including the finalelse—is skipped.
Using ternary operator for compact conditionals
x = 5
result = "Positive" if x > 0 else "Non-positive"
print(result)--OUTPUT--Positive
The ternary operator offers a clean, one-line syntax for simple conditional assignments. It's a shortcut for a basic if-else block, making your code more concise.
- The expression first evaluates the condition,
x > 0. - If true, the value before the
ifkeyword ("Positive") is assigned toresult. - If false, the value after the
elsekeyword is used instead.
This operator is ideal for quickly assigning one of two values to a variable based on a single condition.
Advanced control flow techniques
Building on those foundational structures, you can refine your control flow even further with placeholder statements like pass, nested logic, and combined conditions.
Using pass for empty code blocks
data = []
if not data:
pass # We'll handle empty data later
else:
for item in data:
print(item)
print("Processing complete")--OUTPUT--Processing complete
The pass statement is a null operation—a placeholder that does nothing. Understanding using pass in Python is useful when Python's syntax requires an indented block, but you don't have any code to put there yet. This prevents your script from throwing an error.
- In this case, the
if not data:block is intentionally left empty. - Using
passmakes the code syntactically valid and acts as a to-do note, signaling that the logic for handling empty data will be added later.
Nesting if statements with proper indentation
temp = 22
is_sunny = True
if temp > 20:
print("It's warm")
if is_sunny:
print("And it's sunny - perfect day!")
print("Weather report complete")--OUTPUT--It's warm
And it's sunny - perfect day!
Weather report complete
You can nest if statements to create more complex logic where one condition depends on another. The inner if statement only gets evaluated if the outer one is true. Each level of nesting requires its own indentation to define the code block.
- In this example, the outer condition
temp > 20is met, so the program proceeds to the indented block. - It then evaluates the inner condition,
if is_sunny:, which is also true, causing its message to print. - This structure is perfect for handling layered checks in your code.
Using logical operators to combine conditions
age = 25
income = 50000
if age > 18 and income > 30000:
print("Eligible for premium account")
if age < 18 or income < 20000:
print("Eligible for discount")--OUTPUT--Eligible for premium account
Logical operators like and and or let you combine multiple conditions into a single if statement. Learning using and in Python is often cleaner than nesting and allows for more complex decision-making in your code.
- The
andoperator requires all conditions to be true. In the example, eligibility for a premium account is granted because bothage > 18andincome > 30000are met. - Conversely, the
oroperator only needs one condition to be true. The discount check is skipped because neitherage < 18norincome < 20000is true.
Move faster with Replit
Understanding control flow is one thing, but building with it is another. Replit is an AI-powered development platform where you can start coding Python instantly. All Python dependencies pre-installed means you can skip the setup and focus on your project.
This is where you can move from piecing together techniques to building complete applications. With Agent 4, you can describe what you want to build, and it will handle the code, databases, APIs, and deployment. Instead of just writing if statements, you can build the entire system that uses them.
- Build a user access tool that assigns roles based on multiple criteria using chained
elifconditions. - Create an automated inventory alert system that triggers only when stock is low
anddemand is high. - Develop a dynamic pricing engine that uses nested
iflogic to offer different prices based on user status and location.
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 simple if statements can cause tricky bugs; here are a few common errors and how to fix them.
One of the most frequent slip-ups is confusing the assignment operator (=) with the equality operator (==). Using a single equals sign inside an if statement tries to assign a value rather than compare it, which will cause a SyntaxError in most conditional checks. Always double-check that you're using == when you intend to test for equality.
Python's reliance on whitespace can lead to an IndentationError if you're not careful. This error pops up when indentation levels are inconsistent within the same block. Your code editor might mix tabs and spaces, or you might accidentally un-indent a line that should be part of the conditional block through code repair.
- To resolve this, ensure every line inside a specific
if,elif, orelseblock is indented by the exact same amount. - Most code editors have a setting to convert tabs to spaces, which is a great way to prevent these issues from happening in the first place.
A subtle but critical issue is mixing up the logical operators and and or. While both combine conditions, they do so with opposite logic. Using or when you meant and can make your condition far too lenient, potentially creating security flaws or incorrect outputs because only one condition needs to be true.
For example, checking if a user is an admin and is active is very different from checking if they are an admin or are active. The first is restrictive; the second is permissive. Always pause to think through the logic your program truly needs.
Fixing the = vs == confusion in conditional statements
It's a classic Python mistake: using the assignment operator (=) when you mean to use the comparison operator (==). This simple typo doesn't just give you a wrong answer; it stops your code cold with a SyntaxError. See what happens below.
user_type = "premium"
if user_type = "premium": # SyntaxError: can't use assignment in condition
discount = 0.2
print(f"You get a {discount*100}% discount!")
The expression user_type = "premium" is an assignment, not a question that returns True or False. Since an if statement requires a boolean check, the code breaks. The corrected code below makes the right comparison.
user_type = "premium"
if user_type == "premium": # Using equality operator correctly
discount = 0.2
print(f"You get a {discount*100}% discount!")
The fix is to use the double equals sign == for comparison. An if statement needs a condition that evaluates to True or False, which is exactly what == provides. The single equals sign = is for assigning values, which isn't a valid condition and causes a SyntaxError.
- This error is common when checking if a variable matches a specific string or number, so always double-check your operators inside conditionals.
Resolving indentation issues with conditional blocks
Python's strict indentation rules are usually helpful, but they can also create subtle logic bugs. A misplaced indent might not cause an error, but it can completely change your code's behavior, making two separate if statements appear nested. See what happens below.
grade = 85
if grade >= 70:
print("You passed!")
if grade >= 90: # This looks nested but isn't due to indentation
print("With distinction!")
The second if statement is aligned with the first, so Python treats them as separate checks. This means your code doesn't connect the "passing" and "distinction" conditions. See how proper indentation fixes this in the example below.
grade = 85
if grade >= 70:
print("You passed!")
if grade >= 90: # Properly nested with correct indentation
print("With distinction!")
By indenting the second if statement, you create a nested condition. This correctly links the two checks, ensuring the code only evaluates for a distinction (grade >= 90) after confirming the student has passed (grade >= 70). Without this nesting, the two checks run independently, which isn't the intended logic.
- This kind of bug is common when one condition should only be checked if another is already met, so always verify your indentation in layered logic.
Fixing logical errors with and vs or operators
Using the wrong logical operator, like or instead of and, can create conditions that are almost always true, leading to hard-to-spot bugs. This common mistake makes your program's logic behave unexpectedly. See what happens in the code below when checking an age range.
age = 25
# Intending to check if number is between 18 and 65
if age > 18 or age < 65: # Logic error: this is almost always true!
print("Working age adult")
else:
print("Not a working age adult")
The or operator makes this condition true for almost any number. Since an age of 10 is < 65 and an age of 70 is > 18, the logic is flawed. See how the corrected code below properly restricts the range.
age = 25
# Correctly checking if age is between 18 and 65
if age > 18 and age < 65: # Fixed: requires both conditions
print("Working age adult")
else:
print("Not a working age adult")
The fix is to use the and operator, which requires both conditions to be true. This correctly restricts the logic to a specific range, ensuring the age falls between 18 and 65.
- The
oroperator is too permissive here; a number only needs to satisfy one condition, making the check true for almost any age. - This kind of logical error is especially common when you're validating data that must fall between two specific values, like a date range or a price bracket.
Real-world applications
With those common errors fixed, you can confidently apply conditional logic to practical tasks like filtering data and calculating discounts.
Using conditionals for data filtering with if statements
An if statement is a great tool for filtering data, which is similar to filtering a list in Python, as it lets you check each item in a list and collect only the ones that meet a specific condition.
numbers = [10, 25, 3, 41, 8, 15, 22]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print("Even numbers:", even_numbers)
This code builds a new list by selectively pulling items from an existing one through vibe coding. It iterates through the numbers list, and for each num, the if statement uses the modulo operator (%) to check if it's perfectly divisible by two.
- When the condition
num % 2 == 0is true, the code adds that number to theeven_numberslist with theappend()method. - This approach lets you construct a new, targeted list from a larger dataset without modifying the original source.
Implementing a simple discount calculator with multiple if conditions
You can use a series of independent if statements to build a flexible system where multiple conditions contribute to a final outcome, like stacking discounts.
This example uses three separate if statements to check for different discount criteria. Unlike an elif chain, each if is evaluated independently, allowing multiple discounts to be applied to a single purchase. The discount variable starts at 0 and increases with the += operator every time a condition is met.
- The code first checks if
is_memberis true, adding a 10 percent discount. - It then evaluates if the
purchase_amountis over 100, adding another 5 percent. - Finally, it confirms the
day_of_weekis eligible, adding a last 2 percent.
Since all three conditions are met, the discounts accumulate. The total discount becomes 17 percent, which is then used to calculate the final price. This structure is great for scenarios where a customer can qualify for several offers at once.
purchase_amount = 120
is_member = True
day_of_week = "Tuesday"
discount = 0
if is_member:
discount += 10 # 10% member discount
if purchase_amount > 100:
discount += 5 # 5% bulk purchase discount
if day_of_week in ["Monday", "Tuesday"]:
discount += 2 # 2% early week discount
final_price = purchase_amount * (100 - discount) / 100
print(f"Purchase amount: ${purchase_amount}")
print(f"Total discount: {discount}%")
print(f"Final price: ${final_price:.2f}")
This code demonstrates the versatility of if statements by using three different kinds of conditions to build a cumulative discount. Each condition is evaluated on its own, and all of them contribute to the final discount value if their test passes.
- The first check,
if is_member:, is a simple boolean test. - The second,
if purchase_amount > 100:, uses a numerical comparison. - The third,
if day_of_week in [...], checks if a string exists within a list.
This approach shows how you can combine different logical checks to create sophisticated, rule-based outcomes in your code.
Get started with Replit
Turn your knowledge into a real tool. Tell Replit Agent to "build a grade calculator based on scores" or "create a multi-tier discount tool for an e-commerce site."
Replit Agent writes the code, tests for errors, and deploys your app. Start building with Replit.
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.
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.



