def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
command = input("Enter a command: ")
while command == 'squares' :
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
print('Sum = ', sq_sum)
我想知道如何打印出求和线(例如:Sum = 2**2 + 3**2 + 4**2 + 5**2 = 54
)。我的代码只打印出Sum = 54
。
答案 0 :(得分:1)
您可以使用for
循环生成字符串"number**2"
并保留在列表中,稍后您可以使用' + '.join(list)
来连接此字符串
def squares(start, num):
s_sum = 0
for i in range(num):
s_sum += start**2
start += 1
return s_sum
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = squares(a, b)
terms = []
for number in range(a, a+b):
terms.append("{}**2".format(number))
terms = ' + '.join(terms)
print(terms, '=', sq_sum)
编辑或更短:
a = int(input("Enter initial integer: "))
b = int(input("Enter the number of terms: "))
sq_sum = sum(i**2 for i in range(a, a+b))
terms = ' + '.join("{}**2".format(i) for i in range(a, a+b))
print(terms, '=', sq_sum)
答案 1 :(得分:0)
您也可以更改squares()
以返回字符串。
def squares(start, num):
s_sum = 0
output = ""
for i in range(num):
s_sum += start**2
output += '{}**2+'.format(start)
start += 1
return s_sum, output[:-1]