0
0
Pythonprogramming~5 mins

If–else execution flow in Python - Time & Space Complexity

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

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: A single if-else decision.
  • How many times: Exactly once per function call.
How Execution Grows With Input

Whether the input number is small or large, the program only checks one condition once.

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

Pattern observation: The number of operations stays the same no matter the input size.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter what number you give it.

Common Mistake

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

Interview Connect

Understanding simple if-else time helps you explain how decisions affect program speed clearly and confidently.

Self-Check

"What if we added a loop that runs n times inside the if block? How would the time complexity change?"