+ 2

How to add by step, multiple solutions?

I have my code that allows me to get the sum of each number consecutively up until the input and print the sum of all of those numbers. How would I edit this code to add every 3rd number instead of every number for example. Also, is there a way of finding this solution instead of using range? But instead by creating an input, then converting that input into a list and then adding them up to and including the last number (input)? https://code.sololearn.com/c1GBkwSyAY3s/?ref=app Thanks

17th Mar 2022, 4:21 PM
iic3y
iic3y - avatar
7 odpowiedzi
+ 6
You can use the step argument of range(): range(start, stop, step) range(0, 6, 3)
17th Mar 2022, 4:26 PM
Lisa
Lisa - avatar
+ 5
iicey , a bit late but anyway 2 samples: https://code.sololearn.com/cYyQTeL2SSN1/?ref=app
17th Mar 2022, 8:26 PM
Lothar
Lothar - avatar
+ 3
a = int(input()) sum = 0 for x in range (1,a+1,3): sum+=x print(sum) #sum of 1 to a numbers print(sum(range(1,a+1,2))) # 1,3,5,7,...
17th Mar 2022, 4:28 PM
Jayakrishna 🇮🇳
17th Mar 2022, 5:24 PM
Simon Sauter
Simon Sauter - avatar
+ 2
Thank you so much these are all great answers and exactly what im looking for. I appreciate your help everyone.
17th Mar 2022, 4:43 PM
iic3y
iic3y - avatar
+ 1
I’ve edited my code to show more of what I’m trying to achieve Would you be able to post code so i can visualize it please?
17th Mar 2022, 4:30 PM
iic3y
iic3y - avatar
+ 1
Without range() something like this ,without any functions. but this equal to sum(range(1,n+1)). l = [] n = int(input()) while True : l.append(n) if not (n:=n-1) : break print(sum(l)) edit: if you want only sum of range numbers, then no need list. you can directly add.
17th Mar 2022, 5:50 PM
Jayakrishna 🇮🇳