新聞中心
創(chuàng)新互聯(lián)python教程:

網(wǎng)站建設(shè)哪家好,找創(chuàng)新互聯(lián)建站!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序設(shè)計(jì)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了襄垣免費(fèi)建站歡迎大家使用!
寫一個(gè) Python 程序計(jì)算數(shù)列 1 +2 +3 +的和……+n 用 For 循環(huán)和函數(shù)舉例。
級(jí)數(shù) 1 +2 +3 +的 Python 和的數(shù)學(xué)公式。+n =(n(n+1)(2n+1))/6
計(jì)算數(shù)列 1 +2 +3 +和的 Python 程序。+n
這個(gè) Python 程序要求用戶輸入任意正整數(shù)。接下來,Python 程序使用上面的公式找到系列 12+22+32+…+n2的和。
# Python Program to calculate Sum of Series 12+22+32+….+n2
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.0Sum =(Number (Number+1)(2 Number+1))/6 Sum =(6 (6+1)(2 6+1))/6 =>(6 7 13)/6 和輸出,Sum = 91
計(jì)算數(shù)列 1 +2 +3 +和的 Python 程序。+n 例 2
如果你想讓 Python 顯示序列順序 12+22+32+42+52、我們必須在 If Else 的基礎(chǔ)上增加額外的 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
計(jì)算數(shù)列 1 +2 +3 +和的 Python 程序。+n 使用函數(shù)
這個(gè)系列 1 +2 +3 +的 Python 和……+n 程序同上。但是在這個(gè) Python 程序中,我們定義了一個(gè)函數(shù)來放置邏輯。
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
計(jì)算數(shù)列 1 +2 +3 +和的 Python 程序。使用遞歸
這里,我們使用 Python 遞歸函數(shù)來求數(shù)列 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)) 本文題目:Python程序:計(jì)算數(shù)列12+22+...+n2
轉(zhuǎn)載注明:http://www.fisionsoft.com.cn/article/cdgeege.html


咨詢
建站咨詢
