代码打印错误答案

时间:2015-04-23 01:39:31

标签: python-3.x conditional-statements

编写一个函数first_last6(nums),它接受一个int列表并返回True,如果6作为列表中的第一个或最后一个元素出现。该列表的长度为1或更长。

我的代码:

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

没有为此测试返回正确的答案:

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

它假设为False,同时打印True

2 个答案:

答案 0 :(得分:0)

原始测试检查nums [0]是否为True或nums [-1]是否为6,检查是否为6,应使用:

如果nums [0] == 6或nums [-1] == 6:

答案 1 :(得分:0)

你的代码应该是这样的:

const blacklist = ['bad word 1', 'bad word 2', 'bad word 3']
    blacklist.forEach(word => {
        // 'word' represents an element inside of the array. 
        // Everytime the client is finished walking through an element, the value of 'word' changes to the next one!
        if (message.content.toLowerCase().includes(word)) message.delete() && message.author.send("Keep the use of Profanity out of our server!")
    })

在您的原始代码中,您检查列表的第一个元素的计算结果是否为 True(def first_last6(nums): if (nums[0] == 6) or (nums[-1] == 6): return True else: return False 在 python 中为 True)。相反,检查它是否等于 6。然后检查列表的最后一个元素是否为“6”,而不是检查 6。 交互式解释器中的测试:

bool(1)
相关问题