简体   繁体   中英

Python Code Understanding the code step by step

Hi everyone I am currently practicing interpreting code and writing down the process of it every step of the way! This is what I have currently come up with.

x = 4
y = 19
finished = False
while x <= y and not finished:
    subtotal = 0
    for z in range(0, x, 4):
        print(x)
        subtotal += x
        print("This is subtotal", subtotal)
        if y // x <= 1:
            finished = True
        else:
            x += x
            print("New x value:", x)
  1. x = 4, y = 19, finished = false, subtotal =4, z = 0
  2. x = 8, y = 19, finished = false, subtotal =8, z = 0
  3. x = 16, y = 19, finished = True, subtotal =24, z = 0

I believe what I did here is correct but I am not sure how the subtotal are going to 4 to 8 to 24? If someone could explain this to me that would be great.

I understand that range is exclusive so when the x value is 4 it only goes through the for loop once hence why the subtotal is = 4. However when the x value is 8 it goes through the for loop to my under standing 2 times so this is the part where I get lost.

My last question is each time it goes through this loop does the subtotal get reset everytime the x value is changed? Would this be the reason I can not get the correct subtotals?

If someone could visually show this to me or explain it that would be awesome thank you very much!

That is because in the first loop subtotal is 0. The for loop iterates just once because it then looks like this for z in range(0, 4, 4) . Then x and subtotal become 4. NOW subtotal is brought back to 0 and the for loop becomes for z in range(0, 8, 4) so this time the for loop will iterate twice as there are two possible numbers in that range (which are 0 and 4), subtotal gets added to x which is 8 and x becomes 16, the for loop iterates ( NOTE the subtotal doesn't get brought back to 0 as the subtotal = 0 statement isn't inside the for loop) again making subtotal now 8 + 16. Which is 24.

Just examining the changes to the variables:

Start: x = 4, y = 19, finished = False
1.      subtotal = 0
2.       z = 0
3.       subtotal += x (0+4) = 4
4.       x += x (4+4) = 8
5.      subtotal = 0
6.       z = 0
7.       subtotal += x (0+8) = 8
8.       x += x (8+8) = 16
9.       z = 4
10.      subtotal += x (8+16) = 24
11.      finished = True
End:   x = 16, y = 19, finished = True, z = 4, subtotal = 24

subtotal only gets reset to 0 when the inner loop exits, as x gets large the inner loop repeats more times, 1 the first time, 2 the second.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM