fork download
  1. def somatorio(x, y):
  2. soma = 0
  3. while x <= y:
  4. soma += x
  5. x += 1
  6. return soma
  7.  
  8. print(somatorio(1, 2))
  9. print(somatorio(1, 5))
  10.  
  11. def somatorio_2(x, y): # usa a fórmula da soma da P.A.
  12. return (x + y) * (y - x + 1) // 2
  13.  
  14. print(somatorio_2(1, 2))
  15. print(somatorio_2(1, 5))
  16.  
  17. def somatorio_3(x, y): # usando coisas prontas da linguagem
  18. return sum(range(x, y + 1)) # um range não inclui o valor final, por isso soma 1 ao y
  19.  
  20. print(somatorio_3(1, 2))
  21. print(somatorio_3(1, 5))
  22.  
  23.  
Success #stdin #stdout 0.02s 9060KB
stdin
Standard input is empty
stdout
3
15
3
15
3
15