Why input and output are required in Python - Performance Analysis
When we write programs, input and output help us interact with the world outside the code.
We want to know how the time a program takes changes as the input size changes.
Analyze the time complexity of the following code snippet.
user_numbers = input("Enter numbers separated by space: ").split()
numbers = [int(num) for num in user_numbers]
sum_numbers = 0
for number in numbers:
sum_numbers += number
print(f"Sum is: {sum_numbers}")
This code takes numbers from the user, adds them up, and shows the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of numbers to add them.
- How many times: Once for each number entered by the user.
As the user enters more numbers, the program does more additions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with how many numbers are entered.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Input and output do not affect how long the program takes."
[OK] Correct: Getting input and showing output take time too, especially if the input is large.
Understanding how input size affects program time helps you write better code and explain it clearly in interviews.
"What if we read input numbers one by one instead of all at once? How would the time complexity change?"