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

I need to understand the above python code and why two return statement in 'for loop'. This is seriously confusing me.

Bill the Lizard
407k213 gold badges579 silver badges892 bronze badges
asked Oct 30, 2013 at 15:13

4 Answers 4

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.

answered Oct 30, 2013 at 15:21
Sign up to request clarification or add additional context in comments.

Comments

2

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.

answered Oct 30, 2013 at 15:20

Comments

1

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.

answered Oct 30, 2013 at 15:15

1 Comment

Correct, with one addition: i <= 4
0

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
answered Oct 30, 2013 at 15:21

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.