I'm writing a program that reads an integer number "n" from the user, and then add the numbers 1^2-2^2+3^2-4^2+...±n^2 together. For example if n = 7, then the program will return 28. I've done it like this:
n = int(input("n = "))
summ = 0
for number in range (1,n +1):
square = (number**2)*((-1)**(number+1))
summ += square
print(square)
print("The loop ran",number,"times, the sum is", summ)
The problem is that I want the program to end before the sum reaches an input "k" from the user.
n = int(input("n = "))
k = int(input("k = "))
summ = 0
for number in range (1,n +1):
square = (number**2)*((-1)**(number+1))
summ += square
print(square)
if summ > k:
break
print("The loop ran",number,"times, the sum is", summ)
If k = 6, the program returns "The loop ran 5 times, the sum is 15", but 15 is obviously over 6. The correct answer would be "The loop ran 4 times, the sum is -10". Does anyone know how to fix this? I've also tried putting the if statement right under the "for number" line, but that returns "The loop ran 6 times, the sum is 15".
summ + squareinstead, before adding tosummsumm.print("The loop ran",number-1,"times, the sum is", summ-square)