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

Time:03-29

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

CodePudding user response:

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.

CodePudding user response:

By the way, there is no need to sum all the numbers one by one (complexity O(n)). You should use some basic math instead:

n = input('Enter the value: ')
result = n * (n   1) // 2

CodePudding user response:

The first line

n = int((input("Enter The Value: ")))

asks the user for a value and converts it to integer. Then, you set the variable s to 0. Then you loop through all the values from 1 up to the number that was inserted, and for each iteration you add to s the value of the number you are iterating through.

CodePudding user response:

let's assume n = 5. s=0 right?

for i in range(1,n 1): -> n 1 is now 6... s = i -> meaning... 0=0 1 -> 1=1 2 -> 3=3 3 and so on until i is n 1(6). because i always go on one more and s keeps climbing as well. the result of s will be in this case = 15

  • Related