Space Rocker
Space Rocker

Reputation: 787

syntax error with python code

I have this function in my class:

 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"

now I always get error at this last else with message: SyntaxError: invalid syntax where as it should work. users is a dictionary here and there is no other method. Why am I getting this syntax error?

Upvotes: 0

Views: 1675

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113988

you can simplify this alot by

def removeUserFromSessionDatabase(self, user):
      return self.users.pop(user,False)

or

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

or

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

or lastly

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))

apparently (per denlan and I believe it) del is fine to use

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" 

Upvotes: 3

Martijn Pieters
Martijn Pieters

Reputation: 1121972

Your indentation could be incorrect, most likely caused by tabs. Run python -tt scriptname.py to check.

There is otherwise no syntax error in your code that would cause this specific exception, not in the code you've given us.

Upvotes: 3

Related Questions