Home > database >  The Sum of Consecutive Numbers
The Sum of Consecutive Numbers

Time:12-25

I have to write a program which asks the user to type in a limit. The program then calculates the sum of consecutive numbers (1 2 3 ...) until the sum is at least equal to the limit set by the user.

In addition to the result it should also print out the calculation performed. I should do this with only a while loop, no lists or True conditionals.

limit = int(input("Limit:"))
base = 0
num = 0
calc = " "
while base < limit:
    base  = num
    num  = 1
    calc  = f"   {num}"
print(base)
print(f"The consecutive sum: {calc} = {base}")

So for example, if the input is 10, the output should be 10 and underneath that should be "The consecutive sum: 1 2 3 4 = 10." If the input is 18, the output should be 21 and underneath that should be "The consecutive sum: 1 2 3 4 5 6 = 21."

Right now I can get it to print the final result (base) and have gotten it to print out the calculation, but it prints out one integer too many. If the input is 10, it prints out 1 2 3 4 5 when it should stop before the 5.

CodePudding user response:

I would avoid the while loop and use range instead. You can derive the value of the last term with arithmetic.

If the last term is

  • Related