46.0k views
5 votes
For every question, show all the necessary work to get to the answer. Explain!

3.) Write a Python function to print the even numbers from any given list. Make sure to include the code and output. Hint: Make use of append() function.
For example:

Sample List: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Expected Output: [2, 4, 6, 8]

User Dicle
by
7.0k points

1 Answer

0 votes

Final answer:

To print the even numbers from a given list in Python, you can define a function that takes the list as input. Within the function, you can iterate through each element and append the even numbers to a new list. Finally, you can return the list of even numbers as the output.

Step-by-step explanation:

To print the even numbers from a given list in Python, you can define a function that takes the list as input. Within the function, you can create an empty list to store the even numbers. Then, you can iterate through each element in the input list and check if it is divisible by 2 (i.e., an even number). If it is, you can append it to the empty list using the append() function. Finally, you can return the list of even numbers as the output.

Here is the code:

def print_even_numbers(lst):
even_numbers = []
for num in lst:
if num % 2 == 0:
even_numbers.append(num)
return even_numbers

sample_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers_output = print_even_numbers(sample_list)
print(even_numbers_output)

The output for the given sample list would be:

[2, 4, 6, 8]

User Kixx
by
7.7k points