0
0
Pythonprogramming~5 mins

Nested conditional execution in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nested conditional execution
O(1)
Understanding Time Complexity

When we use nested conditional statements, we want to know how the program's steps grow as input changes.

We ask: Does adding more input make the program take longer, and how much longer?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def check_number(n):
    if n > 0:
        if n % 2 == 0:
            return "Positive even"
        else:
            return "Positive odd"
    else:
        return "Non-positive"

This code checks if a number is positive and then if it is even or odd.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated steps here.
  • How many times: The conditions run once per function call.
How Execution Grows With Input

Since the code only checks conditions once, the steps do not increase with input size.

Input Size (n)Approx. Operations
103 checks
1003 checks
10003 checks

Pattern observation: The number of steps 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 how big the input is.

Common Mistake

[X] Wrong: "Nested conditions always make the program slower as input grows."

[OK] Correct: Nested conditions just check more things in order, but they don't repeat steps based on input size.

Interview Connect

Understanding how nested conditions affect time helps you explain your code clearly and shows you know when programs stay fast.

Self-Check

"What if we added a loop inside the nested condition? How would the time complexity change?"