0

I would like to define my function f(x,a) in which the value of 'a' changes, so that every time I call f(x,a), the value of 'a' will be different. So far the following code serve the purpose:

a=0
def f(x):
    global a
    a=a+1
    return a+x**2

In this case, everytime f(x) is called, the value of a is changed as well. I am wondering if there are any other ways to realize the results? Thank you.

1
  • what is expected input and output for this function? Your problem statement is unclear Commented Sep 2, 2015 at 5:07

2 Answers 2

2

You can take advantage of using a mutable default value (normally this is a gotcha that trips people up, I never thought I would use it on purpose):

def f(x, a={"value":0}):
    a["value"] += 1
    #Do other stuff

But since you are trying to encapsulate a piece of functionality with some data you would probably be better off creating a new class:

class Foo:
    def __init__(self):
        self.a = 0

    def f(self, x):
        self.a += 1
        return x + self.a

foo = Foo()
foo.f(0) # 1
foo.f(0) # 2
Sign up to request clarification or add additional context in comments.

Comments

0

You should pass a to f each time you call it instead of using a as a global variable. Something like

def f(x, a):
    # your code

A full example

def f(x, a):
    a = a + 1
    return a + x ** 2

if __name__ == "__main__":
    x = 1
    a = 2
    print f(x, a)
    # output 4

4 Comments

if I do this, it will give me the following error: "SyntaxError: name 'a' is local and global"
if you call the function multiple times, it alway gives you the output 4, while I want to have 4,5,6,7,8...
You need to update a and pass it to f. e.g. a += 1, then call f(x, a). I would suggest you learn some basics about Python function.
@ zyxue: I need to let the function f update the value of 'a' everytime I call it, not by user. It is the whole point of the question... never mind...

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.