To solve this problem, we need to compute the sum of squares of the first n natural numbers. The original code had a few issues that needed correction, including variable shadowing, incorrect range, and indentation errors.
Approach
- Avoid Variable Shadowing: The variable name
sumis a built-in function in Python, so we usetotalinstead to prevent shadowing. - Correct Range: To include the
nth term, we userange(1, n+1)since Python'srangeis exclusive of the upper bound. - Fix Indentation: The
if __name__ == "__main__":line should be at the top level (unindented), and the print statement should be indented under it.
Corrected Code
def sum_of_squares(n):
total = 0
for i in range(1, n + 1):
total += i * i
return total
if __name__ == "__main__":
print(sum_of_squares(10))
Explanation
- Function Definition: The
sum_of_squaresfunction initializestotalto 0, then iterates over each number from 1 ton(inclusive). For each numberi, it addsi*itototal. - Main Block: The main block calls
sum_of_squares(10)and prints the result, which is the sum of squares from 1 to 10 (1² + 2² + ... + 10² = 385).
This approach efficiently computes the desired sum with a time complexity of O(n) and space complexity of O(1). The corrections ensure the code is correct, readable, and follows Python best practices.


作者声明:本文包含人工智能生成内容。