A few things,
First off, this is a very old-school type of looping.
i = 0
while i <= some_number:
do_something
i = i + 1
The last language I used that required a pattern like that was Basic. Use for loops. A standard for loop (note: NOT Python's, but I'll get to that in a minute) looks like for i=0; i<=some_number; i++ { do_something }. That is:
- Initialize
i
- Conditional for when to keep looping
- What to do after each loop block
Python is even more clear. for loops over any iterable, so:
for element in [1,3,5,7,9]:
...
Gives you 1, then 3, then 5, then 7, then 9 as element in the loop body. Use this in conjunction with the range built-in to loop N times.
for i in range(high):
# do something `high` number of times
A naive re-write looks like:
def multiples(k, n):
res = 0
for i in range(n):
res += (k+i)
print(res)
return res
def p(n):
for i in range(n):
multiples(i, i)
However that doesn't really give you what you want either. What you WANT is to assign the value multiples(i, i) TO something.
def p(n):
total = 0
for i in range(n):
total += multiples(i, i)
return total
Now we're tracking your grand total inside p, and returning it afterwards.
result = p(6)
print(result) # does what you want
Of course there's no good reason to break up these two functions. You could just as easily write:
def p(n):
total = 0
for i in range(n):
for j in range(i):
total += j+i
return total