我的代码部分被跳过 (python 3)

section of my code is being skipped (python 3)

我的程序应该检查矩阵是否为幻方。但是它会跳过 "adding the diagonals" 并检查是否所有数字 (1-16) 都在 table.

ROWS=4
COLUMNS=4

def main():

    tbl=[]
    numChecktbl=[]
    for i in range (ROWS):
        tbl.append([])
        for j in range (COLUMNS):
           userinput=int(input("Enter a value for location (%d,%d): " %(i,j)))
           tbl[i].append(userinput)
           numChecktbl.append(userinput)
    for i in range(ROWS):
        for j in range(COLUMNS):
           print("%3d" %tbl[i][j], end='') 
        print()
    if (totSumRowsColumns(ROWS,COLUMNS,tbl)and totSumDiagonals(ROWS,COLUMNS,tbl)
                     and numInMatrix(numChecktbl)):
        print("It is a magic square")
    else:
        print("It is not a magic square")

def totSumRowsColumns(ROWS,COLUMNS,tbl):
    for i in range (ROWS):
        totalrow=0
        totalColumn=0
        for j in range (COLUMNS):
            totalColumn+=tbl[j][i]
            totalrow=totalrow+tbl[i][j]
        if (totalrow != 34!=totalColumn):
            return False
        return True
def totSumDiagonals(ROWS,COLUMNS,tbl):    
    totDiag1=0  
    totDiag2=0
    for i in range (ROWS): 
        for j in range (COLUMNS):
            totDiag1=tbl[0][3]+tbl[1][2]+tbl[2][1]+tbl[3][0]
            if i==j:
               totDiag2+=tbl[i][j] 
    if (totDiag1!=totDiag2!=34):
        return False
    return True

def numInMatrix(numChecktbl):     
    for i in range(1,17):
        if i not in numChecktbl:
            return False
        return True
main()

由于您的 if 语句包含多个条件,这些条件都需要全部为真,因此一旦一个条件为假,它就会转移到另一个条件。

当您的输入有效时,所有功能和检查运行。但是,当您的输入不是幻方时,totSumRowsColumns returns false 并且检查停止。