Reputation: 20916
I have the below piece that created few person objects and apply some methods on those objects.
class Person:
def __init__(self, name, age, pay=0, job=None):
self.name = name
self.age = age
self.pay = pay
self.job = job
def lastname(self):
return self.name.split()[-1]
def giveraise(self,percent):
return self.pay *= (1.0 + percent)
if __name__ == '__main__':
bob = Person('Bob Smith', 40, 30000, 'software')
sue = Person('Sue Jones', 30, 40000, 'hardware')
people = [bob,sue]
print(bob.lastname())
print(sue.giveraise(.10))
Once I run this program, this is the output--
Syntax Error: Invalid syntax
but when I run using the below code, I don't have any problem,
if __name__ == '__main__':
bob = Person('Bob Smith', 40, 30000, 'software')
sue = Person('Sue Jones', 30, 40000, 'hardware')
people = [bob,sue]
print(bob.lastname())
sue.giveraise(.10)
print(sue.pay)
What is the difference in two cases
Upvotes: 0
Views: 511
Reputation: 95385
I get the invalid syntax error even in the second version; I don't know how you got it to work, but you must have changed the giveraise
function. In Python, assignments, including those using mutators like *=
, are statements, not expressions; they have no value. Since they have no value, it doesn't make sense to return them from a function, hence the error.
Upvotes: 1
Reputation: 251598
*=
is an assignment, and assignment is a statement in Python, not an expression. Try:
self.pay *= (1.0 + percent)
return self.pay
Upvotes: 5
Reputation: 298562
Your problem is this function (I get an error in both cases):
def giveraise(self,percent):
return self.pay *= (1.0 + percent)
Change it to this and it will work:
def giveraise(self,percent):
self.pay *= (1.0 + percent)
return self.pay
I'm not entirely sure why Python throws a syntax error, but I do know that this works.
Upvotes: 0