8

I'm trying to write a program to add up the numbers from 1 to n. I've managed to get it to print the numbers several times but not to add them all. It keeps on just adding two of the numbers.

My 1st attempt is:

def problem1_3(n):
    my_sum = 0
    while my_sum <= n:
        my_sum = my_sum + (my_sum + 1)
    print() 
    print(my_sum)

How can I fix this problem?


For the recursive version of this question, see Recursive function to calculate sum of 1 to n?

2
  • 1
    my_sum = my_sum + (my_sum + 1) doubles your previous value and adds 1 to it. Why not my_sum += 1 (which is equivalent to my_sum = my_sum + 1). Outside of that, your indentation is off and you don't show how you call the function.
    – roganjosh
    Commented May 10, 2017 at 19:49
  • 2
    while my_sum <= n This condition doesn't look correct. Did you mean to use a counter there? Consider 1 2 3 4. This will get out of the loop at 3 because the sum (1+2+3) will be larger than 4.
    – user2285236
    Commented May 10, 2017 at 19:51

11 Answers 11

21

There is no need for a loop at all. You can use the triangular number formula:

n = int(input())
print(n * (n + 1) // 2)

A note about the division (//) (in Python 3): As you might know, there are two types of division operators in Python. In short, / will give a float result and // will give an int. In this case, we could use both operators, the only difference will be the returned type, but not the value. Since multiplying an odd with an even always gives an even number, dividing that by 2 will always be a whole number. In other words - n*(n+1) // 2 == n*(n+1) / 2 (but one would be x and the other x.0, respectively).

0
14

You can do it with one line, where you sum the range of numbers from 0 to n (the end is exclusive):

def problem1_3(n):
    return sum(range(n+1))
3
  • With Python3, range produces a generator not a list, I thought it had to be explicitly converted to a list for sum, but without it it also works. Thanks for the remark. Commented Jun 5, 2017 at 7:35
  • 2
    No worries. Most standard functions & methods that accept a list will also accept a generator, and it's generally more efficient to feed them a generator if you can. So (for example) you can pass a generator to max. One big exception is the str.join method. It can accept a generator, but it needs to scan the sequence of strings twice: the 1st time it calculates the total length of the final destination string, the 2nd time it copies the data. So if you pass it a generator it has to build a list before it can process the data. The same goes for the bytes.join method.
    – PM 2Ring
    Commented Jun 5, 2017 at 8:04
  • (cont) Similarly, sorted can accept a generator, but it has to construct a list, which it then calls the list.sort method on, so there's no advantage in using sorted on a generator, rather than .sort on a list, apart from the more compact syntax.
    – PM 2Ring
    Commented Jun 5, 2017 at 8:04
3

You need 2 different variables in your code -- a variable where you can store the sum as you iterate through the values and add them (my_sum in my code), and another variable (i in my code) to iterate over the numbers from 0 to n.

def problem1_3(n):
    my_sum = 0
    i=0
    #replace this pass (a do-nothing) statement with your code
    while i <= n:
        my_sum = my_sum + i
        print(my_sum)
        i+=1
    return my_sum

You are using the my_sum variable in your code to both store the sum and iterate through the numbers.

0
1

so it will be more optimal

def f(a):
    return (a + 1) * (abs(a) + 2 * (a <= 0)) // 2
1
  • 1
    Welcome to Stack Overflow! Please don't answer just with source code. Try to provide a nice description about how your solution works. See: How do I write a good answer?. Thanks Commented Sep 11, 2018 at 9:46
1

You could use numpy to sum the numbers in the arange of 1 to n+1 (exclusive):

import numpy as np 

np.sum(np.arange(1, n+1))
1
  • A little overkill to import such a strong tool for something that can be just the same be done with equivalent built-in functions: sum(range(1, n+1))
    – Tomerikoo
    Commented Feb 1, 2023 at 11:03
0

The sum of numbers from 1 to n will be greater than n. For example, the sum of numbers from 1 to 5 is 15 which is obviously greater than 5. Your while loop terminates prematurely. You need to maintain a separate counter for the loop.

0

Real programmers use recursion (and hopes for a not too big n since there is no tail call optimization in Python):

def problem1_3(n):
    return n + problem1_3(n-1) if n > 1 else 1
1
  • And, yes, as it is currently written, this function wouldn't be able to use TCO, anyway...
    – JohanL
    Commented May 10, 2017 at 20:32
0

In this case where you iterate over a known sequence, it is better to use a for loop and add the numbers as you go:

def summation(num): 
    sumX = 0
    for i in range(1, num + 1):
        sumX = sumX + i
    return sumX

summation(3)  # You place the num you need here
0

This while loop works:

def main():
    n = int(input('Enter a number:'))              
    while n <= 1:
        n = int(input('Please input a new number'))

    total = 0
    my_sum = 0
    while (n-1) >= total:
        total = total + 1
        my_sum += total
        print(my_sum)
        
    return 

main()
1
  • Btw, if you want to just have the second while loop to say "while n >= total:" all you need to do is just put "print(my_sum) right before "my_sum += total". Commented Mar 8, 2021 at 3:26
-1
n = input("Enter Number to calculate sum")
n = int (n)
#average = 0.
#sum = 0
sum = 0.
for num in range(0,n+1,1):
    sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )

# Print sum of numbers from 1 to N inclusive

def sum2N(N):
    r = 0
    for i in range(N+1):
        #for i in range(0,N+1,1):
        #r+=i
        r=r+i
    return(r)

print(sum2N(10))
-2

How about you try it using a "While Loop":

def problem1_3(n):
my_sum = 0
while my_sum <= n:
    print(my_sum,end=" ")  # end = " " keeps from starting a new line
    my_sum = my_sum + 1
print(my_sum) 
1
  • Apart from the bad indentation, this simply doesn't answer the question. This just prints the sequence of numbers from 0 to n+1. The question asks for the sum of the numbers from 1 to n...
    – Tomerikoo
    Commented Feb 1, 2023 at 7:21

Not the answer you're looking for? Browse other questions tagged or ask your own question.