首页 > 解决方案 > End of line error appearing in the end of the conditional statement

问题描述

I am trying out some conditional statements but I am getting indentation error at the end of the statement. I am trying to delete the last condition but the error appear again. How to resolve this.

import numpy as np
new_sobel = np.random.randint(100, size=(100,100))
theta= np.random.randint(10, size=(100,100))


MM, NN = new_sobel.shape
Z = np.zeros((MM,NN), dtype=np.int32)
angle = theta * 180. / np.pi
angle[angle < 0] += 180

for i in range(1,MM-1):
    for j in range(1,NN-1):
        try:
            q=255;
            r=255;
            if (0 <= angle[i,j] < 22.5) or (157.5 <= angle[i,j] <= 180):
                        q = new_sobel[i, j+1]
                        r = new_sobel[i, j-1]
                    
            elif (22.5 <= angle[i,j] < 67.5):
                        q = new_sobel[i+1, j-1]
                        r = new_sobel[i-1, j+1]
                    
            elif (67.5 <= angle[i,j] < 112.5):
                        q = new_sobel[i+1, j]
                        r = new_sobel[i-1, j]
                    
            elif (112.5 <= angle[i,j] < 157.5):
                        q = new_sobel[i-1, j-1]
                        r = new_sobel[i+1, j+1]
        
            if (new_sobel[i,j] >= q) and (new_sobel[i,j] >= r):
                        Z[i,j] = new_sobel[i,j]
            else:
                        Z[i,j] = 0

标签: pythonpython-3.xif-statement

解决方案


excepttry正如@Lcj 所述,您的块中缺少它,因为它预计excepttry块的末尾。

另外,要回答您对以下功能的评论:

只要您知道代码在哪里以及如何中断,或者您知道它无法工作的用例,就可以使用它,因此您定义 try-except 块并将您的那部分代码放在try块中以及您需要什么一旦您的代码中断是您放入except块中的内容,请立即执行。

通常,它对于记录用于调试代码的错误很有用。

例如。玩具示例:

try :   
    for i in range(0, 10):
        print(c/i)  # c can be any constant
except :
    print("ZeroDivisonError : not possible to divide any number by zero !") # can do anything here once it breaks and comes to this section 

因此,循环变量“i”在开始时仅达到 0,并且我们知道 c/0 无法定义,因此我们将错误与任何其他信息一起打印。


推荐阅读