如果在Python中出现else语句错误

时间:2016-02-12 15:57:02

标签: python regex function if-statement

我一直在第一个elif上得到错误语法无效。我很确定语法是正确的,但我不知道为什么我一直收到这个错误。

def make_tracker(self):
        self.region = re.search(r'CLI Command: \'show system information\'',line)
        if self.region:
          self.region = "show system information"
          return self.region

        self.region = re.search(r'CLI Command: \'show card detail\'',line)
        elif self.region:
          #The error is on the elif statement it self ^
          self.region = "CPM or IOM"
          return self.region

        self.region = re.search(r'CLI Command: \'show mda detail\'',line)
        elif self.region:
          self.region = "MDA"

        else:
          print"Could not Enter any of the regions"

3 个答案:

答案 0 :(得分:2)

我认为这就是你想要的,用elif替换if

def make_tracker(self):
    self.region = re.search(r'CLI Command: \'show system information\'',line)
    if self.region:
      self.region = "show system information"
      return self.region

    self.region = re.search(r'CLI Command: \'show card detail\'',line)
    if self.region:
      #The error is on the elif statement it self ^
      self.region = "CPM or IOM"
      return self.region

    self.region = re.search(r'CLI Command: \'show mda detail\'',line)
    if self.region:
      self.region = "MDA"
      return self.region

    print"Could not Enter any of the regions"

现在不需要else语句,但您必须在第三个return上添加if,否则最后的print将被执行。

有关if.. else ..声明read the tutorial

的详细信息

答案 1 :(得分:1)

正如其他人所说,问题在于if和elif语句之间的表达式。要保留当前功能,您可以将自身区域变量更改为

def make_tracker(self):
    self.regionSystem = re.search(r'CLI Command: \'show system information\'',line)
    self.regionCard = re.search(r'CLI Command: \'show card detail\'',line)
    self.regionMDA = re.search(r'CLI Command: \'show mda detail\'',line)

    if self.regionSystem:
      self.region = "show system information"
      return self.region

    elif self.regionCard:
      #The error is on the elif statement it self ^
      self.region = "CPM or IOM"
      return self.region

    elif self.regionMDA:
      self.region = "MDA"

    else:
      print"Could not Enter any of the regions"

答案 2 :(得分:1)

在使用文字字符串时,为什么要使用正则表达式呢?

def make_tracker(self):
    if "CLI Command: 'show system information'" in line:
        self.region = "show system information"
        return self.region

    elif "CLI Command: 'show card detail'" in line:
        self.region = "CPM or IOM"
        return self.region

    elif "CLI Command: 'show mda detail'" in line:
        self.region = "MDA"

    else:
        print"Could not Enter any of the regions"