sec03 - Python If Statements Tutorial for Beginners: Learn Conditional Logic with Examples
スポンサーリンク

What Is Conditional Branching in Python? A Beginner-Friendly Guide to if Statements

Programs are generally executed sequentially from top to bottom. This is called "sequential execution."

However, real-world decisions often require branching based on conditions, such as "if it rains." This is where conditional branching (if statements) comes in.

Conditional branching allows a program to "change its behavior depending on the situation." For example, "take an umbrella if it rains" or "go for a walk if it is sunny." You can represent such decisions in code. This makes it possible to execute code only when a certain condition is met or run only the first matching option among several candidates, providing flexible behavior.

if / elif / else: Meaning and Usage Explained Clearly

There are three keywords used in conditional branching:

  • if
    • Checks the first condition.
    • If the condition written on the if line is True, the indented code immediately below is executed.
    • If the condition is False, the code inside the if block is not executed.
    • Must always be written at the beginning of a conditional branch.
  • elif
    • Short for "else if." It is used to check an additional condition when the if condition is not met. You can have multiple elif statements in a row.
    • elif is optional.
  • else
    • Used to write code for "when none of the above conditions apply." No condition is written. If neither if nor any elif matches, the else block is executed.
    • else is optional.

if is the first check, and elif is an additional check afterward. If the if condition is True, the elif statements are skipped (only the first matching block is executed).

スポンサーリンク

The Basic Structure of Conditional Branching in Python: Using Colons and Indentation

The basic form of conditional branching in Python is as follows. Remembering to use a colon (:) and proper indentation is critical.

if conditionA:
    processA1  # Add indentation (4 spaces)
    processA2  # Align with the same indentation level
elif conditionB:
    processB1  # This runs when conditionB is True
    processB2
    processB3  # End of the conditionB block
elif conditionC:
    processC  # You can add as many elif blocks as needed
else:
    processD  # Runs when none of the conditions are met

Important points here:

  • A conditional expression is written as a comparison expression (e.g., num > 0) or any expression that returns a bool value.
    • bool values will be covered in a dedicated lesson.
    • Comparison expressions introduced in this lesson:
      • A > B: True when "A is greater than B." If A and B are equal, it is False.
      • A >= B: True when "A is greater than or equal to B." If A and B are equal, it is also True.
      • A == B: True when "A and B have the same value."
  • The colon (:) marks the end of a conditional expression.
  • The code to be executed when if / elif / else conditions are met must be indented.
    • As long as the indentation is consistent, all code at that level belongs to the block.
  • elif and else are optional, used as needed.
    • You can add as many elif statements as required.
    • else can be written only once at the end.

What Is Indentation in Python? Beginner-Friendly Rules for Indenting

What Is Indentation in Python? Basic Rules and Examples

In Python, indentation is used to define blocks such as "the code to run when an if condition is satisfied" or "the code for an elif condition."

In other languages, curly braces {} are often used to mark blocks. In Python, however, indentation itself defines the block boundaries. If indentation is incorrect, Python cannot determine which code belongs to which block, resulting in an error.

The standard indentation is 4 spaces. (In Visual Studio Code, pressing the TAB key inserts 4 spaces by default.)

Correct Indentation Example: How to Write Blocks in Python if Statements

As long as lines are indented at the same depth, Python recognizes them as part of the same block. If there is a blank line inside a block, lines with the same indentation level after the blank line are still considered part of that block.

When indentation is removed (returned to the previous depth), Python treats it as code outside of the if block.

num = 10  # Change the value of num and observe the flow of execution

if num > 0:
    # Indented with 4 spaces
    print("Positive number")

    print("This is also inside the if block")
print("This is outside the if block")

Execution order for the code above (when num is 10):

  1. Assign num = 10 on line 1
  2. Evaluate if num > 0:10 > 0 is True (condition satisfied)
  3. Execute the two indented print statements in order
    • As long as indentation is consistent, code runs inside the block
  4. Execute the unindented print and finish
# Execution result #
Positive number
This is also inside the if block
This is outside the if block

Execution order for the code above (when num is -5):

  1. Assign num = -5 on line 1
  2. Evaluate if num > 0:-5 > 0 is False (condition not satisfied)
  3. The indented lines are not executed
  4. Execute the unindented print and finish
# Execution result #
This is outside the if block

Common Mistake: Forgetting Indentation in Python if Statements

If the code immediately below an if is not indented, Python raises a syntax error. This is one of the most common pitfalls for beginners.

if num > 0:
print("Positive number")  # Causes IndentationError

NG Example: Inconsistent Indentation Levels and How to Fix Them

Inside an if block, all lines must be indented at the same depth. If indentation is inconsistent, Python raises an IndentationError.

# Incorrect example
if num > 0:
    print("Positive number")
      print("This is also positive")  # Error: inconsistent spaces
   print("This is also positive")  # Error: inconsistent spaces

# Correct example
if num > 0:
    print("Positive number")
    print("This is also positive")  # OK: indented with 4 spaces
    print("This is also positive")  # OK: indented with 4 spaces

Executable Python Conditional Branching Code Examples

Code Example with Only if Statement|Execute Only When the Condition is Met

The code inside the if block is executed only when the condition is satisfied. If the condition is not met, the code inside the if block will not run.

num = 10  # Change the value of num to check the program flow

if num > 0:
    print("positive")

Program Execution Flow (when num=10)

  1. Evaluate num = 10 and assign 10 to the variable num.
  2. Evaluate if num > 0: (10 > 0True).
  3. Since the condition is True, execute the indented print("positive").
  4. If there is nothing else to execute, the program ends.

Program Execution Flow (when num=-5)

  1. Evaluate num = -5 and assign -5 to the variable num.
  2. Evaluate if num > 0: (-5 > 0False).
  3. Since the condition is False, the indented print("positive") is not executed.
  4. If there is nothing else to execute, the program ends.

if + else Code Example|Processing When the Condition Is Not Met

If the initial if condition is not satisfied, the “else” (otherwise) branch is executed. else covers all cases where the condition is not met.

num = -3

if num > 0:
    print("positive")
else:
    print("zero or negative")

Program Execution Flow

  1. Assign num = -3.
  2. Evaluate if num > 0:-3 > 0 is False.
  3. The if block is skipped, and the program moves to the else block.
  4. Execute print("zero or negative").
  5. Program ends.

if + elif Code Example|Sequentially Checking Multiple Conditions

When you want to check multiple conditions in sequence, use elif.

num = 0

if num > 0:
    print("positive")
elif num == 0:
    print("zero")

Program Execution Flow

  1. Assign num = 0.
  2. Evaluate if num > 0:0 > 0 is False.
  3. Evaluate elif num == 0:0 == 0 is True.
  4. Execute print("zero").
  5. Program ends.

Since this code has no else, if num is negative, it will not match any condition, and the program will end without outputting anything.

if + elif + else Code Example|Comprehensive Branching with Multiple Conditions

You can add as many elif clauses as needed. Adding else at the end allows you to handle the “none of the above” case.

# Example: Display evaluation based on score
score = 75

if score >= 80:
    print("Excellent")
elif score >= 60:
    print("Pass")
elif score >= 40:
    print("Make-up Exam")
else:
    print("Fail")

Program Execution Flow

  1. Assign score = 75.
  2. if score >= 80:75 >= 80 is False.
  3. elif score >= 60:75 >= 60 is True.
  4. Execute print("Pass").
  5. Program ends.

In the above code, once score >= 60 evaluates to True, subsequent conditions such as elif score >= 40 or else are skipped. (Only the first matched condition is executed.)

It is very important to understand that if / elif / else statements are evaluated from top to bottom, and only the first block that evaluates to True is executed.

Common Mistakes and Points of Caution in Python Conditional Branching

Why Forgetting the Colon (:) in Python Causes an Error

Always remember to put a : at the end of an if line. Forgetting it will result in a syntax error.

# NG (Error)
if num > 0  # ← Missing colon causes SyntaxError
    print("...")

Beware of Condition Order|Evaluation Order of Python if Statements

When checking thresholds, it is best practice to write the conditions from higher (stricter) to lower values. If written in the wrong order, the program may match an earlier condition and skip the later ones.

# Incorrect Example (Leads to unexpected result)
score = 85  # Intended as "Excellent"

if score >= 60:   # This is True, so it outputs "Pass" instead of "Excellent"
    print("Pass")
elif score >= 80:
    print("Excellent")

In examples like the above, where conditions are evaluated in sequence, writing conditions in descending order (e.g., >= 80, >= 60, >= 40, …) ensures that the branching works as intended.

Difference Between if~elif and if-if|Understanding Conditional Behavior

The following two examples look similar, but one uses if~elif, while the other consists of only if statements.

When using if~elif, with score = 85 the output will be "Excellent". However, when using only if statements, the output will be "Pass". Let’s confirm the flow with flowcharts.

# if ~ elif
score = 85

if score >= 80:   # This is True, so the elif block is skipped ("Excellent" is confirmed)
    result = "Excellent"
elif score >= 60:
    result = "Pass"

print(result)  # Outputs "Excellent"

elif is skipped when any preceding if or elif condition is satisfied. Therefore, once if score >= 80: evaluates to True, "Excellent" is confirmed.

# if only
score = 85

if score >= 80:   # This is True, result is assigned "Excellent"
    result = "Excellent"
if score >= 60:   # This is also True, result is overwritten with "Pass"
    result = "Pass"

print(result)  # Outputs "Pass"

An if statement always starts a new evaluation regardless of the result of previous if statements. Once the first if evaluation ends, the flow returns to the “main line,” and then the second if statement is evaluated.

スポンサーリンク