Python Forum
What's the meaning of this coding? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: What's the meaning of this coding? (/thread-7984.html)



What's the meaning of this coding? - xin2408 - Feb-01-2018

What's the meaning of this code? Could someone please explain this to me? Thanks! Huh

temp = input('Please enter a number:')
number = int(temp)
i = 1
while number:
    print(i)
    i = i + 1
    number = number - 1
I could write the first two lines but the later on of i = i +1 & number = number -1
What's the relationship between the number and i?


RE: What's the meaning of this coding? - Larz60+ - Feb-01-2018

i keeps count of the number of iterations,
while number is one less after each iteration.

this could also be written as:
number = int(input('Please enter a number: '))
i = 1
while number:
    print(i)
    i += 1
    number -= 1
Output:
>>> number = int(input('Please enter a number: ')) Please enter a number: 5 >>> i = 1 >>> while number: ... print(i) ... i += 1 ... number -= 1 ... 1 2 3 4 5 >>>



RE: What's the meaning of this coding? - xin2408 - Feb-01-2018

But why this output will stop at five? Ah, is it due to that after 5 times of iteration, the number will become 0 and it means False in the bool so the iteration stops? Does that mean right?


RE: What's the meaning of this coding? - buran - Feb-01-2018

(Feb-01-2018, 06:41 PM)xin2408 Wrote: Ah, is it due to that after 5 times of iteration, the number will become 0 and it means False in the bool so the iteration stops? Does that mean right?
yes, that is correct. when number becomes 0 it is evaluated as False and it will exit the while loop. That is also correct for empty list, empty dict, empty str, etc.


RE: What's the meaning of this coding? - Kebap - Feb-02-2018

Usually, you want to use a for loop for this kind of task:

for i in reversed(range(1, number)):
  print(i)



RE: What's the meaning of this coding? - DeaD_EyE - Feb-02-2018

Or you can do it direct with the range function.

list(range(10, 0, -1))
Means: count from 10 till exclusive 0. Each step counts -1.


RE: What's the meaning of this coding? - xin2408 - Feb-02-2018

(Feb-02-2018, 01:07 PM)Kebap Wrote: Usually, you want to use a for loop for this kind of task:
for i in reversed(range(1, number)): print(i)

However, this way the number u enter could not be printed right?:-D


RE: What's the meaning of this coding? - Kebap - Feb-08-2018

You can fiddle with the parameters to the range() function to set the start and end boundaries. There is even an optional third parameter, but I'll leave that for you to figure out