寫一個 Python 程序,使用 While 循環和 For 循環列印從 1 到 N 的奇數,並舉例說明。
使用 For 循環列印從 1 到 N 的奇數的 Python 程序
這個 Python 程序允許用戶輸入最大限制值。接下來,Python 將列印奇數從 1 到用戶輸入的最大限制值。
在這個例子中,Python For Loop 確保奇數在 1 和最大極限值之間。
提示:建議大家參考 Python 奇數或偶數程序文章,了解 Python 奇數背後的邏輯。
# Python Program to Print Odd Numbers from 1 to N
maximum = int(input(" Please Enter any Maximum Value : "))
for number in range(1, maximum + 1):
if(number % 2 != 0):
print("{0}".format(number))
Python 奇數用於循環和 if 語句輸出
Please Enter any Maximum Value : 10
1
3
5
7
9
列印從 1 到 N 的奇數的 Python 程序
這個 Python 程序對於從 1 到 N 的奇數的編碼同上。但是,我們將更改為循環以消除 If 塊。
如果你仔細觀察,我們從 1 開始範圍,我們使用的計數器值是 2。這意味著,對於第一次迭代次數= 1,第二次迭代次數= 3(不是 2)等等。
# Python Program to Print Odd Numbers from 1 to N
maximum = int(input(" Please Enter any Maximum Value : "))
for number in range(1, maximum + 1, 2):
print("{0}".format(number))
Python 奇數用於循環輸出
Please Enter any Maximum Value : 12
1
3
5
7
9
11
使用 While 循環列印奇數的 Python 程序
在這個 python 奇數程序中,我們只是將 For 循環替換為 While 循環。
# Python Program to Print Odd Numbers from 1 to N
maximum = int(input(" Please Enter the Maximum Value : "))
number = 1
while number <= maximum:
if(number % 2 != 0):
print("{0}".format(number))
number = number + 1
Please Enter the Maximum Value : 15
1
3
5
7
9
11
13
15
使用 For 循環顯示從 1 到 100 的奇數的 Python 程序
這個 python 顯示奇數的程序允許用戶輸入最小值和最大值。接下來,Python 顯示最小值和最大值之間的奇數。
# Python Program to Print Odd Numbers from Minimum to Maximum
minimum = int(input(" Please Enter the Minimum Value : "))
maximum = int(input(" Please Enter the Maximum Value : "))
for number in range(minimum, maximum+1):
if(number % 2 != 0):
print("{0}".format(number))
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/300192.html