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.
CodePudding user response:
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(34 - (8 * 22))
CodePudding user response:
Keep subtracting, for example, written your way:
I = 22 RESULT = 34
while I > 0:
RESULT = RESULT - 8
I = I - 1
ANSWER = RESULT
You could also use for loop or write some of this shorter way, like
RESULT = RESULT - 8
as
RESULT -= 8
or
I = I - 1
as
I--