Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Functions

The document provides a comprehensive overview of functions in Python, including their types, syntax, parameters, and scope resolution through the LEGB rule. It covers various concepts such as call by value and reference, default and keyword arguments, variable length arguments, and returning multiple values. Additionally, it emphasizes the importance of documentation and the difference between parameters and arguments in function definitions.

Uploaded by

pranayjn14
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Functions

The document provides a comprehensive overview of functions in Python, including their types, syntax, parameters, and scope resolution through the LEGB rule. It covers various concepts such as call by value and reference, default and keyword arguments, variable length arguments, and returning multiple values. Additionally, it emphasizes the importance of documentation and the difference between parameters and arguments in function definitions.

Uploaded by

pranayjn14
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

profound classes

Functions

Function, its type and Scope of Variables

Gaurav Sharma
9971677014
Index

Topic Page No.


1. Function, It’s types and Syntax……………………………………..………....2

2. Parameter and Argument…………………………………………..…….…….3

3. Call by Value and Reference…………………………………..…….…………3

4. Default Arguments………………………………………………..……………4

5. Keyword Arguments…………………………………………………….……..4

6. Variable length arguments……………………………………………………..5

7. Anonymous functions………………………………………………………….5

8. Python return statement………………………………………………………..5

9. Returning multiple values from a function……………………………………6

10.Scope Resolution in Python | LEGB Rule……………….……………………6

Page 1
Functions in Python
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. There are four types of functions in Python:

I. Built-in functions, such as help() to ask for help, min() to get the minimum value, print() to print an object to
the terminal etc.
II. Function defined in modules like random, maths etc.
III. User-Defined Functions (UDFs), which are functions that users create to help them out; And

Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

return

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.

A simple example
def evenOdd( x ): # x is parameter
”””A simple Python function to #docstring
check whether x is even or odd ”””

if (x % 2 == 0):
print("even")
else:
print("odd")

# Driver code
a=10
evenOdd(a) #function calling a is argument
evenOdd(3) #function calling

Output:
even
odd

Page 2
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:
>>> print(evenOdd.__doc__)
A simple Python function to
check whether x is even or odd

Difference between Parameters and Arguments


A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass
into the method's parameters.
Parameter is variable in the declaration of function. Argument is the actual value of this variable that gets
passed to function.

Note: The parameter required by a function i.e. which has/have to be passed to the function while calling are
called positional or required arguments. In above evenOdd( ) example, x is a positional argument. You can’t
skip or change the order of these arguments.

Pass by Reference or pass by value?


One important thing to note is, in Python every variable name is a reference. When we pass a variable to a function,
a new reference to the object is created. Parameter passing in Python is same as reference passing in any languages
like C++ or Java. To be more clear

Arguments are passed by assignment. The rationale behind this is twofold:


1. the parameter passed in is actually a reference to an object (but the reference is passed by value)
2. some data types are mutable, but others aren't
So:
 If you pass a mutable object into a method, the method gets a reference to that same object and you
can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will
know nothing about it, and after you're done, the outer reference will still point at the original object.
 If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't
even mutate the object.

To be more clear let us understand the following codes

# Here x is a new reference to same list lst


def myFun(x):
x[0] = 20

# Driver Code (Note that lst is modified after function call).


lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output:
[20, 11, 12, 13, 14, 15]

Page 3
When we pass a reference and change the received reference to something else, the connection between passed
and received parameter is broken. For example, consider below program.

def myFun(x):

# After below line link of x with previous object gets broken. A new object is
#assigned to x.
x = [20, 30, 40]

# Driver Code (Note that lst is not modified after function call).
lst = [10, 11, 12, 13, 14, 15]
myFun(lst)
print(lst)

Output:
[10, 11, 12, 13, 14, 15]

Default arguments:
A default argument is a parameter that assumes a default value if a value is not provided in the function call for that
argument. The following example illustrates Default arguments.

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)

# Driver code (We call myFun() with only 1 argument)


myFun(10)

Output:
('x: ', 10)
('y: ', 50)
Like C++ default arguments, 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.

Keyword arguments:
The idea behind Keyword argument is to allow caller to specify argument name with values so that caller does not
need to remember order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname):
print(firstname, lastname)

# Keyword arguments
student(firstname =’Raman’, lastname ='Singh')
student(lastname ='Singh', firstname ='Raman')

Output:
('Raman', 'Singh')
('Raman', 'Singh')

Page 4
Variable length arguments:
We can have variable number of arguments. Please see this for details.

# Python program to illustrate


# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)

myFun('Hello', 'Welcome', 'to', 'Class')


Output:
Hello
Welcome
to
Class

Python return statement


A return statement is used to end the execution of the function call and “returns” the result (value of the expression
following the return keyword) to the caller. The statements after the return statements are not executed. If the
return statement is without any expression, then the special value None is returned. If a function doesn’t use return
statement, it can be called as void function.

Note: Return statement can’t be used outside the function.


Syntax:
def fun():
statements
.
.
return [expression]
# Python program to demonstrate working of return statement
def add(a, b):
# returning sum of a and b
return a + b

def is_true(a):
# returning boolean of a
return bool(a)

# calling function
res = add(2, 3)
print("Result of add function is ", res)

res = is_true(2<5)
print("\nResult of is_true function is ", res))
Output:
Result of add function is 5
Result of is_true function is True

Returning multiple values from a function


Returning multiple values from a function is quite cumbersome in C and other languages, but it is very easy to do
with Python.

In Python, you can return multiple values by simply return them separated by commas. See a simple example below

def test():
return 'abc', 100 #Note: comma-separated values are considered tuples without parentheses
result = test()
print(result)

Page 5
print(type(result))

Output:
('abc', 100)
<class 'tuple'>
You can unpack and assign multiple return values to different variables.
a, b = test()
print(a)
print(b)

Output:
abc
100

Scope Resolution in Python | LEGB Rule


Namespaces: A namespace is a container where names are mapped to objects, they are used to avoid confusions in
cases where same names exist in different namespaces. They are created by modules, functions, classes etc.

Scope: A scope defines the hierarchical order in which the namespaces have to be searched in order to obtain the
mappings of name-to-object(variables). It is a context in which variables exist and from which they are referenced. It
defines the accessibility and the lifetime of a variable.

Let us take a simple example as shown below:

pi = 'outer pi variable'
def print_pi():
pi = 'inner pi variable'
print(pi)
print_pi()
print(pi)

Output:
inner pi variable
outer pi variable
Above program give different outputs because the same variable name pi resides in different namespaces, one
inside the function print_pi and the other in the upper level. When print_pi() gets executed, ‘inner pi variable‘ is
printed as that is pi value inside the function namespace. The value ‘outer pi variable‘ is printed when pi is
referenced in the outer namespace. From the above example, we can guess that there definitely is a rule which is
followed, in order in decide from which namespace a variable has to be picked.

Scope resolution via LEGB rule:

Page 6
In Python, the LEGB rule is used to decide the order in which the namespaces are to be searched for scope
resolution. The scopes are listed below in terms of hierarchy(highest to lowest/narrowest to broadest):

Local(L): Defined inside function/class


Enclosed(E): Defined inside enclosing functions(Nested function concept)
Global(G): Defined at the uppermost level
Built-in(B): Reserved names in Python built-in modules

Local Scope:
Local scope refers to variables defined in current function. Always, a function will first look up for a variable name in
its local scope. Only if it does not find it there, the outer scopes are checked.

# Local Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)
inner()

Output:
inner pi variable
On running the above program, the execution of the inner function prints the value of its local (highest priority in
LEGB rule) variable pi because it is defined and available in the local scope.

Local and Global Scopes:


If a variable is not defined in local scope, then, it is checked for in the higher scope, in this case, the global scope.

# Global Scope
pi = 'global pi variable'
def inner():
pi = 'inner pi variable'
print(pi)

inner()
print(pi)

Output:
inner pi variable
global pi variable
Therefore, as expected the program prints out the value in the local scope on execution of inner(). It is because it is
defined inside the function and that is the first place where the variable is looked up. The pi value in global scope is
printed on execution of print(pi) on line 9.

Local, Enclosed and Global Scopes:


For the enclosed scope, we need to define an outer function enclosing the inner function, comment out the local pi
variable of inner function and refer to pi using the nonlocal keyword.

# Enclosed Scope
pi = 'global pi variable'
def outer():
pi = 'outer pi variable'
def inner():
print(pi)
inner()

Page 7
outer()
print(pi)
Output:
outer pi variable
global pi variable

The pi variable is not found in local scope, so the higher scopes are looked up. It is found in both enclosed and global
scopes. But as per the LEGB hierarchy, the enclosed scope variable is considered even though we have one defined
in the global scope.

Local, Enclosed, Global and Built-in Scopes:


The final check can be done by importing pi from math module and commenting the global, enclosed and local pi
variables as shown below:

# Built-in Scope
from math import pi
# pi = 'global pi variable'
def outer():
# pi = 'outer pi variable'
def inner():
# pi = 'inner pi variable'
print(pi)
inner()
outer()

Output:
3.141592653589793

Since, pi is not defined in either local, enclosed or global scope, the built-in scope is looked up i.e the pi value
imported from math module. Since the program is able to find the value of pi in the outermost scope, the following
output is obtained,

~~~~ Thank You! ~~~~

Page 8

You might also like