Sum of powers | Challenge

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-13192{{"`Sum of powers | Challenge`"}} python/for_loops -.-> lab-13192{{"`Sum of powers | Challenge`"}} python/list_comprehensions -.-> lab-13192{{"`Sum of powers | Challenge`"}} python/lists -.-> lab-13192{{"`Sum of powers | Challenge`"}} python/tuples -.-> lab-13192{{"`Sum of powers | Challenge`"}} python/function_definition -.-> lab-13192{{"`Sum of powers | Challenge`"}} python/default_arguments -.-> lab-13192{{"`Sum of powers | Challenge`"}} python/build_in_functions -.-> lab-13192{{"`Sum of powers | Challenge`"}} end

Sum of powers Challenge

Problem

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.

Example

sum_of_powers(10) ## returns 385
sum_of_powers(10, 3) ## returns 3025
sum_of_powers(10, 3, 5) ## returns 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