0

Please note, the code is extracted with placeholder data for example's sake. It might not make that much sense alone, but it does play a role in a larger project.

The code is as follows:


for x in range(10):
 Total = 0    

 for i in range(4):
        t = 1 + i**x
        print ("Unit", i+1 ,"value: ", t)
        Total += t
 print("Total: ", Total)

 if Total == 280:
    break  

and it gives the following result:

Unit 1 value:  2
Unit 2 value:  2
Unit 3 value:  2
Unit 4 value:  2
Total:  8
Unit 1 value:  1
Unit 2 value:  2
Unit 3 value:  3
Unit 4 value:  4
Total:  10
Unit 1 value:  1
Unit 2 value:  2
Unit 3 value:  5
Unit 4 value:  10
Total:  18
Unit 1 value:  1
Unit 2 value:  2
Unit 3 value:  9
Unit 4 value:  28
Total:  40
Unit 1 value:  1
Unit 2 value:  2
Unit 3 value:  17
Unit 4 value:  82
Total:  102
Unit 1 value:  1
Unit 2 value:  2
Unit 3 value:  33
Unit 4 value:  244
Total:  280

The above program ends when the total is equal to 280.

How could I add a feature that ends the program when the change in total from one iteration to another is equal to or greater than a certain amount. In pseudo-code:

if Δ in Total is > 100:
   break

This means the program would have stopped at a total of 102, as the Δ in total between 100 and 280 is > 100, with the exact change being 178.

1 Answers1

0

Let's try this, create a tmp:

tmp = 0
for x in range(10):
    total = 0    
    for i in range(4):
        t = 1 + i**x
        print ("Unit", i+1 ,"value: ", t)
        total += t
    print("Prev value: ", tmp)
    print("Total: ", total)
    if abs(tmp - total) > 100 or total == 280:
        break
    tmp = total
isydmr
  • 649
  • 7
  • 16
  • You are welcome! Please note that variable names should be **lowercase**, `total` instead of `Total`. – isydmr Jan 15 '20 at 14:15
  • It is also worth to mention that if the first sum is greater than `100` it will also break the loop as `tmp` starts with `0`. – isydmr Jan 15 '20 at 14:16