Skip to content
Sign upLog in
← Back to Community

4.5. For: Sum of cubes

Profile icon
pole55

For the given integer N calculate the following sum: 1³ + 2³ + ... + N³

Voters
Profile icon
KARENSOFIASOFI2
Profile icon
DP1VSuspanovs
Profile icon
PriscillaWillia
Profile icon
dcorbin8798
Profile icon
TienDungDung1
Profile icon
NormanTaylor
Profile icon
tomsfy
Profile icon
OkhmushVlad
Profile icon
WillKoehrsen
Profile icon
pole55
Comments
hotnewtop
Profile icon
WillKoehrsen

Good work! This is also a nice opportunity to apply a recursive function. The below code does the same task but recursively, by calling itself!

n = int(input("N: ")) def cuber(n): if n == 1: return 1 return n**3 + cuber(n - 1) print(cuber(n))

To make a recursive function you need two parts:

  1. The base case: how the program exits. The lines
if n == 1: return 1

are the base case.

  1. The recursive (general) case: the solution is expressed as a smaller version of itself. The line
return n**3 + cuber(n - 1)

is the recursive case.

Here's a link to the repl: https://repl.it/@WillKoehrsen/45-Recursive-For-Sum-of-cubes

Profile icon
Neil_Chaudhury

OK, so the first thing you need to do is change
for e in range(n) to for e in range(1, n+1)
This way, you're starting from 1 and ending at n.
Also, the for loop where you are going through lst could be simplified to a sum(statement),
eg. total = sum(lst)
Hope this helped you,
Neil
Btw, I forked your real and applied the above changes. here is my link > https://repl.it/@Neil_Chaudhury/45-For-Sum-of-cubes

Profile icon
PYer

Cool! Just saying, I would make line one like this:
n = int(input('N: '))
That way they know to type.