Search code examples
pythonloops

The Sum of Consecutive Numbers


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.


Solution

  • One way that came to my mind is concatenating values for each iteration:

    limit = int(input("Limit:"))
    base = 0
    num = 1
    num_total = 0
    calculation = 'The consecutive sum: '
    while base < limit:
        calculation += f"{num} + "
        base += num
        num += 1
    
    print(f"{calculation[:-3]} = {base}")
    print(base)
    
    #> Limit:18
    ## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 = 21
    ## 21
    

    The other way is printing value on each iteration without new line in the end (but you have additional + sign in the end here):

    limit = int(input("Limit:"))
    base = 0
    num = 1
    num_total = 0
    print('The consecutive sum: ', end='')
    while base < limit:
        print(f"{num} + ", end='')
        base += num
        num += 1
    
    print(f"= {base}")
    print(base)
    
    #> Limit:18
    ## The consecutive sum: 1 + 2 + 3 + 4 + 5 + 6 + = 21
    ## 21