1

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".

3
  • test summ + square instead, before adding to summ Commented Sep 25, 2017 at 9:13
  • Have a separate variable which you check before updating summ. Commented Sep 25, 2017 at 9:13
  • you could just subtract off the values when you print (if this is all you're doing) print("The loop ran",number-1,"times, the sum is", summ-square) Commented Sep 25, 2017 at 9:13

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.