如何使用while循环、for循环和函数以及有用的示例来编写一个Python程序来打印列表中的正数。
Python程序:使用For Loop打印列表中的正数
在此Python程序中,我们使用For Loop遍历列表中的每个元素。在for循环内部,我们使用If语句来验证和打印正数。
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]
For Loop – 第一次迭代:for 0 in range(0, 4)。条件结果为True。因此,它进入If Statement
if(NumList[0] >= 0) => if(12 >= 0) – 条件为True。因此,打印此正数。
第二次迭代:for 1 in range(0, 4) – 条件为True
if(NumList[1] >= 0) => if(-14 >= 0) – 条件为False
此数字被跳过。
第三次迭代:for 2 in range(0, 4) – 条件为True
if(NumList[2] >= 0) => if(15 >= 0) – 条件为True
此正数已打印。
第四次迭代:for 3 in range(0, 4) – 条件为True
if(-22 >= 0) – 条件为False
此数字被跳过。
第五次迭代:for 4 in range(0, 4) – 条件为 False
因此,它退出 Python For 循环
程序:使用While loop打印列表中的正数
此列表的正数程序与上述相同。我们将For Loop替换为While loop。
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
打印所有正数列表的输出
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
Python程序:使用函数打印列表中的正数
在此列表中打印正数的程序中,我们使用了Functions来分离逻辑。
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)
打印列表中正数的输出
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