0

Sum of consecutive numbers

How do I do this

6th Jan 2023, 4:11 PM
Garfield
Garfield - avatar
3 Respuestas
+ 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))
6th Jan 2023, 4:30 PM
Mozzy
Mozzy - avatar
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
6th Jan 2023, 4:18 PM
Hirakjyoti Medhi
Hirakjyoti Medhi - avatar
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
6th Jan 2023, 6:47 PM
Aditya Dixit