Reputation: 23
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".
Upvotes: 1
Views: 100
Reputation: 16733
You are updating the summ
value and then checking the condition. You should instead check the total before actually adding the number to the sum.
for number in range(1, n+1):
square = (number**2)*((-1)**(number+1))
if summ + square > k:
break
summ += square
...
# this should work, assuming the rest of your code works.
Upvotes: 1
Reputation: 7504
Just put a condition before adding the square to summ
if summ + square > 7: break
n = int(input("n = "))
summ = 0
for number in range (1,n +1):
square = (number**2)*((-1)**(number+1))
if summ + square > 7:
break
summ += square
print(square)
print("The loop ran",number,"times, the sum is", summ)
Upvotes: 0