Hi need help,newbie here to python

Given a range of first 10 numbers, Iterate from start number to the end number and print the sum of the current number and previous number.

``````def sumNum(num):
previousNum = 0
for i in range(num):
sum = previousNum + i
print("Current Number", i, "Previous Number ", previousNum," Sum: ", sum)
previousNum = i
``````

print(“Printing current and previous number sum in a given range(10)”)
sumNum(10)

So I do not understand why there is a need for this>>previousNum = i at the end. Please help me understand. Totally beginner to python.
Thank you

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (`</>`) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Thank you! I’ll do that .

we need to save the previous number somewhere right ? hence we do
`previousNum = i`
Otherwise we will forget.
An alternative way of looking at this is that, we just need to the sum of a number `x` and
and the number before it ,i.e, `x-1` , do we not ? So we can simply loop from 1 to num and
get the sum by doing ` x + (x-1)`, i.e, a number and its previous

``````for i in range(1,10):
#     print(f"{i} + {i-1} = { i+(i-1) }")
print(i + (i-1))
``````

uncomment the line to get a detailed print.

1 Like

Thank you!! I understood

Happy to help