+ 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
9 Answers
+ 6
You can use the step argument of range():
range(start, stop, step)
range(0, 6, 3)
+ 5
iicey ,
a bit late but anyway 2 samples:
https://code.sololearn.com/cYyQTeL2SSN1/?ref=app
+ 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,...
+ 2
Thank you so much these are all great answers and exactly what im looking for. I appreciate your help everyone.
+ 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?
+ 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.