# Write a code that prints the sum of the first n(input) natural numbers.
n = int((input("Enter The Value: ")))
s = 0
for i in range(1,n+1):
s += i
print(s)
I figured out the code but I can’t understand how this code works. Please help me.
I am confused about how this code works.
>Solution :
Let’s go line by line:
n = int((input("Enter The Value: ")))
Variable n is assigned to the value entered by the user converted to integer
s = 0
Variable s is assigned to value 0
for i in range(1,n+1):
This is a loop on a range of numbers that will go from number 1 until the number passed by the user plus one. I suppose your understanding problem is here.
The second parameter of range is the exclusive stop value, meaning that if the user pass 5, the range will be range(1,5), meaning it will range between 1 to 4.
s += i
Here you’re incrementing the value of variable s.
print(s)
Print the value of variable s.