I'm trying to write a program to add up number from 1 to n. I've managed to get it to print the numbers several times but not add them all. It keeps on just adding two of the numbers.
My 1st attempt is:
def problem1_3(n):
my_sum = 0
# replace this pass (a do-nothing) statement with your code
while my_sum <= n:
my_sum = my_sum + (my_sum + 1)
print()
print(my_sum)
How can I fix this problem?
I don't understand why everyone keeps making everything complex. Here is my simple solution
n = int(input())
print(n * (n + 1) // 2)
You can do it with one line, where you create a list of integers from 0
to n
and sums all the elements with sum
function
def problem1_3(n):
return sum(range(n+1))
That's where I use "math" to solve problems like this. There is a formula for solving this problem: n * (n+1) / 2.
The code I would write:
def sum(n):
return n*(n+1)//2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With