asked 226k views
3 votes
write code using the range function to add up the series 15,20,25,30 50 and print the resulting sum each step along the way

asked
User Margalit
by
8.4k points

1 Answer

7 votes

Answer:

Three parameters, start, stop, and step, are required for the range() method. The start value is by default set to 0 and the step value to 1. This function may be used in conjunction with a for loop to repeatedly cycle through a list of integers and apply operations to them.

Let's create the code to add up the numbers in the series 15, 20, 25, 30, and 50 and output the total at each stage.

# Initialize a variable to store the sum

total_sum = 0

# Use the range function to create a sequence of numbers from 15 to 50 (inclusive) with a step of 5

for number in range(15, 51, 5):

# Add the current number to the total_sum

total_sum += number

# Check if the number is 30 or 50 (the final values in the desired sequence)

if number == 30 or number == 50:

# Print the sum at this step

print(f'Sum after adding {number}: {total_sum}')

The aforementioned code sets up the variable total_sum to hold the series sum. Finally, with a step of 5, we run through the values from 15 to 50 using a for loop and the range() method. As stated in the issue description, we add the current number to total sum within the loop and output the sum when the number reaches 30 or 50.

answered
User Stephan Schlecht
by
7.9k points

No related questions found