Question:medium

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):
    S = 0
    for I in range(1, N + 1):
        S = S + I
    return S

print(Sum(10))

Show Hint

Always initialize variables, add missing colons,
and check your range() boundaries carefully.
Updated On: Jan 14, 2026
Show Solution

Solution and Explanation

Revised Code (with modifications highlighted):

def Sum(N):
    S = 0
    for I in range(1, N + 1):
        S = S + I
    return S

print(Sum(10))
  

1. Added a colon : to the function header, which is mandatory in Python.

2. Initialized variable S to 0 before its first use. Failure to do so results in an error.

3. Modified range() to include numbers from 1 up to and including N + 1.

4. Adjusted indentation to comply with Python's block structure requirements for functions and loops.

5. The statement print(Sum(10)) is syntactically correct and successfully executes the function.

Was this answer helpful?
0