0

Sum of Consecutive Numbers

I'm trying to solve another problem with python in "python for beginner", i must creare a program that execute the sum of all the numbers of an input,i used the function "For" but the output is not correct because it won't give me the right result, the code is this: N = int(input()) #your code goes here for i in range(N): somma = i * i print (somma) The input is 358 and the Expected Output is 64261, what is wrong in the function "For"?

10th Oct 2021, 8:54 AM
Luigi Pietragalla
Luigi Pietragalla - avatar
3 Respostas
+ 5
What you did print the square of all numbers. You must give somma a value before adding something with it. Here for calculating sum you must declare somma with 0. Give the range upto N+1 as the range calculate only upto N-1. Then add somma with each i and print after for loop. N = int(input()) #your code goes here somma=0 for i in range(N+1): somma+=i print (somma)
10th Oct 2021, 10:11 AM
Arun Ruban SJ
Arun Ruban SJ - avatar
+ 5
You need to declare somma before entering the loop. Also, sum means "+" (you used the multiplication sign). You need to add i to somma. Print somma only once after the loop (not inside the loop)
10th Oct 2021, 9:12 AM
Lisa
Lisa - avatar
0
To declare you intend somma = i ? (somma in english is Sum) So in the loop what i must write? (yes i wrote * just because with + the loop end with the result of 700 or something, and i'm out of idea lol)
10th Oct 2021, 10:05 AM
Luigi Pietragalla
Luigi Pietragalla - avatar