編寫一個 Python 程序,使用 For 循環、While 循環和函數打印列表中的奇數,並給出一個實例。
使用 For 循環打印列表中奇數的 Python 程序
在這個 python 程序中,我們使用 For 循環來迭代這個列表中的每個元素。在 Python for 循環中,我們使用 If 語句來檢查和打印奇數。
# Python Program to Print Odd Numbers in a List
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
print("\nOdd Numbers in this List are : ")
for j in range(Number):
if(NumList[j] % 2 != 0):
print(NumList[j], end = ' ')
用戶輸入了列表元素= [3,4,5,9]。在這個 python 程序中, For Loop 迭代是
對於循環–第一次迭代:對於範圍(0,4)
中的 0,條件為真。所以,進入 If 語句
if(NumList[0] % 2!= 0) => if(3 % 2!= 0)–條件為真
該數字已打印。
第二次迭代:對於範圍(0,4)中的 1–條件為真
如果(NumList[1] % 2!= 0) = > if(4 % 2!= 0)–條件為假
跳過該數字。
第三次迭代:對於範圍(0,4)中的 2–條件為真
如果(NumList[2] % 2!= 0) = > if(5 % 2!= 0)–條件為真
該數字已打印。
第四次迭代:對於範圍(0,4)中的 3–條件為真
如果(9 % 2!= 0)–條件為真
該數字也打印出來。
第五次迭代:對於範圍(0,4)中的 4–條件為假
因此,它退出 Python For Loop
使用 While 循環打印列表中奇數的 Python 程序
這個列表中奇數的 Python 程序與上面的相同。我們剛剛將 For 循環替換為 While 循環。
# Python Program to Print Odd Numbers in a List
NumList = []
j = 0
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
print("\nOdd Numbers in this List are : ")
while(j < Number):
if(NumList[j] % 2 != 0):
print(NumList[j], end = ' ')
j = j + 1
Please enter the Total Number of List Elements: 5
Please enter the Value of 1 Element : 45
Please enter the Value of 2 Element : 65
Please enter the Value of 3 Element : 78
Please enter the Value of 4 Element : 98
Please enter the Value of 5 Element : 1
Odd Numbers in this List are :
45 65 1
用函數計算列表中奇數的 Python 程序
列表程序中的這個 Python 奇數與第一個示例相同。然而,我們使用函數來分離邏輯
def odd_numbers(NumList):
for j in range(Number):
if(NumList[j] % 2 != 0):
print(NumList[j], end = ' ')
NumList = []
Number = int(input("Please enter the Total Number of List Elements: "))
for i in range(1, Number + 1):
value = int(input("Please enter the Value of %d Element : " %i))
NumList.append(value)
print("\nOdd Numbers in this List are : ")
odd_numbers(NumList)
Please enter the Total Number of List Elements: 6
Please enter the Value of 1 Element : 22
Please enter the Value of 2 Element : 43
Please enter the Value of 3 Element : 57
Please enter the Value of 4 Element : 98
Please enter the Value of 5 Element : 12
Please enter the Value of 6 Element : 49
Odd Numbers in this List are :
43 57 49
原創文章,作者:WRJWX,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/318069.html