Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I don't understand how this code works. Write a code that prints the sum of the first n(input) natural numbers

# 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading