Question:

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.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

Corrected Version (with corrections underlined):

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

print(Sum(10))
1. Added missing colon : after function header — required syntax in Python.
2. Initialized S = 0 before using it — otherwise, using S before assignment causes an error.
3. Updated range() to start from 1 and go up to N inclusive — so used 1 as the start and N + 1 as the end.
4. Corrected indentation to match Python’s rules for blocks inside functions and loops.
5. print(Sum(10)) is valid and correctly calls the function.
Was this answer helpful?
0
0

Top Questions on Programming in Python

View More Questions