Python 程序:打印列表中的负数

编写一个 Python 程序,使用 For 循环、While 循环和函数打印列表中的负数,并提供实际示例。

在此程序中,我们使用 For 循环来迭代列表中的每个元素。在 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("\nNegative Numbers in this List are : ")
for j in range(Number):
    if(NumList[j] < 0):
        print(NumList[j], end = '   ')
Program to Print Negative Numbers in a List 1

在此 Python 程序中,用户输入的 列表元素为 = [2, -12, 0, -17]

For循环 – 第一次迭代:for 0 in range(0, 4)
条件为 True。因此,它进入If 语句

if( NumList[0] < 0) => if( 2 < 0 ) – 条件为 False
此数字被跳过。

第二次迭代:for 1 in range(0, 4) – 条件为True
if(NumList[1] < 0) => if( -12 < 0 ) – 条件为 True
此负数将被打印。

第三次迭代:for 2 in range(0, 4) – 条件为True
if(NumList[2] < 0) => if( 0 < 0 ) – 条件为 False
此数字被跳过。

第四次迭代:for 3 in range(0, 4) – 条件为True
if( -17 < 0 ) – 条件为 True
此负数将被打印。

第五次迭代:for 4 in range(0, 4) – 条件为 False
因此,它退出 Python For 循环

Python 程序:使用 While 循环打印列表中的负数

此列表负数程序与上面相同。我们只是将 For 循环替换为 While 循环

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("\nNegative Numbers in this List are : ")
while(j < Number):
    if(NumList[j] < 0):
        print(NumList[j], end = '   ')
    j = j + 1

使用 while 循环打印列表中的负数输出

Please enter the Total Number of List Elements: 5
Please enter the Value of 1 Element : 12
Please enter the Value of 2 Element : -13
Please enter the Value of 3 Element : -15
Please enter the Value of 4 Element : 3
Please enter the Value of 5 Element : -22

Negative Numbers in this List are : 
-13 -15 -22

Python 程序:使用函数打印列表中的负数

此负数列表程序与第一个示例相同。但是,我们使用 函数分离了逻辑

def negative_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("\nNegative Numbers in this List are : ")
negative_number(NumList)

使用函数和 for 循环打印负数列表的输出。

Please enter the Total Number of List Elements: 6
Please enter the Value of 1 Element : -12
Please enter the Value of 2 Element : 5
Please enter the Value of 3 Element : -7
Please enter the Value of 4 Element : -8
Please enter the Value of 5 Element : 9
Please enter the Value of 6 Element : -10

Negative Numbers in this List are : 
-12 -7 -8 -10