Python Block Structure and Indentation - Time & Space 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.
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 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.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times |
| 100 | About 100 times |
| 1000 | About 1000 times |
Pattern observation: The steps increase directly with n; double n means double steps.
Time Complexity: O(n)
This means the program takes longer in a straight line as the input number grows.
[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.
Understanding how Python reads blocks and counts steps helps you explain your code clearly and think about efficiency.
"What if we added another loop inside the if block? How would the time complexity change?"