Code

Python Program to Calculate the Sum of Squares

This Python program calculates the sum of the squares of a list of numbers. There are multiple ways to accomplish this.

Method 1: Using a for Loop

This method defines a function sum_of_squares that iterates through a list, squares each number (including negative numbers), and adds it to a running total, which is then returned.

def sum_of_squares(numbers): total = 0 for num in numbers: total += num ** 2 return total # Example 1: my_numbers1 = [1, 2, 3, 4, 5] result1 = sum_of_squares(my_numbers1) print(f"The list of numbers is: {my_numbers1}") print(f"The sum of their squares is: {result1}") # Expected Output: # The list of numbers is: [1, 2, 3, 4, 5] # The sum of their squares is: 55 # Example 2 (with negative numbers): my_numbers2 = [2, 10, -9, 78] result2 = sum_of_squares(my_numbers2) print(f"The list of numbers is: {my_numbers2}") print(f"The sum of their squares is: {result2}") # Expected Output: # The list of numbers is: [2, 10, -9, 78] # The sum of their squares is: 6269

Method 2: Using a Generator Expression

A more concise and "Pythonic" way to achieve the same result is by using a generator expression within Python's built-in sum() function. This approach generates the square of each number on-the-fly and sums them up in a single line of code.

# Example using a generator expression: numbers = [1, 2, 10, -9, 78] sum_of_squares = sum(x**2 for x in numbers) print(f"The list of numbers is: {numbers}") print(f"The sum of their squares is: {sum_of_squares}") # Expected Output: # The list of numbers is: [1, 2, 10, -9, 78] # The sum of their squares is: 6270

0

1

Updated 2026-05-02

Contributors are:

Who are from:

Tags

Ch.2 Generative Models - Foundations of Large Language Models

Foundations of Large Language Models

Computing Sciences