Python Forum
Question about code sequence - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Question about code sequence (/thread-4687.html)



Question about code sequence - tsetsko - Sep-02-2017

Hi all,
I am new to code and follow a few tutorial in code academy and other places, and I have a question about the sequence of code.
The code shown below will print the number up to 4 (0,1,2,3,4) = 5 numbers in total. I looked at what count +=1 means it is basically count = count + 1 (adds a number every time), however I don't understand why it is put at the bottom of the code.

count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))

How I understand it is
count = 0 #Count starts at 1.
while (count<5): #A limit is given.
count +=1 #The computer must understand that we are adding 1 after every iteration
print (count) #We use this to print the result.

So simply my question is why count +=1 at the end?

Best Regards,

Tsvetan


RE: Question about code sequence - Larz60+ - Sep-02-2017

count +=1
increments count by 1
If you didn't have this, you would never satisfy the while condition.

you should put your print routine before the increment


RE: Question about code sequence - tsetsko - Sep-03-2017

Thank you for that.