Python Functions
Python Functions
I. Types of function (built-in functions, user defined functions ,functions defined in module,)
II. Creating user defined function
III. Arguments and parameters
IV. Default parameters
V. Positional parameters
VI. Function returning value(s)
VII. Flow of execution
VIII. Scope of a variable (global scope, local scope)
IX. Recursion
X. Functions defined in module
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better
modularity for your application and a high degree of code reusing. In Python, a function is a group of related statements that
performs 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 the code reusable.
I. Types of function
Built-in functions (Library Function o PDFs), such as help() to ask for help, min() to get the minimum value, print() to
print an object etc.
User-Defined Functions (UDFs), which are functions that users create to help them out.
Functions defined in module.
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
1. Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
2. Any input parameters or arguments should be placed within these parentheses. You can also define parameters
inside these parentheses.
3. The first statement of a function can be an optional statement - the documentation string of the function .
4. The code block within every function starts with a colon (:) and is indented.
5. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
Syntax
4 code block
5 return [expression]
Example
print str
return
Information can be passed into functions as arguments.Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a comma.The following example has a function with one
argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:
Example
def my_function(fname):
my_function("Emil")
my_function("Phone")
my_function("Address")
output
Emil Detail
Phone Detail
Address Detail
Parameters or Arguments
The terms parameter and argument can be used for the same thing: information that are passed into a function.
From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition.
Number of Arguments
By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you
have to call the function with 2 arguments, not more, and not less.
Example
print(a+b)
my_function(12,14)
The following example shows how to use a default parameter value. If we call the function without argument, it uses the default
value:
Example
my_function()
my_function("Brazil")
V. Positional parameters
If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function
definition. This way the function will receive a tuple of arguments, and can access the items accordingly:
def my_function(*num):
my_function(2,4,6)
Keyword Arguments
You can also send arguments with the key = value syntax. This way the order of the arguments does not matter.
If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter
name in the function definition.This way the function will receive a dictionary of arguments, and can access the items accordingly:
def my_function(**kid):
You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data
type inside the function.E.g. if you send a List as an argument, it will still be a List when it reaches the function:
def my_function(food):
for x in food:
print(x)
my_function(fruits)
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
def plus(a,b):
sum = a + b
mul=a*b
s, m = plus(3,4)
print(s)
print(m)
VII. Flow of execution
When you are working with functions it is really important to know the order in which statements are executed. This is called the
flow of execution .Execution always begins at the first statement of the program. Statements are executed one at a time, in order,
from top to bottom. Function definitions do not alter the flow of execution of the program, but remember that statements inside
the function are not executed until the function is called.
2 y = b ** p
3 return y
5 def square(x):
6 a = pow(x, 2)
7 return a
9n=5
10 result = square(n)
11 print(result)
Ans: 1,5,9,10,5,6,1,2,3,6,7,10,11
Local Scope
Whenever you define a variable within a function, its scope lies ONLY within the function. It is accessible from the point at which it is
defined until the end of the function and exists for as long as the function is executing (Source). Which means its value cannot be
changed or even accessed from outside the function. Let's take a simple example:
def print_number():
first_num = 1
# Print statement 1
print_number()
# Print statement 2
print("The first number defined is: ", first_num)
We were able to print the first_num variable by calling the function print_number() (# Print statement 1). But when trying to access
and then print the same variable from outside the function (# Print statement 2), it raised a NameError. This is because first_num is
"local" to the function - thus, it cannot be reached from outside the function body.
Global Scope
This is perhaps the easiest scope to understand. Whenever a variable is defined outside any function, it becomes a global variable,
and its scope is anywhere within the program. Which means it can be used by any function.
greeting = "Hello"
def greeting_world():
world = "World"
print(greeting, world)
def greeting_name(name):
print(greeting, name)
greeting_world()
greeting_name("Ankur")
IX. Recursion
Python also accepts function recursion, which means a defined function can call itself.Recursion is a common mathematical and
programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a
result.
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
else:
When you need to write longer programs you start writing scripts. As your program grows more in the size you may want to split it
into several files for easier maintenance as well as reusability of the code. The solution to this is Modules. You can define your most
used functions in a module and import it, instead of copying their definitions into different programs. A module can be imported by
another program to make use of its functionality. This is how you can use the Python standard library as well.
Simply put, a module is a file consisting of Python code. It can define functions, classes, and variables, and can also include runnable
code. Any Python file can be referenced as a module. There are various methods of writing modules, but the simplest way is to
create a file with a .py extension which contains functions and variables.
Writing a module is just like writing any other Python file. Let's start by writing a function to add/subtract two numbers in a file
calculation.py.
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)
If you try to execute this script on the command line, nothing will happen because you have not instructed the program to do
anything. Create another python script in the same directory with name module_test.py and write following code into it.
If you execute module_test.py, you will see "3" as output. When the interpreter came across the import statement, it imported the
calculation module in your code and then by using the dot operator, you were able to access the add() function.
print(add(1,2))
In above example, only the add() function is imported and used. Notice the use of add()? You can now access it directly without
using the module name. You can import multiple attributes as well, separating them with a comma in the import statement. Take a
look at the following example:
You can import all attributes of a module using this statement. This will make all attributes of imported module visible in your code.
print(add(1,2))
print(sub(3,2))
Note that in the professional world, you should avoid using from..import and from..import*, as it makes your code less readable.
You can rename the module you are importing, which can be useful in cases when you want to give a more meaningful name to the
module or the module name is too large to use repeatedly. You can use the as keyword to rename it. The following example explains
how to use it in your program.
print(cal.add(1,2))
Note that you now can't use calculation.add(1,2) anymore, as calculation is no longer recognized in your program.