I am writing a function that has two parameters F & L and the function returns the sum of the squares of all the intergers between F & L

e.g if i call def sum(3,5) should output 50 (9 + 16 + 25)

def sum(first,last):
sqaure = i
for i in range(first,last + 1)

this is my program code at the moment what am I missing?

Recommended Answers

All 5 Replies

Try this and hack it!

j = 0
for i in range(2, 9):
    j = pow(i, 2)+j
print "The Final result is %d" %(j, )

BTW this is Python 2.x

Try this and hack it!

j = 0
for i in range(2, 9):
    j = pow(i, 2)+j
print "The Final result is %d" %(j, )

BTW this is Python 2.x

I am writing a function that has two parameters F & L and the function returns the sum of the squares of all the intergers between F & L

e.g if i call def sum(3,5) should output 50 (9 + 16 + 25)

def sum(first,last):
sqaure = i
for i in range(first,last + 1)

this is my program code at the moment what am I missing?

First of all, do not call your function sum because there is already a built-in Python function sum() that will sum up the numbers in a numeric list. This also gives you the hint how to solve your problem. Change your function name to mysum, a common and safe alternative.

Now here is a hint on how to create a list and use Python's sum() function ...

first = 3
last = 5
mylist = []
for x in range(first, last+1):
    mylist.append(x * x)

print( mylist )       # [9, 16, 25]
print( sum(mylist) )  # 50

First of all, do not call your function sum because there is already a built-in Python function sum() that will sum up the numbers in a numeric list. This also gives you the hint how to solve your problem. Change your function name to mysum, a common and safe alternative.

Now here is a hint on how to create a list and use Python's sum() function ...

first = 3
last = 5
mylist = []
for x in range(first, last+1):
    mylist.append(x * x)

print( mylist )       # [9, 16, 25]
print( sum(mylist) )  # 50

I just want the output to be 50, I try changing the the code but t doesn't work

I just want the output to be 50, I try changing the the code but t doesn't work

Vegaseat has pretty much given you the answer.
You dont say that code dos not work and nothing more.
Then is not possibly to help you,post your code and then you say it will not work or try to explain what you need help to.

def my_sum(first,last):
    mylist = []
    for x in range(first, last+1):
        mylist.append(x * x)
    return sum(mylist)
        
print my_sum(3,5)
'''
my output-->
50
'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.