A good first question is, "what does 9 mean"?
If you have an array of numbers read from the command line, or from user input, then the "9" is likely the character "9", which is ASCII code 57, or unicode code point U+0039.
On the other hand, if you have actual integers in your array, then you are likely dealing with the integer value 9 (which would be an ASCII TAB character).
Second, you are too impatient!
Consider this input: [0, 0, 0, 0].
What happens?
def array_front9(nums):
for num in nums:
first4 = nums[0:4]
if num in first4 and num == 9:
return True
else:
return False
Well, nums is [0] * 4 because it was passed in.
Then num starts as 0.
Then first4 gets set to [0, 0, 0, 0].
Then num in first4 is certainly true,
but num == 9 is definitely not true
so the and is False.
Then the if fails and the else is executed
So your code executes a return False.
But that's wrong!
Because it happened while you were still looking at the very first value in the array. You never checked the other values, because you return False too soon.
You are permitted to do a pre-emptive return when you know the result -- when you find a 9 in the first 4 places. But if you are going to scan over each of the 4 places, you cannot return false until you finish your scanning.
Something like this:
for num in nums[0:4]:
if num == 9:
return True
# Note: this is after the for loop
return False