2015-10-09 57 views
0

使用函數print_even_values輸入整數列表並打印列表中的每個偶數。調用print_even_values([2,8,1,9,0,19,24])將產生此輸出在外殼窗口:函數定義:從整數列表中返回偶數的列表

我的做法是:

def print_even_numbers(n:list) -> list: 

'''Return a list of even numbers given a list of integers''' 
for x in list: 
    if x % 2 == 0: 
     return(x) 
assert print_even_numbers([2, 4, 2, 4, 5, 6]) == [2, 4, 2, 4, 6] 

assert print_even_numbers([4, 1, 3, 2, 5, 9]) == [4, 2] 

,但出現錯誤。另外,如何讓我的輸出與問題類似? (即

[2, 4, 2, 4, 6] 

與(單獨行)

2 
4 
2 
4 
6 
+0

格式化結果 – Phani

回答

0

我認爲這個問題是你是返回一個數字時爲偶數,而不是返回偶數的列表,你應該存儲編號爲偶數然後返回列表:

def print_even_numbers(number_list): 
    even_numbers = [] # define the empty list of even numbers 
    for number in number_list: 
     if number % 2 == 0: # check if number is even 
      even_numbers.append(number) # if it is, store it 
     return even_numbers # Return the list of even numbers