Placing return false

Question:

I am very new to coding, two weeks in.
So I do apologize if this is a very silly question.

I have been trying to complete the following codingbat problem:

Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4.

Why does the below code not return the correct answer?

def array_front9(nums):
  if len(nums)>4:
    count = 4
  else:
    count = len(nums)

  for i in range(0,count):
    if nums[i]==9:
      return True
    else:  
      return False

If the return False is placed on a new line and not in the loop it works.

Can someone please explain this to me.

Asked By: Help_Steve_Code

||

Answers:

I think you need:

def array_front9(nums):
    count = 4
    if len(nums)<4:
        count = len(nums)
    if 9 in nums[:count]:
        return True
    return False

What’s wrong with your code

if nums[i]==9:
      return True
else:  
      return False

In above lines you’re just checking for 1st value if it is 9 then it returns True else False

Answered By: Sociopath

On the first iteration of the loop, the loop checks if nums[0] is 9 and always returns either True or False; you’re not giving any chance for the rest of the elements to be inspected. You should only return True if the element being inspected is 9, and return False only when this fails for the first four elements, i.e. outside the loop.

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

The problem in your code is if the first number in your list is not 9 then the loop will stop and function execution will stop it’s because of return False in else condition.

def array_front9(nums):
  count = [len(nums), 4][len(nums) > 5]
  for i in range(count):
    if nums[i] == 9:
      return True
  return False
Answered By: deadshot
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.