python代码的语法错误

时间:2012-09-08 20:18:45

标签: python syntax

我班上有这个功能:

 def removeUserFromSessionDatabase(self, user):
      if user in self.users:
         for k in self.users.keys():
            if k == user:
               del self.users[k]
               print("Removed")

            else:
               print("user does not exist")
      else:
         print "soemthing"

现在我总是在最后else收到错误消息:SyntaxError: invalid syntax 应该在哪里工作。用户是这里的字典,没有其他方法。为什么我会收到此语法错误?

2 个答案:

答案 0 :(得分:3)

您的缩进可能不正确,很可能是由标签引起的。运行python -tt scriptname.py进行检查。

您的代码中没有语法错误会导致此特定的异常,而不会出现在您提供给我们的代码中。

答案 1 :(得分:3)

你可以通过

简化这个
def removeUserFromSessionDatabase(self, user):
      return self.users.pop(user,False)

def removeUserFromSessionDatabase(self, user):
      if self.users.pop(user,False):
         print "%s was deleted from group"
      else:
         print "%s is not in group"

def removeUserFromSessionDatabase(self, user):
      userData = self.users.pop(user,False):
      if userData: 
          #do Something
      else:
          #do something else

或最后

def removeUserFromSessionDatabase(self, user):
      try:userData = self.users.pop(user):
      except KeyError:
          #user does not exist in dict
          pass
      print "Deleted {0}:{1} From List".format((user,userData))

显然(per denlan,我相信)del可以使用

def removeUserFromSessionDatabase(self, user):
      try:
         del self.users[user]
         print "Removed user"
      except KeyError:  
         print "User does not exist" 


def alt_removeUserFromSessionDatabase(self, user):
      if user in self.users
         del self.users[user]
         print "Removed user"
      else:  
         print "User does not exist"