Skip to main content

Learn Python : Python Functions

 Python Functions


In Python, function is a group of related statements that perform a specific task. 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 of Function

def function_name(parameters):
	"""docstring"""
	statement(s)
Above shown is a function definition which consists of following components.
  1. Keyword def marks the start of function header.
  2. A function name to uniquely identify it. Function naming follows the same rules of writing identifiers in Python.
  3. Parameters (arguments) through which we pass values to a function. They are optional.
  4. A colon (:) to mark the end of function header.
  5. Optional documentation string (docstring) to describe what the function does.
  6. One or more valid python statements that make up the function body. Statements must have same indentation level (usually 4 spaces).
  7. An optional return statement to return a value from the function.

Example of a function

def greet(name):
	"""This function greets to
	the person passed in as
	parameter"""
	print("Hello, " + name + ". Good morning!")



Function Call

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. Try running the following into the Python shell to see the output.
>>> greet('Paul')
Hello, Paul. Good morning!

Docstring

The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does. Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code. In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of the function. For example: Try running the following into the Python shell to see the output.
>>> print(greet.__doc__)
This function greets to
	the person passed into the
	name parameter

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]
This statement can contain expression which gets evaluated and the value is returned. If there is no expression in the statement or the return statement itself is not present inside a function, then the function will return the None object.for example
>>> print(greet("May"))
Hello, May. Good morning!
None
Here, None is the returned value.

Example of return

def absolute_value(num):
	"""This function returns the absolute
	value of the entered number"""

	if num >= 0:
		return num
	else:
		return -num

# Output: 2
print(absolute_value(2))

# Output: 4
print(absolute_value(-4))
output
2
4

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function is not visible from outside. Hence, they have a local scope. Lifetime of a variable is the period throughout which the variable exits in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls. Here is an example to illustrate the scope of a variable inside a function.
def my_func():
	x = 10
	print("Value inside function:",x)

x = 20
my_func()
print("Value outside function:",x)
output
Value inside function: 10
Value outside function: 20
Here, we can see that the value of x is 20 initially. Even though the function my_func() changed the value of x to 10, it did not effect the value outside the function. This is because the variable x inside the function is different (local to the function) from the one outside. Although they have same names, they are two different variables with different scope. On the other hand, variables outside of the function are visible from inside. They have a global scope. We can read these values from inside the function but cannot change (write) them. In order to modify the value of variables outside the function, they must be declared as global variables using the keyword global.

Types of Functions

Basically, we can divide functions into the following two types: Built-in functions - Functions that are built into Python. User-defined functions - Functions defined by the users themselves.

Python Function Arguments

In user-defined function topic, we learned about defining a function and calling it. Otherwise, the function call will result into an error. Here is an example.
def greet(name,msg):
   """This function greets to
   the person with the provided message"""
   print("Hello",name + ', ' + msg)

greet("Monica","Good morning!")
Output

Hello Monica, Good morning!

Here, the function greet() has two parameters. Since, we have called this function with two arguments, it runs smoothly and we do not get any error. If we call it with different number of arguments, the interpreter will complain. Below is a call to this function with one and no arguments along with their respective error messages.
>>> greet("Monica")    # only one argument
TypeError: greet() missing 1 required positional argument: 'msg'

>>> greet()    # no arguments
TypeError: greet() missing 2 required positional arguments: 'name' and 'msg'

Variable Function Arguments

Up until now functions had fixed number of arguments. In Python there are other ways to define a function which can take variable number of arguments. Three different forms of this type are described below.

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 (=). Here is an example.
def greet(name, msg = "Good morning!"):
   """
   This function greets to
   the person with the
   provided message.

   If message is not provided,
   it defaults to "Good
   morning!"
   """

   print("Hello",name + ', ' + msg)

greet("Kate")
greet("Bruce","How do you do?")
output
Hello Kate, Good morning!
Hello Bruce, How do you do?
In this function, the parameter name does not have a default value and is required (mandatory) during a call. On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional during a call. If a value is provided, it will overwrite the default value. Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values. This means to say, non-default arguments cannot follow default arguments. For example, if we had defined the function header above as:
def greet(msg = "Good morning!", name):
We would get an error as:
SyntaxError: non-default argument follows default argument

Python Keyword Arguments

When we call a function with some values, these values get assigned to the arguments according to their position. For example, in the above function greet(), when we called it as greet("Bruce","How do you do?"), the value "Bruce" gets assigned to the argument name and similarly "How do you do?" to msg. Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result.
>>> # 2 keyword arguments
>>> greet(name = "Bruce",msg = "How do you do?")

>>> # 2 keyword arguments (out of order)
>>> greet(msg = "How do you do?",name = "Bruce") 

>>> # 1 positional, 1 keyword argument
>>> greet("Bruce",msg = "How do you do?")  
As we can see, we can mix positional arguments with keyword arguments during a function call. But we must keep in mind that keyword arguments must follow positional arguments. Having a positional argument after keyword arguments will result into errors. For example the function call as follows:
greet(name="Bruce","How do you do?")
Will result into error as:
SyntaxError: non-keyword arg after keyword arg

Ref: Learn python:Python tutorial app

App by Avrram piperidas

Most Popular Course:Data Science of Harvard, MIT, IBM.... 

John Academy: 97% Off on Popular Online Courses



Amazon Best Seller in Baby Products

Python Arbitrary Arguments

Sometimes, we do not know in advance the number of arguments that will be passed into a function.Python allows us to handle this kind of situation through 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. Here is an example.
def greet(*names):
   """This function greets all
   the person in the names tuple."""

   # names is a tuple with arguments
   for name in names:
       print("Hello",name)

greet("Monica","Luke","Steve","John")
Output

Hello Monica
Hello Luke
Hello Steve
Hello John
Here, we have called the function with multiple arguments. These arguments get wrapped up into a tuple before being passed into the function. Inside the function, we use a for loop to retrieve all the arguments back.

Comments

Popular posts from this blog

Python Input and Output | Usage of input and output

  Python Output Using print() function We use the print() function to output data to the standard output device (screen). print('This sentence is output to the screen') # Output: This sentence is output to the screen a = 5 print('The value of a is', a) # Output: The value of a is 5 output This sentence is output to the screen The value of a is 5 In the second print() statement, we can notice that a space was added between the string and the value of variable a.This is by default, but we can change it. The actual syntax of the print() function is print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) Here, objects is the value(s) to be printed. The sep separator is used between the values. It defaults into a space character. After all values are printed, end is printed. It defaults into a new line. The file is the object where the values are printed and its default value is sys.stdout (screen). Here are an example to illustrate this. Amazon Best...

Python Package

  Python Package We don't usually store all of our files in our computer in the same location. We use a well-organized hierarchy of directories for easier access. Similar files are kept in the same directory, for example, we may keep all the songs in the "music" directory. Analogous to this, Python has packages for directories and modules for files. As our application program grows larger in size with a lot of modules, we place similar modules in one package and different modules in different packages. This makes a project (program) easy to manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a Python package can have sub-packages and modules. A directory must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but we generally place the initialization code for that package in this file. Importing module from a package We can import modules from packages using the dot (....

Python Exception Handling | Learn python

  Python Exception Handling - Try, Except and Finally Python has many built-in exceptions which forces your program to output an error when something in it goes wrong. When these exceptions occur, it causes the current process to stop and passes it to the calling process until it is handled. If not handled, our program will crash. For example, if function A calls function B which in turn calls function C and an exception occurs in function C. If it is not handled in C, the exception passes to B and then to A. If never handled, an error message is spit out and our program come to a sudden, unexpected halt. Catching Exceptions in Python In Python, exceptions can be handled using a try statement. A critical operation which can raise exception is placed inside the try clause and the code that handles exception is written in except clause. It is up to us, what operations we perform once we have caught the exception. Here is a simple example. # import module sys to get the type of except...