如何利用 While 循環、For 循環和函數編寫一個 Python 程序來打印列表中的正數,並給出一個有用的例子。
在這個 python 程序中,我們利用 For 循環來迭代這個列表中的每個元素。在 Python for 循環中,我們使用 If 語句來驗證和打印正數。
# Python Program to Print Positive 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("\nPositive Numbers in this List are : ")
for j in range(Number):
if(NumList[j] >= 0):
print(NumList[j], end = ' ')
用戶在這個 python 程序中輸入了列表元素 = [12,-14,15,-22]
對於循環–第一次迭代:對於範圍(0,4)中的 0。條件結果為真。因此,進入 If 語句
If(NumList[0]>= 0)=>If(12>= 0)–條件為真。所以,這個正數被打印出來。
第二次迭代:對於範圍(0,4)中的 1–條件為真
如果(NumList[1] > = 0) = >如果(-14>= 0)–條件為假
跳過此數字。
第三次迭代:對於範圍(0,4)中的 2–條件為真
如果(NumList[2] > = 0) = >如果(15>= 0)–條件為真
這個正數被打印出來。
第四次迭代:對於範圍(0,4)中的 3–條件為真
如果(-22>= 0)–條件為假
跳過該數字。
第五次迭代:對於範圍(0,4)中的 4–條件為假
因此,它從PythonFor Loop 退出
這個 Python 正數列表程序和上面的一樣。我們將 For Loop 替換為 While loop 。
# Python Program to Print Positive 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("\nPositive Numbers in this List are : ")
while(j < Number):
if(NumList[j] >= 0):
print(NumList[j], end = ' ')
j = j + 1
Python 打印正數列表輸出
Please enter the Total Number of List Elements: 5
Please enter the Value of 1 Element : 12
Please enter the Value of 2 Element : 34
Please enter the Value of 3 Element : -12
Please enter the Value of 4 Element : 3
Please enter the Value of 5 Element : -22
Positive Numbers in this List are :
12 34 3
在這個 List 程序中打印正數,我們使用函數來分離邏輯。
def positive_number(NumList):
for j in range(Number):
if(NumList[j] >= 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("\nPositive Numbers in this List are : ")
positive_number(NumList)
Python 在列表輸出中打印正數
Please enter the Total Number of List Elements: 6
Please enter the Value of 1 Element : -12
Please enter the Value of 2 Element : 33
Please enter the Value of 3 Element : -15
Please enter the Value of 4 Element : 9
Please enter the Value of 5 Element : -13
Please enter the Value of 6 Element : -17
Positive Numbers in this List are :
33 9
原創文章,作者:SAGS2,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/126369.html