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

成都創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),濉溪企業(yè)網(wǎng)站建設(shè),濉溪品牌網(wǎng)站建設(shè),網(wǎng)站定制,濉溪網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營(yíng)銷,網(wǎng)絡(luò)優(yōu)化,濉溪網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長(zhǎng)自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。
編寫一個(gè) Python 程序,使用 While 循環(huán)和 For 循環(huán)計(jì)算從 1 到 N 的奇數(shù)之和,并給出一個(gè)例子。
用 For 循環(huán)計(jì)算從 1 到 N 的奇數(shù)和的 Python 程序
這個(gè) Python 程序允許用戶輸入最大值。接下來(lái),Python 將計(jì)算從 1 到用戶輸入的最大值的奇數(shù)之和。
在本例中,F(xiàn)or 循環(huán)用于保持奇數(shù)在 1 和最大值之間。
提示:建議大家參考 Python 奇數(shù)從 1 到 N 的文章,了解 Python 打印奇數(shù)背后的邏輯。
# Python Program to Calculate Sum of Odd Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
Oddtotal = 0
for number in range(1, maximum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, Oddtotal))
Python 奇數(shù)和輸出
Please Enter the Maximum Value : 12
1
3
5
7
9
11
The Sum of Odd Numbers from 1 to 12 = 36
Python 程序顯示從 1 到 N 的奇數(shù)之和,不帶 If
這個(gè) Python 奇數(shù)和程序同上。但是,我們?cè)?for 循環(huán)中使用了第三個(gè)參數(shù)來(lái)消除 If 塊。
# Python Program to Calculate Sum of Odd Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
Oddtotal = 0
for number in range(1, maximum+1, 2):
print("{0}".format(number))
Oddtotal = Oddtotal + number
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, Oddtotal))
Python 奇數(shù)和使用 for 循環(huán)輸出
Please Enter the Maximum Value : 15
1
3
5
7
9
11
13
15
The Sum of Odd Numbers from 1 to 15 = 64
使用 While 循環(huán)尋找奇數(shù)和的 Python 程序
在本 Python 程序中,我們將 For Loop 替換為 While Loop 。
# Python Program to Calculate Sum of Odd Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
Oddtotal = 0
number = 1
while number <= maximum:
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
number = number + 1
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(maximum, Oddtotal))
Python 奇數(shù)和使用 while 循環(huán)輸出
Please Enter the Maximum Value : 20
1
3
5
7
9
11
13
15
17
19
The Sum of Odd Numbers from 1 to 20 = 100
尋找 1 到 100 的奇數(shù)和的 Python 程序
這個(gè) Python 示例允許用戶輸入最小值和最大值。接下來(lái),Python 計(jì)算從最小值到最大值的奇數(shù)之和。
# Python Program to Calculate Sum of Odd Numbers from 1 to 100
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
Oddtotal = 0
for number in range(minimum, maximum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
print("The Sum of Odd Numbers from {0} to {1} = {2}".format(minimum, maximum, Oddtotal)) 文章標(biāo)題:Python程序:計(jì)算奇數(shù)和
標(biāo)題來(lái)源:http://www.dlmjj.cn/article/djedjgi.html


咨詢
建站咨詢
