Discuss / Python / 交作业

交作业

Topic source

辰川时羽

#1 Created at ... [Delete] [Delete and Lock User]
def findMinAndMax(L):
    if L:
        min = max = L[0]
        for i in L:
            if i < min:
                min = i
            if i > max:
                max = i
        return (min, max)
    else:
        return (None, None)

PrimeDly

#2 Created at ... [Delete] [Delete and Lock User]

“if L: ”这里我写成“ if L == True: ”可以运行,但是写成“if L !=False: ”就报错IndexError: list index out of range,请问这是为什么呢?

woshi詹森

#3 Created at ... [Delete] [Delete and Lock User]

@PrimeDly,你用前面的L==True运行也是测试失败啊,list怎么可以和bool型比较都是不成立的,之所报错是因为第一个分支检测的就是空list,list!=False这个成立并不代表他就是True了,list中没有元素,但是初始化min,max的时候访问了list,此时list为空,肯定会报越界访问的错误啊。


  • 1

Reply