首页 > 编程知识 正文

Python 程序:打印列表中负数

时间:2023-11-24 15:33:41 阅读:308914 作者:WVSC

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

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

在这个 python 程序中,我们使用 For 循环来迭代这个列表中的每个元素。在 Python for 循环中,我们使用 If 语句来检查和打印负数。

# Python Program to Print Negative 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("nNegative Numbers in this List are : ")
for j in range(Number):
    if(NumList[j] < 0):
        print(NumList[j], end = '   ')

在这个 python 程序中,用户输入了列表元素= [2,-12,0,-17]

对于循环–第一次迭代:对于范围(0,4) 中的 0,条件为真。所以,进入 If 语句

if(NumList[0]< 0) =>)if(2< 0) – Condition is False 跳过此数字。

第二次迭代:对于范围(0,4)中的 1–条件为真 如果(NumList[1] < 0) = >如果(-12<0)–条件为真 这个负数被打印。

第三次迭代:对于范围(0,4)中的 2–条件为真 如果(NumList[2] < 0) = >如果(0<0)–条件为假 跳过此数字。

第四次迭代:对于范围(0,4)中的 3–条件为真 如果(-17<0)–条件为真 则打印该负数。

第五次迭代:对于范围(0,4)中的 4–条件为假 因此,它退出 Python For Loop

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

这个列表中负数的 Python 程序与上面的相同。我们刚刚将 For Loop 替换为 While loop 。

# Python Program to Print Negative 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("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 程序

这个 Python 负数列表程序与第一个示例相同。然而,我们使用函数来分离逻辑

# Python Program to Print Negative Numbers in a List

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)

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

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 

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。