Understand and use nested statements

Resources | Subject Notes | Computer Science

Nested Statements - IGCSE Computer Science

Nested Statements

Nested statements occur when one control structure (like an if statement, a for loop, or a while loop) is placed inside another control structure. This allows for more complex and conditional program logic.

Why Use Nested Statements?

Nested statements are essential for creating programs that can handle multiple levels of conditions or repeat actions within other repeating actions. They enable you to build sophisticated algorithms.

Examples of Nested Structures

1. Nested if Statements

You can place an if statement inside another if statement. This is useful for checking multiple conditions.

Example: Determine if a number is within a specific range and also positive.

Code Explanation

if number > 0:
    if number < 100:
        print("Number is positive and less than 100")
    else:
        print("Number is positive but not less than 100")
else:
    print("Number is not positive")
                        
The outer if checks if the number is greater than 0. If it is, the inner if checks if it's also less than 100. The output depends on the evaluation of both conditions.

2. Nested for Loops

A for loop can be placed inside another for loop. This is commonly used for processing multi-dimensional data (like a 2D array) or generating combinations.

Example: Print a multiplication table up to 5x5.

Code Explanation

for i in range(1, 6):
    for j in range(1, 6):
        print(i * j, end="\t")
    print()
                        
The outer loop iterates through numbers 1 to 5 (inclusive). The inner loop also iterates through numbers 1 to 5 (inclusive). For each combination of i and j, their product is calculated and printed, followed by a tab. After each row, a newline is printed to move to the next line.

3. Nested while Loops

Similar to for loops, while loops can be nested to create more complex iterative processes. The inner loop continues to execute as long as the outer loop's condition is true.

Example: Prompt the user for input until they enter a valid number between 1 and 10.

Code Explanation

while True:
    user_input = input("Enter a number between 1 and 10: ")
    try:
        number = int(user_input)
        if 1 <= number <= 10:
            print("Valid number:", number)
            break  # Exit the outer loop
        else:
            print("Number is outside the range 1-10")
    except ValueError:
        print("Invalid input. Please enter a number.")
                        
The outer while loop runs indefinitely until a valid number is entered. The inner while loop attempts to convert the user's input to an integer and checks if it falls within the range of 1 to 10. If the input is valid, the loop breaks. If not, an error message is displayed, and the outer loop continues.

Important Considerations

  • Complexity: Nested statements can make code harder to read and debug.
  • Efficiency: Deeply nested structures can sometimes impact program performance.
  • Indentation: Proper indentation is crucial for readability when using nested statements.