How do i subract a number a specific amount of times?

Viewed 37

I have this exercise: Create a while-loop that subtracts 8 from 34, 22 times. Answer with the result.

I can subract 8 from 34, until it reaches 0, but how do I do it 22 times instead?

MIN = 0

MAX = 34

while MIN < MAX:

    MAX = MAX -8

ANSWER = MAX

Thats how i did it to subtract until it hit 0. But now i need it 22 times, so until it reaches -142. But i want the code to tell me that it's at -142, like if i didn't know it was -142.

2 Answers

You need the condition of the while loop to only be True the first 22 times. The typical way of doing this is assigning a variable outside the loop, then having the loop compare that value to something else, and change it at the end of the loop.

i = 22
while i > 0:
    # do something
    i -= 1

This isn't a typical use of a while loop though. You would be better off using a for-loop if you know something has to happen a set number of times.

for _ in range(22):
    # do something

Side note: in fact this problem is bad even for a for-loop, because you can represent it just a maths:

v = 34
print(v - (8 * 22))

Keep subtracting, for example, written your way:

TIMES = 22 RESULT = 34

while TIMES > 0: 

  RESULT = RESULT - 8
  TIMES = TIMES - 1

ANSWER = RESULT

I don’t do python though so sorry if the syntax is incorrect.

Related