结束for循环,Python

时间:2017-09-25 09:10:37

标签: python for-loop

我正在编写一个读取整数的程序" n"从用户,然后将数字1^2-2^2+3^2-4^2+...±n^2加在一起。例如,如果n = 7,那么程序将返回28.我已经这样做了:

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)

问题是我希望程序在总和到达输入之前结束" k"来自用户。

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)

如果k = 6,程序返回"循环运行5次,总和为15",但15显然超过6.正确的答案是"循环运行4次,总和是-10"。有谁知道如何解决这一问题?我也尝试将if语句放在"对于数字"但是,返回"循环运行了6次,总和为15"。

2 个答案:

答案 0 :(得分:1)

您正在更新summ值,然后检查条件。您应该在实际将数字添加到总和之前检查总数。

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.

答案 1 :(得分:0)

在将广场添加到汇总

之前设置一个条件
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)