Write a Python program to get the sum of the powers of all the numbers from start to end (both inclusive)


  1. Use range() in combination with a list comprehension to create a list of elements in the desired range raised to the given power
  2. Use sum() to add the values together
  3. Omit the second argument, power, to use a default power of 2
  4. Omit the third argument, start, to use a default starting value of 1

This Python program defines a function sum_of_powers() that calculates the sum of powers of integers between a given start and end point. The function takes three arguments, e, p, and s, where e is the end point (inclusive), p is the power to which each integer should be raised (default value is 2), and s is the start point (default value is 1).

Inside the function, a list comprehension is used to create a list of the p-th powers of integers between s and e, using the range() function. The sum() function is then used to calculate the sum of these powers. Finally, the function returns the sum of powers.

In the print() statement, the function is called with e=12 as the only argument, which means the sum of squares of integers between 1 and 12 will be calculated and printed to the console.

Source Code

def sum_of_powers(e, p = 2, s = 1):
  return sum([(i) ** p for i in range(s, e + 1)])
 
print(sum_of_powers(12))

Output

650

Example Programs