Loops 列表上的迭代

Loops 列表上的迭代,loops,python-3.x,iteration,Loops,Python 3.x,Iteration,我正在努力解决以下问题: 编写一个函数has23(nums),该函数接受长度为2的整数列表,如果它包含2或3,则返回True 霉菌代码: def has23(nums): for i in nums: if i == 2 or i == 3: return True return False 测试: has23([2,5]) 应为:True 获得:True has23([42,53]) 应为:False 获取:False has2

我正在努力解决以下问题:

编写一个函数has23(nums),该函数接受长度为2的整数列表,如果它包含
2
3
,则返回
True

霉菌代码:

def has23(nums):
    for i in nums:
        if i == 2 or i == 3:
            return True
        return False
测试:

has23([2,5])
应为:
True
获得:
True

has23([42,53])
应为:
False
获取:
False

has23([4,3])
应为:
True
得到:
**False**

has23([1,2])
应为:
True
得到:
**False**


我不知道为什么它会返回给我
False
,而在最后两次测试中它应该是
True

缩进很重要。您只进行了一次迭代,因为
return False
出现在循环中,导致循环提前退出。将其更改为:

def has23(nums):
    for i in nums:
        if i == 2 or i == 3:
            return True
    return False
正如@dawg所提到的,您不需要循环

def has23(nums):
    return 2 in nums or 3 in nums
//Python解释器由http://www.skulpt.org/
//我与之没有任何关系
功能输出(文本){
var mypre=document.getElementById(“输出”);
mypre.innerHTML=mypre.innerHTML+文本;
}
函数内置读取(x){
if(Sk.builtinFiles===未定义| | Sk.builtinFiles[“文件”][x]==未定义)
抛出“找不到文件:”“+x+””;
返回Sk.builtinFiles[“files”][x];
}
函数runit(){
var prog=document.getElementById(“yourcode”).value;
var mypre=document.getElementById(“输出”);
mypre.innerHTML='';
Sk.canvas=“mycanvas”;
Sk.pre=“输出”;
Sk.configure({
产出:出口,
阅读:内置阅读
});
试一试{
评估(Sk.importMainWithBody(“,false,prog));
}捕获(e){
警报(例如toString())
}
}

def has23(nums):
返回2个nums或3个nums
打印(has23([2,5]))
打印(has23([42,53]))
打印(has23([4,3]))
打印(has23([1,2]))


为无效的回滚表示歉意。不需要循环:
def has23(nums):返回2 in nums或3 in nums
或者,也许更好的是,
def has_ns(li,*ns):返回any(n in li表示n in ns)
然后使用变量测试元组调用:
has_ns([5,4,3],2,3)