【Python】python对齐问题的总

发布时间:2019-08-16 10:27:24编辑:auto阅读(1586)

    Python的对齐方式很重要,对齐方式决定了函数或者判断条件的作用域。

    def print_circle(matrix,up_hang,up_lie,down_hang,down_lie):
        result=[]
        
        if up_lie==down_hang and down_hang==down_lie:
            result.append(matrix[up_hang][up_lie])
        elif up_lie==down_hang or up_lie==down_lie:
            if up_lie==down_hang:
                while up_lie <= down_lie:
                    result.append(matrix[up_hang][up_lie])
                    up_lie+=1
            elif up_lie==down_lie:
                while up_hang <=down_hang:
                    result.append(matrix[up_hang][up_lie])
                    up_hang+=1
    #  return result        #注意对齐方式,其决定了作用的区间范围,很关键     #<1>   
            return result                                                     #<2>

    如上面代码所示,开始的时候在<1>处添加的代码,所有结果总是出错。因为<1>没有缩进,其作用域已经不在if判断的作用域之内,其作用域是print_circle,所以这将导致函数直接返回result 而使该函数下面的代码无法其作用。后来改成<2>处的样子才编译成功。


    还有一个比较坑爹的地方就是Python对于多行注释的注释符来说也是需要对齐的!(之前吃了不少这方面的亏)。如下面的代码,我曾百思不得其解

    def print_circle(matrix,up_hang,up_lie,down_hang,down_lie):
        result=[]  
    '''
        if up_lie==down_hang or up_lie==down_lie:
            if up_lie==down_hang:
                while up_lie <= down_lie:
                    result.append(matrix[up_hang][up_lie])
                    up_lie+=1
            elif up_lie==down_lie:
                while up_hang <=down_hang:
                    result.append(matrix[up_hang][up_lie])
                    up_hang+=1
            return result
    '''           
        i=up_hang
        j=up_lie
        while j<down_lie:
           result.append(matrix[i][j])
           j+=1
        while i<down_hang:
           result.append(matrix[i][j])
           i+=1
        return result
    总是在加上使用'''多行注释符之后总是在"i=up_hang"行报错"unexpected indent"(非法缩进), 而只有把注释符去掉程序就没错了,很是郁闷。后来通过问过大神才知道原来Python还有注释符也需要缩进这一说!所以代码改为:

    def print_circle(matrix,up_hang,up_lie,down_hang,down_lie):
        result=[]  
        '''
        if up_lie==down_hang or up_lie==down_lie:
            if up_lie==down_hang:
                while up_lie <= down_lie:
                    result.append(matrix[up_hang][up_lie])
                    up_lie+=1
            elif up_lie==down_lie:
                while up_hang <=down_hang:
                    result.append(matrix[up_hang][up_lie])
                    up_hang+=1
            return result
        '''           
        i=up_hang
        j=up_lie
        while j<down_lie:
    终于这次没有报错了!



关键字