Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python finding the first even number in a list

Python finding the first even number in a list

Document Object Reference Manual Python3 Examples

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

)

print

(

result

)

Code analysis:

  1. find_first_even The function takes a list numbers as its argument.
  2. Use for Loop through each element in the list num。
  3. In the loop, use if statement to check whether the current element num is even (i.e., num % 2 == 0)。
  4. if an even number is found, return it immediately.
  5. If no even number is found after the loop ends, return the message "No even number found".
  6. In the example, the list numbers contains the numbers [1, 3, 5, 7, 8, 9], where 8 is the first even number.

Output result:

8

Document Object Reference Manual Python3 Examples