Python finding the first even number in a list
In Python, we can use a loop to traverse the list, find the first even number, and return it. If there is no even number in the list, we can return a prompt message.
Example
def
find_first_even
(
numbers
)
:
for
num
in
numbers:
if
num %
2
==
0
:
return
num
return
"No even number found"
Example list
numbers
=
[
1
,
3
,
5
,
7
,
8
,
9
]
result
=
find_first_even
(
numbers
)
(
result
)
Code analysis:
find_first_evenThe function takes a listnumbersas its argument.- Use
forLoop through each element in the listnum。 - In the loop, use
ifstatement to check whether the current elementnumis even (i.e.,num % 2 == 0)。 - if an even number is found, return it immediately.
- If no even number is found after the loop ends, return the message "No even number found".
- In the example, the list
numberscontains the numbers[1, 3, 5, 7, 8, 9], where8is the first even number.
Output result:
8
Python3 Examples