在Python中满足用户输入的总和后结束程序

时间:2014-10-22 01:08:48

标签: python loops while-loop sum

total = 0
not_total = True
sum_of_square = int(input("Enter desired sum: "))

while (not_total == True):
        for n in range (2): 
        total = total + n**2
        print("The sum of squares from 1^2 to {0}^2 is equal to {1}.".format(n,total))

这将提供无限数量的总和,但我想在用户输入之前停止总和

1 个答案:

答案 0 :(得分:0)

你可以比较while循环的条件语句中的两个值,如下所示:

total = 0
sum_of_square = int(input("Enter desired sum: "))

while (sum_of_squares <= total):
        for n in range (2): 
        total = total + n**2
        print("The sum of squares from 1^2 to {0}^2 is equal to {1}.".format(n,total))