Graphics Reference
In-Depth Information
>>> def my_simple_function():
... print("Hello World!")
...
The Python interpreter will remember the definition, and you can call the function like this:
>>>
my_simple_function()
When you call the function, you will see that it outputs the words Hello World! just as if the
print statement had been called directly. In fact, the print statement is being called from within the
my_simple_function() function, which is defined using the def statement. Note also that as in the case
of control structures, the content of a function definition is delimited not with brackets but by left indentation.
It is also possible to define functions that take arguments. To do this, a variable representing the argument is
initialized in the function definition. When the function is called with a corresponding argument, the variable is
instantiated with the argument value:
>>> def my_simple_function(arg):
... print ("Hello World" * arg)
The output of this script is the repetition of the string Hello World five times, as shown here:
>>> my_simple_function(5)
Hello WorldHello WorldHello WorldHello WorldHello World
Variables initialized inside a function are local to that function and cannot be accessed from outside that
function.Ifyoutrytoaccessavariablethathasbeendefinedinsideafunctionoutsidethatfunction,Pythonwill
give an error.
Variables initialized outside the function are global and can be accessed from within the function:
>>> my_global_variable = "Hello!"
>>>
def my_simple_function():
... print (my_global_variable)
Then call:
>>>
my_simple_function()
This function will output the string Hello! . However, things get a bit more complicated when you
want to change the value of global variables in the context of a function. In this next example, the variable
my_global_variable beginswiththevalue "Hello!" butisreassignedthevalue "World!" inthecon-
text of the function.
>>> my_global_variable = "Hello!"
>>> def my_local_function():
... my_global_variable = "World!"
... print (my_global_variable)
When you call the function, the output is printed "World!" .
>>> my_local_function()
World!
>>> print (my_global_variable)
Hello!
Search WWH ::




Custom Search