Q.The code given below accepts N as an integer argument and returns the sum of all integers from 1 to N. Observe the following code carefully and rewrite it after removing all syntax and logical errors. Underline all the corrections made.
def Sum(N)
for I in range(N):
S=S+I
return S
print(Sum(10)
def Sum(N)
for I in range(N):
S=S+I
return S
print(Sum(10)
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The original code has two main errors: the accumulator S is not initialized, and range() is used incorrectly. Fix by initializing S = 0 and changing range(N) to range(1, N + 1). Also add the missing colon after def Sum(N) and the missing closing parenthesis in print(Sum(10)).
The problem asks us to identify and correct both syntax and logical errors in code meant to calculate the sum of integers from 1 to N. Understanding variable initialization and how Python's range() function works is the key.
Concept and intuition
-
Variable initialization. When you write
S = S + I, Python first evaluates the right-hand side (S + I). IfSwas never assigned before, Python raises aNameError. An accumulator likeSmust be initialized to a starting value —0for a sum — before the loop. -
Python's
range()function.range(stop)produces0, 1, 2, ..., stop-1. Sorange(N)gives0, 1, ..., N-1.range(start, stop)producesstart, ..., stop-1. Sorange(1, N+1)gives1, 2, ..., N. The task is the sum from 1 to N, which must include N and start at 1, sorange(N)is wrong here.
Errors and corrections
- Missing colon after the function header:
def Sum(N)must bedef Sum(N):. Snot initialized: addS = 0before the loop.- Wrong loop range:
range(N)gives0..N-1; change it torange(1, N + 1)to sum1..N. - Missing closing parenthesis in the last line:
print(Sum(10)must beprint(Sum(10)). …
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.