Learn How to Write Conditional Statements in Python: Absolute Beginners Tutorial

Conditional statements are how your Python programs make decisions. They let your code choose between different paths depending on whether a condition is true or false — and understanding them unlocks nearly everything that makes programming useful.

Every useful program eventually needs to branch. Show a different message depending on a user's age. Charge a different price depending on a membership tier. Warn a user only if a value is out of range. All of these require conditionals. Python implements conditional logic through three keywords — if, elif, and else — and this tutorial walks through each one from first principles.

What Is a Conditional Statement?

A conditional statement tells Python to run a block of code only when a particular condition is True. If the condition is False, Python skips that block entirely. The simplest form uses just the if keyword.

python
age = 20

if age >= 18:
    print("You are an adult.")

The line if age >= 18: is the condition. The colon at the end is required — it signals that a new indented block follows. The print statement is indented by four spaces, which is how Python knows it belongs to the if block. When age is 20, the condition is True and the message prints. Change age to 15 and nothing prints at all.

Note

Indentation is not optional in Python. Other languages use curly braces to define blocks, but Python uses whitespace. Four spaces per level is the standard. Mixing tabs and spaces causes a TabError.

Adding an else Clause

An if statement on its own only handles the True case. To also handle the False case, add an else clause. The else block runs whenever the if condition is False.

python
age = 15

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

Notice that else has no condition of its own — it is purely a fallback. Python runs exactly one of the two blocks and never both.

Pro Tip

You do not need an else clause every time. If there is nothing meaningful to do when the condition is false, a standalone if block is perfectly valid Python.

code builder click a token to place it

Build a valid if/else statement that prints "Pass" when score is 50 or above, and "Fail" otherwise:

your code will appear here...
else: print("Fail") score if <= 50: >= print("Pass")
Why: The correct order is if score >= 50: print("Pass") else: print("Fail"). The >= operator means "greater than or equal to," which includes the boundary value of 50. Using <= would invert the logic. The else: clause must follow the if block with no condition of its own.

Comparison and Logical Operators

The expression inside an if statement is evaluated as either True or False. Python provides two families of operators for building these expressions: comparison operators and logical operators.

Comparison Operators

Comparison operators test the relationship between two values and return a boolean.

Operator Meaning Example Result
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 4True
<Less than3 < 2False
>=Greater than or equal to5 >= 5True
<=Less than or equal to4 <= 6True
Common Mistake

The single equals sign = is assignment and cannot be used inside a condition. Use == to test equality. Writing if x = 5: raises a SyntaxError.

Logical Operators

Logical operators let you combine multiple conditions into a single expression. Python provides three: and, or, and not.

python
temperature = 22
is_raining = False

# and: both conditions must be True
if temperature > 15 and not is_raining:
    print("Good day for a walk.")

# or: at least one condition must be True
score = 45
if score >= 50 or score == 45:
    print("Close enough to pass.")
Behavior
Returns True only if both sides are True.
Example
x > 0 and x < 100 — True when x is between 1 and 99.
Short-circuit
If the left side is False, Python never evaluates the right side.
Behavior
Returns True if at least one side is True.
Example
role == "admin" or role == "owner" — True for either role.
Short-circuit
If the left side is True, Python never evaluates the right side.
Behavior
Inverts a boolean value. True becomes False, and False becomes True.
Example
not is_logged_in — True when the user is not logged in.
Use case
Useful for making conditions more readable when negation is the natural phrasing.
spot the bug click the line that contains the bug

The code below tries to print a discount message for members who are also over 60. One line contains a bug. Click it, then hit check.

1 is_member = True
2 age = 65
3 if is_member = True and age > 60:
4 print("Senior member discount applied.")
5 else:
6 print("No discount.")
The fix: Change is_member = True to is_member == True — or even better, just is_member. Inside a condition, = is assignment and raises a SyntaxError. The equality check operator is ==. When testing a boolean variable directly, you can simply write if is_member and age > 60:.

The elif Clause and Chained Conditions

When you have more than two possible outcomes, if and else are not enough. The elif keyword — short for "else if" — lets you check additional conditions in sequence. Python evaluates each clause from top to bottom and runs only the first one whose condition is True.

python
score = 74

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Your grade is {grade}.")

With a score of 74, Python tests the first condition (score >= 90) — false. Then the second (score >= 80) — false. Then the third (score >= 70) — true. It assigns "C" and skips all remaining clauses including else.

Note

Order matters with elif. If you placed score >= 60 before score >= 70, a score of 74 would match the first true condition and receive a "D" instead of a "C". Always order conditions from most specific to least specific.

Nested Conditionals

You can place an if statement inside another if block. Each inner level must be indented one additional level. Nested conditionals are useful when a secondary check only makes sense after a primary condition passes.

python
has_ticket = True
age = 16

if has_ticket:
    if age >= 18:
        print("Entry granted.")
    else:
        print("Ticket valid, but must be 18 or older.")
else:
    print("No ticket — entry denied.")
Pro Tip

Deeply nested conditionals are hard to read. If you find yourself nesting three or four levels deep, consider flattening the logic using and conditions or by returning early inside a function.

One-Line Conditional Expressions

Python supports a compact form called a conditional expression (sometimes called a ternary expression) that assigns a value based on a condition in a single line.

python
age = 20
status = "adult" if age >= 18 else "minor"
print(status)  # adult

The format is value_if_true if condition else value_if_false. This works well for simple assignments but can reduce readability when overused — avoid it for complex conditions.

Figure 1 — Execution flow for an if / elif / else chain. Python tests each condition in order and runs only the first matching branch.

How to Write Conditional Statements in Python

Follow these steps to build a complete conditional statement from scratch, adding complexity at each stage.

  1. Write a basic if statement

    Type if, followed by your condition, followed by a colon. On the next line, indent four spaces and write the code to run when the condition is True. Example: if temperature > 30: print("Hot outside.")

  2. Add an else clause for the fallback case

    On the line immediately after the if block, type else: at the same indentation level as if. Indent the fallback code by four spaces beneath it. This block runs whenever the if condition is False.

  3. Use elif to check additional conditions

    Between the if block and the else block, add one or more elif condition: lines. Python evaluates them in order and runs only the first true one. The else block still serves as the final fallback if none match.

  4. Combine conditions with logical operators

    Use and when all sub-conditions must be True, or when at least one must be True, and not to invert a condition. Example: if age >= 18 and has_id: print("Entry allowed.")

  5. Test your conditional with different inputs

    Run your code with values that hit each branch, including boundary values. For an if score >= 50 check, test 49, 50, and 51. Confirm that every path produces the expected output before moving on.

"An if statement selects exactly one of its suites by evaluating each expression." — Python Language Reference

Python Learning Summary Points

  1. The if keyword starts a conditional block. The condition must end with a colon, and the code to run must be indented by four spaces.
  2. The else clause provides a fallback path that runs when the if condition is False. It takes no condition of its own.
  3. The elif clause handles additional conditions between if and else. Python runs only the first matching branch and skips the rest.
  4. Use == to test equality inside conditions. A single = is assignment and raises a SyntaxError when used in a condition.
  5. Logical operators and, or, and not let you combine or invert conditions without nesting additional if statements.
  6. Conditional expressions (value_if_true if condition else value_if_false) provide a concise single-line alternative for simple assignments.

Conditionals are the foundation of decision-making in any Python program. Once you are comfortable with if, elif, and else, the next step is exploring loops — which use the same indentation model to repeat code blocks based on conditions.

check your understanding question 1 of 5

Frequently Asked Questions

A conditional statement in Python is a block of code that runs only when a specified condition evaluates to True. Python uses the keywords if, elif, and else to build conditional logic.

The basic syntax is: if condition: followed by an indented block of code. The colon at the end of the if line is required, and indentation defines what belongs inside the block.

elif checks a new condition only if all previous conditions were False. else runs when no previous condition was True and does not take its own condition — it is the fallback branch.

Yes. You can chain as many elif clauses as needed after an if statement. Python evaluates them in order and runs only the first one whose condition is True.

Python conditionals support ==, !=, >, <, >=, and <=. The == operator checks for equality, while = is assignment and must not be used inside a condition.

Python provides three logical operators for combining conditions: and (both must be True), or (at least one must be True), and not (inverts the truth value of the condition).

Python raises a SyntaxError. The colon at the end of the if, elif, or else line is required — it signals the start of the indented code block that follows.

Yes. Python allows nesting, where an if statement appears inside another if block. Each inner block must be indented one level deeper than the outer block.

In Python, any value can be used in a condition. Values that evaluate to True in a boolean context are called truthy. Values that evaluate to False — such as 0, None, empty strings, and empty lists — are called falsy.

Python allows a short one-liner syntax: result = value_if_true if condition else value_if_false. This is called a ternary expression or conditional expression and is useful for simple assignments.