Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

So the question reads: Design a function that accepts an integer argument and return’s the sum of all integers from 1 up to the number passed as an argument. For example, if 50 is passed as an argument, the function will return the sum of 1,2,3,4…….50. Use recursion to calculate the sum. im having lots of trouble as you can tell by my code

def main():
    numbers= int(input('Enter a number to add the sums: ')
    mysum = sum_num(numbers,1)


def sum_num(numbers,mysum):
    start=1
    end=numbers
    if start>end:
        return 0
    else:
        return my_sum
main()
share|improve this question
1  
What exactly is the problem? "im having lots of trouble..." is too vague for SO. –  iCodez 11 mins ago
 
i cant get the code to work. also i dont know if im doing it right. –  nixvaldez 9 mins ago
 
For a thing to be recursive, it has to... y'know. Call itself recursively. Might want to start there. –  roippi 8 mins ago
 
Well you don't even have recursion in your code...Maybe you can start by learning what a recursive function call is. Google examples for recursive fibonacci and recursive factorial functions. Those are the most basic, I think. You can also make a simple recursive exponentiation function for positive integer exponents. –  Shashank Gupta 8 mins ago

2 Answers

def sumup(n):
    # this one is your emergency break. you return 1 if n gets below
    # a certain threshold, otherwise you'll end up with an infinite
    # loop
    if n <= 1:
        return n
    # here is the recursion step, we return (n + "the sum to n+1")
    else:
        return n + sumup(n-1)

print(sumup(50))
share|improve this answer
def f(s):
    if s == 0:
        return 0
    else:
        return f(s-1) + s

print f(int(input()))
share

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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