define a function to sum up the numbers in a range | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

define a function to sum up the numbers in a range

Help!! I want to define a function where it can sum up the numbers in a given range. What’s wrong with this code? Def sum(x,y): for i in range(x,y): x += i Return x Thank you!

9th Jun 2019, 4:32 PM
Yang Yang
Yang Yang - avatar
9 Answers
+ 8
There are a couple things wrong: First, as Python is case sensitive, the def and return keywords would both return errors (changing them to all lowercase should fix that) Second, you seem to be using the lower value in the range when adding up all the values which may mess with the loop and skew the results. I would recommend creating another variable (declaring it before the for loop and giving it a value of 0) and using that instead to be added to i each iteration. Lastly, you have your return statement within the loop which will exit the function upon the first iteration of the loop, which I'm not sure you want. Instead, move the return statement outside of the loop to be executed once it finishes.
9th Jun 2019, 4:37 PM
Faisal
Faisal - avatar
+ 7
An other recommandation from my side: Do not use names from functions, methods and so on used from python as names for your own functions or variables. This can cause heavy problems because its not easy to find out the reason why python shows an error. sum() is a function from python.
9th Jun 2019, 4:48 PM
Lothar
Lothar - avatar
+ 5
Here is another very simple way of calculating sum of a given range from 5 upto and including 20: print(sum(range(5, 21))) # output is 200
9th Jun 2019, 6:56 PM
Lothar
Lothar - avatar
+ 5
Choe, you probably want to fool me? ;-)) You don‘t use sum() function, but instead you use “hidden” + operator. BTW this a tremendous time consuming variation.
10th Jun 2019, 8:16 AM
Lothar
Lothar - avatar
+ 2
from Faisal observations, def sum(x,y): res = 0 for i in range(x,y): res += i return res
9th Jun 2019, 4:55 PM
Choe
Choe - avatar
+ 2
Lothar but can you do it without using sum() ??hehe 😄 print(eval("\x2b".join([str(i) for i in range(5, 21)])))
9th Jun 2019, 7:12 PM
Choe
Choe - avatar
+ 1
Faisal Got it! It works now! Thank you very much!!!!
9th Jun 2019, 5:01 PM
Yang Yang
Yang Yang - avatar
+ 1
--here is a sample you can do by using lists: def total(x,y): a_list = [] for i in range(x,y+1): a_list.append(i) return sum(a_list) print(total(2,7)) >>>output: 27 --the code will include the last number in the range --also note that the "sum" is a list method which calculates the sum of numbers in a list that's the reason Lothar mentioned in why not to use a method name in a funcion you created.
9th Jun 2019, 5:02 PM
Mo Hani
Mo Hani - avatar
0
Lothar thank you!!!
9th Jun 2019, 5:02 PM
Yang Yang
Yang Yang - avatar