2013-10-30 175 views
1
def array_front9(nums): 
    end = len(nums) 
    if end > 4: 
     end = 4 

    for i in range(end): 
     if nums[i]==9: 
      return True 
    return False 

我需要理解上面的python代码以及为什么两个return语句在for循环中。这让我非常困惑。Python代码解释需要

回答

2

让我解释一下:

def array_front9(nums): # Define the function "array_front9" 
    end = len(nums)  # Get the length of "nums" and put it in the variable "end" 
    if end > 4:   # If "end" is greater than 4... 
     end = 4   # ...reset "end" to 4 

    for i in range(end): # This iterates through each number contained in the range of "end", placing it in the variable "i" 
     if nums[i]==9: # If the "i" index of "nums" is 9... 
      return True # ...return True because we found what we were looking for 
    return False   # If we have got here, return False because we didn't find what we were looking for 

有万一两个返回语句循环落空(结束),而不返回True

1

第二个返回不在for循环中。它提供了一个返回值False如果循环“跌破”,当nums[i]没有在该范围内等于9。

至少,这是你如何缩进它。

+1

正确多了一条:我<= 4 – Mailerdaimon

4

这可能因为这被重写简单得多(即,“更Python”):

def array_front9(nums): 
    return 9 in nums[:4] 

的代码的第一个一半的循环限制设定为前4个元素,或更小,如果数组nums更短。 nums[:4]通过创建仅包含最多4个元素的副本来做基本相同的事情。

循环正在检查循环中是否找到了元素9。如果找到,则立即返回True。如果它从未找到,则循环将结束,而返回False。这是in运算符的一种简单形式,该运算符是该语言的一个内置部分。

0

你可以改写这个更清晰使用列表分片:

def array_front9(nums): 
    sublist = nums[:4] 

    if 9 in sublist: 
     return True 
    else: 
     return False