Sum of powers

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this challenge, you are required to write a Python function that calculates the sum of the powers of all the numbers from start to end (both inclusive).


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-13724{{"`Sum of powers`"}} python/for_loops -.-> lab-13724{{"`Sum of powers`"}} python/list_comprehensions -.-> lab-13724{{"`Sum of powers`"}} python/lists -.-> lab-13724{{"`Sum of powers`"}} python/tuples -.-> lab-13724{{"`Sum of powers`"}} python/function_definition -.-> lab-13724{{"`Sum of powers`"}} python/default_arguments -.-> lab-13724{{"`Sum of powers`"}} python/build_in_functions -.-> lab-13724{{"`Sum of powers`"}} end

Sum of powers

Write a Python function called sum_of_powers that takes in three parameters:

  • end - an integer representing the end of the range (inclusive)
  • power - an integer representing the power to which each number in the range should be raised (default value is 2)
  • start - an integer representing the start of the range (default value is 1)

The function should return the sum of the powers of all the numbers from start to end (both inclusive).

To solve this problem, you can follow these steps:

  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.
def sum_of_powers(end, power = 2, start = 1):
  return sum([(i) ** power for i in range(start, end + 1)])
sum_of_powers(10) ## 385
sum_of_powers(10, 3) ## 3025
sum_of_powers(10, 3, 5) ## 2925

Summary

In this challenge, you have learned how to write a Python function that calculates the sum of the powers of all the numbers from start to end (both inclusive). This challenge will help you to improve your Python programming skills.

Other Python Tutorials you may like