編寫一個 Python 程序,使用 While 循環和 For 循環計算從 1 到 N 的奇數之和,並給出一個例子。
用 For 循環計算從 1 到 N 的奇數和的 Python 程序
這個 Python 程序允許用戶輸入最大值。接下來,Python 將計算從 1 到用戶輸入的最大值的奇數之和。
在本例中,For 循環用於保持奇數在 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 循環中使用了第三個參數來消除 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 循環輸出
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 循環尋找奇數和的 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 循環輸出
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))
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/248729.html