Khatra Ahmed
Khatra Ahmed

Reputation: 59

Why is the result of this python code correct?

I am really confused as to why the result of total is 20 in the below mentioned python code?. I am aware this is correct because I tested it out myself on python. Keep in mind I am new to python, and still learning so don't be too hard on me.

Could you perhaps explain to me in laymen terms why the result is 20? I just recently learnt that total += num means total = total + num.

Even though this seems like a really dumb question, I felt the need to ask because I don't understand it.

num = 0

total = 0

while num < 10:

    total +=num

    num+=2

print(total)

Upvotes: 0

Views: 164

Answers (3)

Siddharth Satpathy
Siddharth Satpathy

Reputation: 3043

Good question! One very nice way of checking the functioning of while and for loops in any programming language is to print outputs of each step inside the while / for loop. In this case we can use the following code (modified version of your code), where we are printing the values stored in total and num at each step.

num = 0

total = 0

while num < 10:
    total +=num
    print 'num = ', num, " total = ", total
    num+=2

print "After final step, total = ", total

This is our output from the above code:

num =  0  total =  0
num =  2  total =  2
num =  4  total =  6
num =  6  total =  12
num =  8  total =  20
After final step, total =  20

From the above outputs, you can see that at every step inside the for loop, the value of num kept getting increased by 2. While the values of total kept getting increased by the value of num (i.e. total_new = total_old + num). As soon as the the value of num became equal to or greater than 10, we exited the while loop, and there was no output.

Upvotes: 1

Sigma65535
Sigma65535

Reputation: 381

num = 0

total = 0

while num < 10:

    total +=num

    num+=2
    print("total =%s , num = %s" %(total,num))

output is :

total =0 , num = 2
total =2 , num = 4
total =6 , num = 6
total =12 , num = 8
total =20 , num = 10

Upvotes: 1

Patol75
Patol75

Reputation: 4547

At each iteration of the while loop, total is incremented by the value of num and num is incremented by 2. Then, the value of num is tested against 10, and the loop goes on until the test fails.
So, you have:

Initial State -> num = 0, total = 0
1st iteration -> num = 2, total = 0
2nd iteration -> num = 4, total = 2
3rd iteration -> num = 6, total = 6
4th iteration -> num = 8, total = 12
5th iteration -> num = 10, total = 20

At this point, num fails the while condition, so the process exits the loop with the value of total being 20.

Upvotes: 4

Related Questions