Python Find 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)
print(result)
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:
find_first_evenThe function accepts a listnumbersas a parameter.- 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 that even number immediately.
- If no even number is found after the loop ends, return the prompt 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:
8Other extensions
Python3 Examples