Test Index

CBSE Class 12 Computer Science 2025 Paper Set 4 Get it on Google PlayDownload on the App Store

© examsnet.com
Question : 26 of 37
Marks: +1, -0
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)
Solution:  
Errors found:
1. def Sum(N): colon missing at the end of the function header (syntax error).
2. S is used in S=S+I without being given a starting value (logical error; it would raise UnboundLocalError). It must be initialised to 0.
3. range(N) gives 0 to N-1, so N itself is not added (logical error). It must be range(1,N+1).
4. print(Sum(10): closing bracket missing (syntax error).
Corrected code (corrections underlined):
def Sum(N):
S=0
for I in range(1,N+1):
S=S+I
return S
print(Sum(10)))
Output:
55
Check: 1+2+⋯+10=10×112=551 + 2 + \dots + 10 = \dfrac{10 \times 11}{2} = 55.
© examsnet.com
Advertisements
Go to Question: