Translate in Your language

Tuesday, 7 April 2020

Learning Python Part-23: Python Functions

In Python, function is a group of statements that perform a specific task. As we discussed about modules, how they help manage the code, Functions help break our program into smaller and modular chunks.


As our program grows larger and larger, functions make it more organized and manageable.
Furthermore, it avoids repetition and makes code reusable.


Syntax:

def function_name(parameters):
         """docstring"""
         statement(s)
  • Keyword def marks the start of function header.
  • A name of function to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  • Parameters (arguments) through which we pass values to a function. They are optional.
  • A colon (:) to mark the end of function header.
  • Optional documentation string (docstring) to describe what the function does.
  • One or more python statements that make up the function body. Statements must have same indentation level (usually 4 spaces or a tabs).
  • An optional return statement to return a value from the function.
  • Example:
def greet(name):
      print("Hello, " + name + ". Good morning!")



Once we have defined a function, we can call it from another function, program or even the Python prompt.  To call a function we simply type the function name with appropriate parameters.

greet('Abhijeet')

Output:

Hello, Abhijeet. Good morning!

Docstring in Python:

Docstring which we referred earlier in an example,  is short for documentation string. Triple quotes are used while writing docstrings. It is a string which comes as the first statement in a module, function, class, or method definition. Documentation string (docstring) is used to describe what the function does.

def double(num):

       """Function to double the value"""
       return 2*num



Docstring is available as the attribute __doc__ of the function. Issue the following code in shell once you run the above program.

>>> print(double.__doc__)

Output:- 

Function to double the value

Types of Functions:

Basically, we can divide functions into the following two types:

  • Built-in functions - Functions that are built-in to Python.
  • User-defined functions - Functions defined by the users.
The return statement:


  • The return statement is used to exit a function and go back to the place from where it was called.
  • Syntax of return
return [expression_list]
  • Example:
num = -8
def positive_value(num):
      if num >= 0:
          return "{} is a positive number".format(num)
      else:
          return "{} is a negative number".format(num)

print(positive_value(num))


Python Function Arguments:

  • Arguments
  • Variable Function Arguments
    • Python Default Arguments
    • Python Keyword Arguments
    • Python Arbitrary Arguments
Arguments:
  • Earlier we talked about defining a function with arguments and calling it. 
  • We call function with arguments, so it runs smoothly without any error.
  • If we call it with different type or without arguments, the interpreter will display error. 
Example:

def greet(name, msg):
      print("Hello", name + ', ' + msg)

greet("Eddy","Good morning!")              # Correct way of calling it since this () has 2 args

greet()                                  # Incorrect way

greet(“Eddy”)                      # Incorrect way

Variable Function Arguments:

Until now, we talked about functions with fixed number of arguments. In Python, function can take variable number of arguments.

Three different types are described below.
  • Python Default Arguments
  • Python Keyword Arguments
  • Python Arbitrary Arguments
Python Default Arguments:

Function arguments can have default values in Python. We can provide a default value to an argument by using the assignment operator (=).  Default argument is used in case not provided while calling function as in example below. If passed while calling function, default argument is ignored.

Example:

def greetings(name, msg = "Good morning!"):
      print("Hello",name + ', ' + msg)

greet("Eddy")
greet("Eddy","How do you do?")

Python Keyword Arguments:
Python allows functions to be called using keyword arguments. When we call a function with some values, these values get assigned to the arguments according to their position.
In below function greet(), when we called it as greet("Eddy","How do you do?"), the value "Eddy" gets assigned to the argument name and similarly "How do you do?" to msg.

def greet(name, msg = "Good morning!"):
      print("Hello",name + ', ' + msg)

greet("Eddy","How do you do?")


#Few more ways to call this ()
greet("Eddy", msg = "How do you do?")
greet(msg = "How do you do?", name = "Eddy")
greet(name = "Eddy", msg = "How do you do?")

Python Arbitrary Arguments:
Sometimes, we do not know in advance the number of arguments that will be passed into a function. To handle this situation, Python allows function calls with arbitrary number of arguments. In the function definition we use an asterisk (*) before the parameter name to denote this kind of argument.

Example:

def greet(*names):
      for name in names:
           print("Hello",name)

greet("Eddy", "Abhijeet", "Priyanka", "Jonathan")


Output:

Hello Eddy
Hello Abhijeet
Hello Priyanka   
Hello Jonathan





No comments:

Post a comment

Followers

Popular Posts This Week