Python if Statement Nesting Explained | Beginner’s Guide with Examples
スポンサーリンク

Python if Statement Nesting Rules

The rules for nesting are very simple. To clearly define the code that should execute when an if-elif-else condition is met, indent the code block one level deeper. For example, the standard indentation for an if statement is four spaces. If you write another if statement (a nested if) inside it, indent that block with eight spaces. In other words, increase the indentation by four spaces for each additional level of nesting.

By following this rule, you can nest if statements as deeply as needed. However, be cautious, as excessive nesting can reduce code readability.

# Check the first condition: process if condition A is True
if conditionA:
    processA
    # Further nested conditional within condition A's block
    if conditionA_1:
        processA_1
        # Further nested conditional within condition A_1's block
        if conditionA_1_1:
            processA_1_1
        else:
            processA_1_2
    elif conditionA_2:
        # Process executed if condition A_1 is False and condition A_2 is True
        processA_2
    else:
        # Process executed if both condition A_1 and condition A_2 are False
        processA_3
    # End of "if conditionA" block #

# Condition checked if condition A is False
elif conditionB:
    processB
    if conditionB_1:
        processB_1
    else:
        processB_2
    # End of "elif conditionB" block #

# Process when both condition A and condition B are False
else:
    processC
    if conditionC_1:
        processC_1
    # End of "else" block #

Sample of Nested if Statements for Login Check in Python

You can nest if statements within the code block that executes when an if-elif-else condition is met.

Let's start with a simple example. This code checks both "user" and "password" to determine whether both conditions are satisfied.

user = 'Taro'
password = 'abc123'

if user == 'Taro':
    # Inside the first if statement block
    if password == 'abc123':
        # This block is inside the nested if statement
        print('Login successful')

Step-by-Step Process

  • (Line 1) user = 'Taro': Assigns 'Taro' to the variable user.
  • (Line 2) password = 'abc123': Assigns 'abc123' to the variable password.
  • (Line 4) if user == 'Taro':: Compares if the variable user equals 'Taro'.
    • == checks whether the values on both sides are the same.
    • Only if the first if condition is True will the subsequent block (indented code) be executed.
  • (Line 6) if password == 'abc123':: Compares if the variable password equals 'abc123'.
  • (Line 8) If the second if condition is True, print('Login successful') is executed.

Summary of Case-Based Execution

  1. user="Taro" and password="abc123"
    1. First if is True
    2. The nested if is also True
    3. print('Login successful') is executed
  2. user="Taro" and password="wrong"
    1. First if is True
    2. The nested if is False
    3. print is not executed
  3. user="Jiro" (wrong username)
    1. First if is False
    2. The first if block is not executed

Notes and Cautions for if Statement Nesting

  • Indentation indicates which if block a statement belongs to. The standard is four spaces.
    • Nested if blocks should be indented an additional four spaces.
    • = is assignment, == is comparison. Beginners often confuse these, so be careful.
    • In this example, if any of the if conditions is False, print('Login successful') will not execute, and the process ends.

    This code will be further refined in future lessons when learning about boolean types (and, or) and functions.

    For now, the key takeaway is that you can nest if statements to check multiple conditions.

    スポンサーリンク

    Sample of Nested if Statements for Python Game Control

    The following code demonstrates conditional branching to determine a game player's actions. Results vary depending on the player's health, stamina, and the enemy's health.

    A flowchart is provided following the code, allowing you to compare it with the code to understand the process flow.

    Note that this is only sample code, so it may appear simplistic compared to an actual game system. Also, player stats such as health would normally change in real time, but here they are fixed. Try changing the values to see how the code flow reacts.

    # Represent player and enemy states with variables
    player_hp = 75           # Player's health
    player_stamina = 65      # Player's stamina
    enemy_hp = 90            # Enemy's health
    has_healing_item = True  # Whether the player has a healing item
    can_call_ally = False    # Whether the player can call an ally
    
    if player_hp > 50:
        print('Attack!')
        if player_stamina >= 60:
            print('Use special move!')
        elif enemy_hp >= 80:
            print('Aim for the enemy’s weak point!')
        else:
            print('Perform a normal attack to steadily reduce health.')
    
    elif player_hp > 30:
        print('Consider healing.')
        if has_healing_item:
            print('Use a healing item.')
        else:
            print('Defend and endure.')
    
    else:
        print('Low health, in danger!')
        if can_call_ally:
            print('Call for an ally to help.')
        else:
            print('Run away!')
    
    スポンサーリンク