3 Replies - 194 Views - Last Post: 15 October 2019 - 05:09 PM Rate Topic: -----

#1 Gator1013   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 15-October 19

Understanding why this output is what it is.

Posted 15 October 2019 - 02:17 PM

i = sum = 0
    
    while i <= 4:
        sum += i
        i = i+1
    print(sum)

:code:

im just learning to code and I have a question.

In the code above, I know that the output is 10. It counts until the while statement is no longer true. But I cant for the life of me figure out how it is ten in my mind. I get 7 most of the time.

Could someone please fill me in step by step as to why the output is 10?

Thank you so much for your help.

This post has been edited by modi123_1: 15 October 2019 - 02:20 PM
Reason for edit:: In the future please use the [code] tag button in the editor.


Is This A Good Question/Topic? 0
  • +

Replies To: Understanding why this output is what it is.

#2 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15356
  • View blog
  • Posts: 61,567
  • Joined: 12-June 08

Re: Understanding why this output is what it is.

Posted 15 October 2019 - 02:21 PM

Have you considered writing out the steps on paper and their corresponding values?
Was This Post Helpful? 0
  • +
  • -

#3 baavgai   User is online

  • Dreaming Coder
  • member icon


Reputation: 7500
  • View blog
  • Posts: 15,542
  • Joined: 16-October 07

Re: Understanding why this output is what it is.

Posted 15 October 2019 - 03:48 PM

EDIT: How the hell did this answer land here. Removed.

Since I am here:

Code with trace:
i = sum = 0
print("[i <= 4 ==", i <= 4, "] [i ==", i, "] [sum ==", sum, "]")
while i <= 4:
    sum += i
    i = i+1
    print("[i <= 4 ==", i <= 4, "] [i ==", i, "] [sum ==", sum, "]")
print(sum)



Results:
[i <= 4 == True ] [i == 0 ] [sum == 0 ]
[i <= 4 == True ] [i == 1 ] [sum == 0 ]
[i <= 4 == True ] [i == 2 ] [sum == 1 ]
[i <= 4 == True ] [i == 3 ] [sum == 3 ]
[i <= 4 == True ] [i == 4 ] [sum == 6 ]
[i <= 4 == False ] [i == 5 ] [sum == 10 ]
10



If this is unclear, feel free to include your own trace data.

This post has been edited by baavgai: 16 October 2019 - 05:06 AM
Reason for edit:: response A somehow landed on post B

Was This Post Helpful? 0
  • +
  • -

#4 kromak   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 12
  • Joined: 23-November 17

Re: Understanding why this output is what it is.

Posted 15 October 2019 - 05:09 PM

Put
print (sum)
and
print (i)
inside your for loop

I think you will understand, step by step, what's going on as soon as you see the values printed in the terminal, but in case of not, come back here that I will try to explain more.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1