If statement execution flow in Python - Time & Space Complexity
We want to see how the time it takes to run an if statement changes as the input changes.
Specifically, does checking conditions take more time when inputs grow?
Analyze the time complexity of the following code snippet.
def check_number(num):
if num > 0:
return "Positive"
elif num == 0:
return "Zero"
else:
return "Negative"
This code checks if a number is positive, zero, or negative and returns a string accordingly.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single if-elif-else condition check
- How many times: Exactly once per function call
Checking the condition happens once no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same even if the input number changes.
Time Complexity: O(1)
This means the time to run the if statement does not grow with input size; it stays constant.
[X] Wrong: "If statements take longer when numbers get bigger because there are more checks."
[OK] Correct: The if statement only checks conditions once per call, no matter how big the number is.
Understanding that simple condition checks run in constant time helps you explain how your code handles decisions efficiently.
"What if we added a loop that runs the if statement multiple times? How would the time complexity change?"