Python Find the first even number in a list

Document 对象参考手册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 explanation:

  1. find_first_evenThe function accepts a listnumbersas a parameter.
  2. Useforloop through each element in the listnum。
  3. In the loop, useifstatement to check whether the current elementnumis even (i.e.num % 2 == 0)。
  4. If an even number is found, return that even number immediately.
  5. If no even number is found after the loop ends, return the prompt message "No even number found".
  6. In the example, the listnumberscontains the numbers[1, 3, 5, 7, 8, 9], where8is the first even number.

Output result:

8

Document 对象参考手册Python3 Examples

Other extensions