Adding New Functions

After quick tour of Python basic built-in modules and functions it’s time to create your first functions. So now we’re working with user-defined functions. A function definition specifies the name of a new function and the sequence of statements that execute the when the function is called. Once the function is defined, we can reuse the function over and over throughout the program.
A simple example of creating new function is given below.
>>> def say_hello():
...     print 'Say Hello'
...
>>> say_hello()
Say Hello

Analysis of previous code:
def is a keyword that indicates that this is a function definition. The name of the function is print_lyrics. The rules for the function names are the same as for the variable names:
-          Letters,
-          Numbers and
-          Some punctuation marks are legal
Warning: first character can’t be a number.
-          You can’t use a keyword as the name of the function
-          Avoid having a variable and a function with the same name.
The empty parenthesis indicate that this function doesn’t take any arguments.
The first line of the function definition is called the header, the rest is called the body. The header has to end with a colon and the body has to be indented otherwise the Python interpreter will report Indentation error. Convention: Indentation is always four spaces. The body can contain any number of statements.
Defining a function creates a variable with the same name.
>>> print say_hello

>>> print type(say_hello)

Once you’ve defined a function, you can use it inside another function. For example, to repeat the previous function, we could write a function called repeat_see_hello
>>> def repeat_say_hello():
...     say_hello()
...     say_hello()
...
>>> repeat_say_hello()
Say Hello
Say Hello

Nema komentara:

Objavi komentar