Why conditional statements are needed in Python - Performance Analysis
Conditional statements help decide which parts of code run based on conditions.
We want to see how these decisions affect how long the program takes as input grows.
Analyze the time complexity of the following code snippet.
def check_numbers(nums):
count = 0
for num in nums:
if num > 10:
count += 1
return count
This code counts how many numbers in a list are greater than 10.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every number in the input list.
As the list gets bigger, the program checks more numbers one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the size of the list.
Time Complexity: O(n)
This means the time to run grows in a straight line as the input list gets bigger.
[X] Wrong: "The if condition makes the code run slower for bigger inputs."
[OK] Correct: The condition only checks each item once inside the loop, so it doesn't add extra loops or repeated work.
Understanding how conditions affect time helps you explain your code clearly and shows you know how programs behave as data grows.
"What if we added a nested loop inside the if condition? How would the time complexity change?"