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

創(chuàng)新互聯(lián)公司是一家專注于成都網(wǎng)站制作、網(wǎng)站設(shè)計與策劃設(shè)計,靖州網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專注于網(wǎng)站建設(shè)10余年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:靖州等地區(qū)。靖州做網(wǎng)站價格咨詢:18982081108
寫一個 Python 程序,用 For 循環(huán)找到從 1 到 N 的偶數(shù)和奇數(shù)的和,并給出一個例子。
用 For 循環(huán)求 1 到 N 的偶數(shù)和奇數(shù)之和的 Python 程序
這個 Python 程序允許用戶輸入最大限制值。接下來,它將打印從 1 到用戶輸入的極限值的偶數(shù)和奇數(shù)。在本例中,F(xiàn)or 循環(huán)確保數(shù)字介于 1 和最大限值之間。接下來,我們使用 If Else 來檢查偶數(shù)。
提示:建議大家參考偶數(shù)之和和奇數(shù)之和的文章,了解一下偶數(shù)和奇數(shù)之和背后的 For Loop 邏輯。也可以參考偶數(shù)或奇數(shù)程序和 If Else 來理解 Python 邏輯
# Python Program to find Sum of Even and Odd Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
even_total = 0
odd_total = 0
for number in range(1, maximum + 1):
if(number % 2 == 0):
even_total = even_total + number
else:
odd_total = odd_total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, even_total))
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, odd_total))Python 使用 For 循環(huán)輸出
對偶數(shù)和奇數(shù)求和
不用 If 語句計算 1 到 N 的奇偶數(shù)和的 Python 程序
這個 Python 奇偶數(shù)求和程序和上面的一樣。但是這個 Python 程序允許用戶輸入最小值和最大值。接下來,它打印最小值和最大值之間的偶數(shù)和奇數(shù)。
# Python Program to find Sum of Even and Odd Numbers from 1 to N
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
even_total = 0
odd_total = 0
for number in range(minimum, maximum + 1):
if(number % 2 == 0):
even_total = even_total + number
else:
odd_total = odd_total + number
print("The Sum of Even Numbers from 1 to {0} = {1}".format(number, even_total))
print("The Sum of Odd Numbers from 1 to {0} = {1}".format(number, odd_total))
Please Enter the Minimum Value : 10
Please Enter the Maximum Value : 40
The Sum of Even Numbers from 1 to 40 = 400
The Sum of Odd Numbers from 1 to 40 = 375 網(wǎng)站標(biāo)題:Python程序:計算偶數(shù)和奇數(shù)和
轉(zhuǎn)載來于:http://www.dlmjj.cn/article/djecjip.html


咨詢
建站咨詢
