为什么这段代码没有触发ValueError?

时间:2014-11-14 08:14:27

标签: python

当“chunk_size”为零或大于“序列”的长度时,我试图触发错误。当我使用chunk_size为4调用此函数,并且序列等于“123”时,它不会抛出错误。我做错了什么?

def slices(sequence,chunk_size):
    position=0
    mini_list=[]
    answer=[]

    while chunk_size<=len(sequence) and chunk_size>0:

        try:
            for char in sequence:
                if len(sequence[position:position+chunk_size])==chunk_size:
                    mini_seq = sequence[position:position+chunk_size]
                    for digit in mini_seq:
                        mini_list.append(int(digit))
                    answer.append(mini_list)
                    mini_list=[]
                    position+=1
            return answer
            break

        except ValueError:
            print "Oops!  That was no valid number.  Try again..."

print slices("012", 4)

1 个答案:

答案 0 :(得分:1)

它不会抛出ValueError,因为你在while块中引发了它,只有在chunk_size < 0的所需条件为> len(str)或{{1}时才输入while块不满足。

因此,要解决此问题,请将代码中的错误提升部分移出while循环。实际上,您在while中放置条件是错误的,而是将其转换为if语句。此外,在return陈述之前的休息时间没有任何意义。

所以你的代码变成了

while True:
    try:
        if chunk_size<=len(sequence) and chunk_size>0:
            for char in sequence:
                if len(sequence[position:position+chunk_size])==chunk_size:
                    mini_seq = sequence[position:position+chunk_size]
                    for digit in mini_seq:
                        mini_list.append(int(digit))
                    answer.append(mini_list)
                    mini_list=[]
                    position+=1
            return answer
        else:
            raise ValueError       
    except ValueError:
        print "Oops!  That was no valid number.  Try again..."

此外,不是引发错误来验证数据是否格式正确,而是可以取消引发异常本身,并使用简单的if-else块实现相同的结果:

while True:
    if chunk_size<=len(sequence) and chunk_size>0:
        for char in sequence:
            if len(sequence[position:position+chunk_size])==chunk_size:
                mini_seq = sequence[position:position+chunk_size]
                for digit in mini_seq:
                    mini_list.append(int(digit))
                answer.append(mini_list)
                mini_list=[]
                position+=1
        return answer
    else:
        print "Oops!  That was no valid number.  Try again..."