If–else execution flow in Python - Time & Space Complexity
We want to see how the time a program takes changes when it uses if-else decisions.
How does choosing one path or another affect how long the program runs?
Analyze the time complexity of the following code snippet.
def check_number(num):
if num > 0:
return "Positive"
else:
return "Non-positive"
result = check_number(10)
This code checks if a number is positive or not and returns a message.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single if-else decision.
- How many times: Exactly once per function call.
Whether the input number is small or large, the program only checks one condition once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 check |
| 100 | 1 check |
| 1000 | 1 check |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter what number you give it.
[X] Wrong: "If-else makes the program slower as numbers get bigger."
[OK] Correct: The if-else only checks once, so bigger numbers don't add more work.
Understanding simple if-else time helps you explain how decisions affect program speed clearly and confidently.
"What if we added a loop that runs n times inside the if block? How would the time complexity change?"