tags:

views:

141

answers:

4

Hi all,

I have a function and I want it to execute. Does anyone know how to do this?

def a():

    a = 'print'
    print a
+14  A: 

The name of your function is a. It takes no arguments. So call it using a():

>>> def a():
...     a = 'print'
...     print a
... 
>>> a()
print

Note that you shadow the definition of a as a function within a itself, by defining a local variable with that same name. You may want to avoid that, as it may confuse you or other readers of your code. Also, it makes it impossible to apply recursion.

Anyway, in general, if f is some function object then you can call it by putting parentheses behind it, possibly containing some arguments. Example:

>>> def twice(text):
...     print text
...     print text
... 
>>> twice('the text I want to print twice')
the text I want to print twice
the text I want to print twice
Stephan202
+1  A: 

just write a() !

Antony Hatchkins
+1  A: 

I'm not sure I understood your question, but a simple function call goes as in

a()

of course, after the definition, so it would be

def a():

    a = 'print'
    print a

a()
Flávio Amieiro
+3  A: 

To do this you just use.

a()

If you want this for use inside the current file use:

if __name__ == '__main__': a()

And if you want to pass the variable a on for use in other functions use:

if __name__ == '__main__': b = a()

The 'b' being the variable and 'a' being the function you have defined.

So the whole function could look like this:

def a():

    b = 'print'
    print b

if __name__ == '__main__': b = a()
chrissygormley
The `if __name__ == '__main__':` is very confusing. Why do you write that so many times?
S.Lott
@ S.Lott - I have taken note of your advice and don't have it written everywhere now. It is entered once at the bottom of the file.
chrissygormley
After that the function `a` is shadowed by the variable `a`. Not good.
@lutz, I was keeping the variable names and function names the same as the question asked. Edited now
chrissygormley