Python Check Whether a List Contains Negative Numbers
We can check whether a list contains negative numbers by iterating over each element. If any negative number is found, we can immediately return True; otherwise, returns False。
Example
def
contains_negative
(
numbers
)
:
for
num
in
numbers:
if
num
<
0
:
return
True
return
False
Test cases
numbers
=
[
1
,
2
,
3
,
4
,
5
]
result
=
contains_negative
(
numbers
)
(
result
)
Code analysis:
contains_negativeThe function takes a listnumbersas its argument.- Use
forLoop through each element in the listnum。 - In the loop, use
ifstatement to check whether the current elementnumwhether it is less than 0 (i.e., whether it is negative). - If a negative number is found, return immediately
True。 - If no negative number is found after the loop ends, return
False。 - In the test case, the list
numberscontains a negative number-4, so the function returnsTrue。
Output result:
True
Python3 Examples