wordpress

Python Program for Calculating the Sum of Squares – Code in Python

Defining the function

Before we dive into the code, let’s first understand what we are trying to achieve. We want to calculate the sum of squares of the first n natural numbers. To do this, we can define a function that takes an input n and returns the sum of squares.

Here is the code for defining the function:

«`python
def sum_of_squares(n):
sum = 0
for i in range(1, n+1):
sum += i**2
return sum
«`

In this code, we define a function called sum_of_squares that takes an input n. We initialize a variable sum to 0, which will store the sum of squares. We then use a for loop to iterate through the range from 1 to n+1. For each iteration, we calculate the square of the current number i using the exponentiation operator (**), and add it to the sum. Finally, we return the sum.

Getting user input

Now that we have defined the function, we need to get the user input for the value of n. We can use the input function to prompt the user to enter a value.

Here is the code for getting user input:

«`python
n = int(input(«Enter the value of n: «))
«`

In this code, we use the input function to display the prompt «Enter the value of n: » and wait for the user to enter a value. We then use the int function to convert the user input to an integer and store it in the variable n.

Recomendado:  How to read JSON file in Python: Syntax and Examples

Calculating the sum of squares

Now that we have the user input, we can call the sum_of_squares function to calculate the sum of squares of the first n natural numbers.

Here is the code for calculating the sum of squares:

«`python
result = sum_of_squares(n)
«`

In this code, we call the sum_of_squares function with the input n and store the result in the variable result.

Displaying the result

Finally, we can display the result to the user. We can use the print function to output the result.

Here is the code for displaying the result:

«`python
print(«The sum of squares of the first», n, «natural numbers is», result)
«`

In this code, we use the print function to display the message «The sum of squares of the first», followed by the value of n, followed by the message «natural numbers is», followed by the value of result.

Now that we have all the code snippets, let’s put them together to create the complete Python program:

«`python
def sum_of_squares(n):
sum = 0
for i in range(1, n+1):
sum += i**2
return sum

n = int(input(«Enter the value of n: «))
result = sum_of_squares(n)
print(«The sum of squares of the first», n, «natural numbers is», result)
«`

That’s it! You now have a Python program that calculates the sum of squares of the first n natural numbers. You can run this program and enter different values of n to get the corresponding sum of squares.

Autor

osceda@hotmail.com

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *