I would like to create a computer program that starts at a given value and adds the same sum over and over again in a loop until the total sum reaches or exceeds a given limit.
For example: I start at the number 7. I add 3 over and over again until the total sum reaches or exceeds x (the limit). If my limit is 23, the program would stop at 25 and display that it went beyond the limit by 2.
CodePudding user response:
We have two kinds of loops in Python: for-loop and while-loop
Usually we use while when we don't know how many times we are going to do something...Here since you have a condition, and you don't know in advance how many times you have to add the value 3 to your 7 to reach the limit, it's time to use while-loop.
initial = 7
add_value = 3
limit = 23
while initial < limit:
initial = add_value
print(initial)
In every iteration, the condition (the expression you write in front of while keyword) is evaluated. If it evaluates to True, the body of the while block is gonna be executed, otherwise Python jumps out of the while-loop block and execute the next line after it.
I know you are particularly asking for loops but I just wanted to say that this question can be solved using simple math operations:
initial = 7
add_value = 3
limit = 23
d, r = divmod(limit - initial, add_value)
if r == 0:
print(initial add_value * d)
else:
print(initial add_value * (d 1))
CodePudding user response:
You can achieve this using while-loop as follows:
start = 7
end = 23
add = 3
while start <= end:
start = add
if start == end:
print(“Ended at end value”)
else:
print(“Went beyond the limit by: ”, start-end)
Here, in while-loop, we check if the start value reaches or exceeds the limit using <= . When that’s not the case, the add value is added to the start value. When it reaches or exceeds it, the loop ends. If the program reaches exactly to the limit, it prints that “Ended at value”. Otherwise, it prints “Went beyond the limit by: X”.
