简体   繁体   English

python程序无法与条件语句一起正常工作

[英]python program not working right with conditional statement

  def matrixADD(A,B):
    minilist=[]
    Z = []
    a=-1
    b=-1

The condition in while loop below is not being followed for some reason so the index goes out of range. 由于某些原因未遵循以下while循环中的条件,因此索引超出范围。 To fix it I had to add nested if statement below to break out of the loop. 为了解决这个问题,我必须在下面添加嵌套的if语句以打破循环。 It is very weird I was wondering why is it not working without the if statement? 我很奇怪,如果不使用if语句,为什么它不起作用?

    while len(A)!=len(Z):
        x=-1
        y=-1
        a=a+1
        b=b+1   

        if len(minilist)!=0:
            Z.append(minilist)
            if len(A)==len(Z):
                break
        minilist=[]    

        while len(A[a])!=len(minilist):
            for numbers in A[a]:
                x=x+1
                y=y+1            
                answer=(A[a][x]+B[b][y])
                minilist.append(answer)

    return Z

def main():
    #Test matrices
    A = [[2,4], [7,0], [6,3]]
    B = [[3,1], [-1,8], [-3, 3]]
Z=matrixADD(A,B)
    print("A + B:",Z)

main()

Hi guys. 嗨,大家好。 I wrote this program and it works just fine but I was having some trouble with 1 thing (indicated above) 我写了这个程序,它工作得很好,但是我在1件事上遇到了麻烦(如上所述)

Thanks for your input guys :) 感谢您的投入:)

It looks like you expected the loop to end as soon as the element was added that caused the list sizes to match. 看起来您希望循环会在添加导致列表大小匹配的元素后立即结束。 That's not how loops work. 那不是循环的工作方式。

The while loop condition is only tested at the start of each iteration of the loop. while循环条件仅while循环的每次迭代开始时进行测试。 If it stops being true in the middle of the loop, Python won't notice until the start of the next iteration, and only if it's still not true at that point. 如果它在循环的中间不再是真的,那么Python直到下一次迭代开始时才会注意到,并且只有那时还不是真的。 If you want the loop condition to be tested in the middle of the loop, you need to manually test it with something like your if statement, or you need to reorganize your loop. 如果要在循环的中间测试循环条件,则需要使用诸如if语句之类的工具手动对其进行测试,或者需要重新组织循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM