在Python中格式化代码时的错误

时间:2015-10-11 12:25:52

标签: python formatting indentation

我知道这可能是一个非常简单的问题,但我的功能格式化问题。我得到了很多意想不到的缩进'以及意外的令牌'我一直在尝试正确地格式化函数,但我不知道为什么这些错误会继续出现。这是我的功能:

def stringCheck(stringForCheck, letterOrNumber):

    valid = True

    x = 0

    a = int(ord(stringForCheck)

    length = len(stringForCheck)

        if LetterOrNumber == 'Letter':

            lowerBoundary = 65

            upperBoundary = 90

        elif LetterOrNumber == 'Number':

            lowerBoundary = 48

            upperBoundary = 57

        while valid == True and x < length:

            if a < lowerBoundary or a > upperBoundary:

                valid = False

            else:

                valid = True

        x = x + 1

    stringCheck = valid



stringCheck('2','Number')

2 个答案:

答案 0 :(得分:3)

  1. 删除不必要的空行
  2. 您在这里错过了一个结束括号:a = int(ord(stringForCheck)
  3. if LetterOrNumber == 'Letter':行到您的while循环,这些行的缩进级别太多了。
  4. 修复代码后,应该看起来像这样:

    def stringCheck(stringForCheck, letterOrNumber):
        valid = True
        x = 0
        a = int(ord(stringForCheck))
        length = len(stringForCheck)
    
        if LetterOrNumber == 'Letter':
            lowerBoundary = 65
            upperBoundary = 90
        elif LetterOrNumber == 'Number':
            lowerBoundary = 48
            upperBoundary = 57
    
        while valid is True and x < length:
            if a < lowerBoundary or a > upperBoundary:
                valid = False
            else:
                valid = True
    
        x = x + 1
        stringCheck = valid
    
    stringCheck('2', 'Number')
    

答案 1 :(得分:0)

尝试在

行后添加一个小括号
    a = int(ord(stringForCheck))