0
Sum of consecutive numbers
How do I do this
3 odpowiedzi
+ 2
You can use `range` to get a collection of consecutive numbers. For example:
range(1, 20) # integers from 1 to 19 inclusive.
To sum them just use the `sum` function:
sum(range(1, 20))
0
You can just use loop ig
For eg:
If you want sum of n consecutive numbers you can just use
i, sum =0, 0
while i != n:
sum += i
i+=1
0
def sum_range(start, end):
# Initialize a variable to store the sum
total = 0
# Iterate over the range of numbers
for i in range(start, end+1):
# Add the current number to the total
total += i
# Return the sum
return total
# Test the function
print(sum_range(1, 10)) # Output: 55
print(sum_range(5, 10)) # Output: 45
print(sum_range(10, 10)) # Output: 10