Hi everyone.

Basically i'm very new to python and i'm trying to learn it at a fairly fast pace. One of the books i am using is comparing for and while loops, showing how while loops are more flexible than for loops but more complicated.

Anyway to the point.. In the book there is the program:

n = int(input('how many numbers to sum?'))
total = 0
i = 1
while i <= n:
    s = input('enter number' + str(i) + ': ')
    total = total + int(s)
    i = i + 1
print('the sum is ' + str(total))

Which is fairly straight forward, the user is asked for input which is stored as the variable n, the variable total starts at 0, and i starts at 1, the while loop checks to see if i is less than or equal to the value that is stored in n (the value the user entered earlier) correct so far?

If that evaluates to true then the loops function starts. So the user is then asked to enter a number.. now the next piece of code seems pointless to me?

str(i)

as when its removed the program acts the exact same way. The next piece of code is part of the addition of the numbers being entered by the user, so total become total + the number added by the user. Then the final part of the while loop is the increment? i = i + 1 stops the program from being an infinite loop. So the first time the program the goes through the loop it adds 1 onto the value in the variable i and so on and so forth. It will stop when the value stored in i in greater than the value stored in n.

So basically i think i've got this loop thing down, but this what seems pointless piece of code that has been thrown into this program is baffling me someone explain lol!

Cheers.

EDIT:

I may as well show the same thing for the for loop version of the code:

n = int(input('how many numbers to sum?'))
total = 0
for i in range(n):
    s = input('please enter number ' + str(i + 1) + ': ')
    total = total + int(s)
print('the sum is ' + str(total))

the line:

s = input('please enter number ' + str(i + 1) + ': ')

Remove:

+ str(i + 1) +

and it still functions as expected?!

Edited 6 Years Ago by vandalised: n/a

Yes, it still functions, but one will prompt
please enter number 1:
please enter number 2:
... and so on

and the other just
please enter number:
please enter number:
... and so on

On that note i'm going to bed, that is really a slap hand on forehead moment (DOH). Its what you get for trying to learn programming at 3am eh?

Cheers btw vegaseat

On that note i'm going to bed, that is really a slap hand on forehead moment (DOH). Its what you get for trying to learn programming at 3am eh?

Cheers btw vegaseat

Happens to the best of us!

This question has already been answered. Start a new discussion instead.