写一个 Python示例计算数列 1 +2 +3 +的和……+n 用 For 循环和函数举例。
级数 1 +2 +3 +的 Python 和的数学公式。+n =(n(n+1)(2n+1))/6
这个 Python示例要求用户输入任意正整数。接下来,Python示例使用上面的公式找到系列 12+22+32+…+n2的和。
# Python Program to calculate Sum of Series 1²+2²+3²+….+n²
number = int(input("Please Enter any Positive Number : "))
total = 0
total = (number * (number + 1) * (2 * number + 1)) / 6
print("The Sum of Series upto {0} = {1}".format(number, total))
系列 1 +2 +3 +的 Python 和……+n 输出
Please Enter any Positive Number : 6
The Sum of Series upto 6 = 91.0
Sum =(Number (Number+1)(2 Number+1))/6 Sum =(6 (6+1)(2 6+1))/6 =>(6 7 13)/6 和输出,Sum = 91
如果你想让 Python 显示序列顺序 12+22+32+42+52、我们必须在 If Else 的基础上增加额外的 For Loop
number = int(input("Please Enter any Positive Number : "))
total = 0
total = (number * (number + 1) * (2 * number + 1)) / 6
for i in range(1, number + 1):
if(i != number):
print("%d^2 + " %i, end = ' ')
else:
print("{0}^2 = {1}".format(i, total))
Please Enter any Positive Number : 7
1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 = 140.0
这个系列 1 +2 +3 +的 Python 和……+n 程序同上。但是在这个 Python示例中,我们定义了一个函数来放置逻辑。
def sum_of_square_series(number):
total = 0
total = (number * (number + 1) * (2 * number + 1)) / 6
for i in range(1, number + 1):
if(i != number):
print("%d^2 + " %i, end = ' ')
else:
print("{0}^2 = {1}".format(i, total))
num = int(input("Please Enter any Positive Number : "))
sum_of_square_series(num)
Please Enter any Positive Number : 9
1^2 + 2^2 + 3^2 + 4^2 + 5^2 + 6^2 + 7^2 + 8^2 + 9^2 = 285.0
这里,我们使用 Python 递归函数来求数列 1 +2 +3 +的和。+n .
def sum_of_square_series(number):
if(number == 0):
return 0
else:
return (number * number) + sum_of_square_series(number - 1)
num = int(input("Please Enter any Positive Number : "))
total = sum_of_square_series(num)
print("The Sum of Series upto {0} = {1}".format(num, total))
标签: 源码