When using somatorio = 0
within the for
repeat structure, its somatorio
will always be reset to 0
before adding the next number. Remove this initialization from within the repeat structure as it should not be repeated, but rather be executed once before starting the calculation:
somatorio = 0
for s in range(....):
The range()
function works as follows: If you pass 2 parameters, the first parameter is the start number, and the second is the final number. In the way you did, you are prompting the user to enter the upper limit and storing it in the variable x
, but at the time of using range(x, y)
put x
as the first parameter! It's inverted. To fix you should swap in one of the two points:
-
Store the lower border in x
instead of top :
x = int(input("Entre com o limite inferior 'x':"))
-
Or reverse the range function call:
for s in range(y, x):
Just as you did in range(1, 16)
to generate 15 numbers, you must put +1
at the upper bound by using the range()
function because it ends one step before reaching the last number. Then you would be: range(x, y+1)
(or range(y, x+1)
if you inverted the order as suggested in the above item)
Python is much simpler and didactic than C, it's possible to write that same code much more intuitively and efficiently. In the example below, the same code uses only two lines, but remains readable. I will leave here as a study and future reference:
# Já cria a lista diretamente com os números digitados:
numeros = [int(input(f"Digite o {i} número:")) for i in range(1, 16)]
# Já soma direto:
somatorio = sum(
numeros[int(input('Limite inferior:')):int(input('Limite superior'))+1])