0

Write a function first_last6(nums) that takes a list of ints nums and returns True if 6 appears as either the first or last element in the list. The list will be of length 1 or more.

My code:

def first_last6(nums):
    if nums[0] or nums[-1] == "6":
        return True
    else:
        return False

It is not returning the right answer for this test:

print(first_last6([3, 2, 1]))

its suppose to be False, while it prints True.

Moh'd H
  • 247
  • 1
  • 4
  • 16
  • possible duplicate of [Why does \`a == b or c or d\` always evaluate to True?](http://stackoverflow.com/questions/20002503/why-does-a-b-or-c-or-d-always-evaluate-to-true) – inspectorG4dget Apr 23 '15 at 01:41
  • 1
    possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – Blckknght Apr 23 '15 at 01:46

2 Answers2

0

The original test checks if nums[0] is True or if nums[-1] is 6, to check if either is 6, should use:

if nums[0] == 6 or nums[-1] == 6:

niuer
  • 1,589
  • 2
  • 11
  • 14
0

Your code should be like this:

def first_last6(nums):
    if (nums[0] == 6) or (nums[-1] == 6):
        return True
    else:
        return False

In your original code, you check if the first element of the list evaluates to True (bool(1) is True in python). Instead, check if it is equal 6. And you check if the last element of the list is "6", instead of checking for 6. A test in the interactive interpreter:

>>> 6 == "6"
False
>>> 6 == 6
True
>>> bool(1)
True
TheEagle
  • 5,808
  • 3
  • 11
  • 39