Let's analyze your solution with the entry: [5, 3]
When i = 0
then num[i]
is 5
, so the if nums[i] == 2 or nums[i] == 3:
is false so the else will be executed, and the else returns False, and remember that when called return the function is finished, that prevents it from being analyzed when i = 1
. For the above you get that answer.
On the other hand, do not use:
for i in range(len(nums)):
but you can use the following:
for num in nums:
which is more readable.
A possible solution using the logic of iterating can be the following:
def has23(nums):
for num in nums:
if num == 2 or num ==3:
return True
return False
That is, if at least num
is 2
or is 3
is returned otherwise iterates, and if nothing is returned in the loop False returns at the end.
But python has other instructions such as any
and all
, the first one returns True
if in the list there is at least one True and in other cases False, and the second only returns True if all are True. And also the instruction in
that used in an if returns True
if an element is in an iterable one. Using the above we obtain:
def has23(nums):
return any(val in nums for val in (2, 3))