0
0
Pythonprogramming~5 mins

Python Block Structure and Indentation - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Python Block Structure and Indentation
O(n)
Understanding Time Complexity

When we write Python code, the way we organize it with indentation affects how the computer reads it.

We want to see how the structure of blocks influences how many steps the program takes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def print_numbers(n):
    for i in range(n):
        if i % 2 == 0:
            print(i)
        else:
            print(-i)

This code prints numbers from 0 to n-1, printing positive even numbers and negative odd numbers.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop that runs from 0 to n-1.
  • How many times: Exactly n times, once for each number.
How Execution Grows With Input

As n grows, the number of times the loop runs grows the same way.

Input Size (n)Approx. Operations
10About 10 times
100About 100 times
1000About 1000 times

Pattern observation: The steps increase directly with n; double n means double steps.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as the input number grows.

Common Mistake

[X] Wrong: "Because there is an if-else inside the loop, the time doubles or grows faster."

[OK] Correct: The if-else only chooses between two simple actions each time; it does not add extra loops or repeated work.

Interview Connect

Understanding how Python reads blocks and counts steps helps you explain your code clearly and think about efficiency.

Self-Check

"What if we added another loop inside the if block? How would the time complexity change?"