0

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

2
  • Where do you receive the SyntaxError? Please update your question with the full Traceback of the error message. Commented Jun 3, 2012 at 2:35
  • From a design standpoint, unless you have a very good reason for doing so, giveraise() shouldn't return a value. "Give raise" implies you are acting on the data in the class instance. It would make more sense to have a separate property accessor for post-raise pay. Commented Jun 3, 2012 at 2:41

3 Answers 3

5

*= is an assignment, and assignment is a statement in Python, not an expression. Try:

self.pay *= (1.0 + percent)
return self.pay
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

1 Comment

Assignments in Python do not return the value, which is why you can't do this: if((line = myFile.readline())): #stuff here.... This type of code works in C, but not in Python. This is part of the plan for Python to be easily readable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.