# Understanding why this output is what it is.

Page 1 of 1

## 3 Replies - 194 Views - Last Post: 15 October 2019 - 05:09 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=417565&amp;s=86d7412f9fc4200e52ce11276213d91d&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Gator1013

Reputation: 0
• 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)

```

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

• Suitor #2

Reputation: 15356
• 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?

### #3 baavgai

• Dreaming Coder

Reputation: 7500
• 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

### #4 kromak

Reputation: 0
• 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)
```