Add naturals to "n" [closed]

-5

I want to implement a def suma_naturales_hasta(n) function.

For this I could use a for loop that would go through the number that I entered, that is, if I put 3, that the sum is 1 + 2 + 3.

How could I implement this for ? Should I use the range() function?

    
asked by Tony13 07.11.2017 в 21:06
source

3 answers

0

Doing it with a for could be like this:

def suma_naturales_hasta(n):
    total=0
    for i in range(1,n+1): # se pone n+1 para que incluya este último
        total+=i
    print total

suma_naturales_hasta(5) #15
suma_naturales_hasta(4) #10
    
answered by 07.11.2017 / 21:43
source
0

you could do it like that

 ###Calcular e imprimir la suma 1+2+3+4+5+...+50
    h = range(1, 51)
    print sum(h) #con el comando sum se suma los numeros de una lista
    
answered by 07.11.2017 в 21:09
0

You must add 1 to include the last number:

def suma_naturales_hasta(n):
    return sum(range(n+1)) # sumar 1 para incluir el último número

And it works:

  

> > > suma_naturales (5)
  15

    
answered by 10.11.2017 в 01:49