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

成都創(chuàng)新互聯是一家集網站建設,濉溪企業(yè)網站建設,濉溪品牌網站建設,網站定制,濉溪網站建設報價,網絡營銷,網絡優(yōu)化,濉溪網站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力。可充分滿足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯網需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學習、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網站。
編寫一個 Python 程序,使用 While 循環(huán)和 For 循環(huán)計算從 1 到 N 的奇數之和,并給出一個例子。
用 For 循環(huán)計算從 1 到 N 的奇數和的 Python 程序
這個 Python 程序允許用戶輸入最大值。接下來,Python 將計算從 1 到用戶輸入的最大值的奇數之和。
在本例中,For 循環(huán)用于保持奇數在 1 和最大值之間。
提示:建議大家參考 Python 奇數從 1 到 N 的文章,了解 Python 打印奇數背后的邏輯。
# 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 奇數和輸出
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 的奇數之和,不帶 If
這個 Python 奇數和程序同上。但是,我們在 for 循環(huán)中使用了第三個參數來消除 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 奇數和使用 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)尋找奇數和的 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 奇數和使用 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 的奇數和的 Python 程序
這個 Python 示例允許用戶輸入最小值和最大值。接下來,Python 計算從最小值到最大值的奇數之和。
# 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)) 網站欄目:Python程序:計算奇數和
URL標題:http://fisionsoft.com.cn/article/djedjgi.html


咨詢
建站咨詢
