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

成都創(chuàng)新互聯(lián)成都企業(yè)網(wǎng)站建設(shè)服務(wù),提供成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計網(wǎng)站開發(fā),網(wǎng)站定制,建網(wǎng)站,網(wǎng)站搭建,網(wǎng)站設(shè)計,自適應(yīng)網(wǎng)站建設(shè),網(wǎng)頁設(shè)計師打造企業(yè)風(fēng)格網(wǎng)站,提供周到的售前咨詢和貼心的售后服務(wù)。歡迎咨詢做網(wǎng)站需要多少錢:028-86922220
編寫一個 Python 程序,使用 For 循環(huán)、While 循環(huán)和函數(shù)打印列表中的奇數(shù),并給出一個實例。
使用 For 循環(huán)打印列表中奇數(shù)的 Python 程序
在這個 python 程序中,我們使用 For 循環(huán)來迭代這個列表中的每個元素。在 Python for 循環(huán)中,我們使用 If 語句來檢查和打印奇數(shù)。
# 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 迭代是
對于循環(huán)–第一次迭代:對于范圍(0,4) 中的 0,條件為真。所以,進入 If 語句
if(NumList[0] % 2!= 0) => if(3 % 2!= 0)–條件為真 該數(shù)字已打印。
第二次迭代:對于范圍(0,4)中的 1–條件為真 如果(NumList[1] % 2!= 0) = > if(4 % 2!= 0)–條件為假 跳過該數(shù)字。
第三次迭代:對于范圍(0,4)中的 2–條件為真 如果(NumList[2] % 2!= 0) = > if(5 % 2!= 0)–條件為真 該數(shù)字已打印。
第四次迭代:對于范圍(0,4)中的 3–條件為真 如果(9 % 2!= 0)–條件為真 該數(shù)字也打印出來。
第五次迭代:對于范圍(0,4)中的 4–條件為假 因此,它退出 Python For Loop
使用 While 循環(huán)打印列表中奇數(shù)的 Python 程序
這個列表中奇數(shù)的 Python 程序與上面的相同。我們剛剛將 For 循環(huán)替換為 While 循環(huán)。
# 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 + 1Please 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 用函數(shù)計算列表中奇數(shù)的 Python 程序
列表程序中的這個 Python 奇數(shù)與第一個示例相同。然而,我們使用函數(shù)來分離邏輯
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 文章名稱:Python程序:打印列表中奇數(shù)
地址分享:http://m.5511xx.com/article/dpposge.html


咨詢
建站咨詢
