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
I need to understand the above python code and why two return statement in 'for loop'. This is seriously confusing me.
4 Answers 4
This could be rewritten much simpler (that is, "more pythonic") as this:
def array_front9(nums):
return 9 in nums[:4]
The first half of the code is setting the loop limit to the first 4 elements, or less if the array nums is shorter. nums[:4] does essentially the same thing by creating a copy that only contains up to the first 4 elements.
The loop is checking to see if the element 9 is found in the loop. If found, it returns immediately with True. If it's never found, the loop will end and False is returned instead. This is a longhand form of the in operator, a built-in part of the language.
Comments
Let me explain:
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
There are two return-statements in case the loop falls through (finishes) without returning True.
Comments
The second return isn't in the for loop. It provides a return value of False if the loop "falls through", when none of nums[i] equal 9 in that range.
At least, that's how you've indented it.
1 Comment
You could rewrite this to be more clear using list slicing:
def array_front9(nums):
sublist = nums[:4]
if 9 in sublist:
return True
else:
return False