以下是一个使用迭代方式计算数字之和的代码示例:
def calculate_sum(n):
total = 0
for i in range(1, n+1):
total += i
return total
n = 10
sum = calculate_sum(n)
print(f"The sum of numbers from 1 to {n} is: {sum}")
如果你不想显示求和的过程,只想显示最终的求和结果,可以将打印语句放在函数外部:
def calculate_sum(n):
total = 0
for i in range(1, n+1):
total += i
return total
n = 10
sum = calculate_sum(n)
print(f"The sum of numbers from 1 to {n} is: {sum}")
这样,函数只会返回结果,而不会将每个数字的求和过程显示出来。