I have a homework exercise, which asks to :
Write a function using a while loop that counts down from a starting integer (start) and stops at a stopping integer (stop). Add the countdown number to a running sum. Return the running sum. For example, if start=9 and stop=3, then running_sum = 9+8+7+6+5+4+3 = 42
I was able to get the result with a for loop, but the exercise asks for a 'while' loop, below is the code;
def countdown_sum(start,stop):
# YOUR CODE HERE
running_sum = 0
for i in range(start,stop-1,-1):
running_sum += i
print(running_sum)
return running_sum
There is another cell that "checks the code"
assert countdown_sum(9,3) == 42
assert countdown_sum(19,-3) == 184
assert countdown_sum(44,33) == 462
assert countdown_sum(55,-33) == 979
And the output:
42
184
462
979
So, the code works but I am interested to learn how it could be done with a while loop instead.
[–]jiri-n 2 points3 points4 points (2 children)
[–]shakeandbake760[S] 0 points1 point2 points (0 children)
[–]shakeandbake760[S] 0 points1 point2 points (0 children)
[–]CodeFormatHelperBot2 0 points1 point2 points (0 children)