QUESTION IMAGE
Question
6 essay 10 points how would you write a function that takes a list of numbers and returns a new list containing only the even numbers?
Step1: Define the function
Define a function, say get_even, that takes a list nums as a parameter.
def get_even(nums):
Step2: Initialize an empty list
Create an empty list to store the even numbers.
result = []
Step3: Iterate through the input list
Loop through each number in the input list nums.
for num in nums:
Step4: Check for even numbers
Use the modulus operator % to check if a number is divisible by 2 (i.e., even). If num % 2 == 0, append it to the result list.
if num % 2 == 0:
result.append(num)
Step5: Return the result
After processing all numbers in the input list, return the result list containing only the even numbers.
return resultSnap & solve any problem in the app
Get step-by-step solutions on Sovi AI
Photo-based solutions with guided steps
Explore more problems and detailed explanations
def get_even(nums):
result = []
for num in nums:
if num % 2 == 0:
result.append(num)
return result
(You can also use a list comprehension: def get_even(nums): return [num for num in nums if num % 2 == 0])