is there any way to sum the values I got from range function?

57 Views Asked by At

I am new at python and is really confused of how loop, range, and sum work...

# Input
x = int(input("Number of pages: "))
y = int(input("Random value: "))

# Operasi
for result in range(0, x + y, y):
    ones = result % 10
    print(sum(ones))

This is the code I wrote earlier, what I am trying to achieve is: "This time, Mr. Rizz made a calculation on the pages of the course book he had. He will choose a random value for one book. Next, Mr. Rizz will add up all the ones number in total pages that can be divided by the random value." (e.g if x = 12 and y = 2 then range should be [0, 2, 4, 6, 8, 0, 2])

Now, how do I sum up all the values I got in range? It always say that it is not iterable. sorry English isn't my first language, feel free to ask if there's any confusion

2

There are 2 best solutions below

1
JonSG On

Using your code as a starting point, you likely want to accumulate a total in a variable:

x = int(input("Number of pages: "))
y = int(input("Random value: "))

total = 0
for result in range(0, x + y, y):
    total += result % 10
print(total)

Alternatively, if you want to use this definition of range() with sum() you can try:

x = int(input("Number of pages: "))
y = int(input("Random value: "))
total = sum(result % 10 for result in range(0, x + y, y))
print(total)
0
forest-spells On

In the line:

for result in range(0, x + y, y):

you give a command so that in each successive iteration of the loop, your "result" variable should represent ONE value, according to the instructions given in range (starting at 0, ending at x+y, with step of y).

In the body of the for loop, you create a variable "ones" which will take ONE different value in each iteration of the function. Then, still in the body of the function, you try to count the sum from that one value.

To calculate the sum of the elements obtained in the for loop, you can, for example, create a list:

list = []

Of course, you should create it outside of the loop (before looping), otherwise it will be deleted and created again with each iteration.

If you want to add an element coming from inside the for loop to the list, you can use the .append() function.

In the next step, you will be able to calculate the sum using the sum() function you used initially.

Just remember that the variable you create inside the function exists inside the function (it is a local variable). The variable you create inside the loop exists during one iteration.