0
0
Pythonprogramming~5 mins

If statement execution flow in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: If statement execution flow
O(1)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Single if-elif-else condition check
  • How many times: Exactly once per function call
How Execution Grows With Input

Checking the condition happens once no matter the input size.

Input Size (n)Approx. Operations
101 check
1001 check
10001 check

Pattern observation: The number of operations stays the same even if the input number changes.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the if statement does not grow with input size; it stays constant.

Common Mistake

[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.

Interview Connect

Understanding that simple condition checks run in constant time helps you explain how your code handles decisions efficiently.

Self-Check

"What if we added a loop that runs the if statement multiple times? How would the time complexity change?"