0% found this document useful (0 votes)
197 views

Functions, Scoping and Abstraction

The document discusses functions, scoping, and abstraction in Python, explaining how to define functions, call functions, and handle variable scoping. It provides examples of defining functions that take parameters, returning values from functions, and using decomposition and abstraction to structure code into reusable modules.

Uploaded by

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

Functions, Scoping and Abstraction

The document discusses functions, scoping, and abstraction in Python, explaining how to define functions, call functions, and handle variable scoping. It provides examples of defining functions that take parameters, returning values from functions, and using decomposition and abstraction to structure code into reusable modules.

Uploaded by

Ankur Sahu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Functions, Scoping and Abstraction

- Decomposition and Abstraction


Instructor: Prof. Ashwin Ganesan
International School of Engineering (INSOFE)

http://www.insofe.edu.in Data Science Education and Research


How do we write good code?
● So far
○ Covered language mechanisms
○ Know how to write different files for each computation
○ Each file is some piece of code
○ Each code is a sequence of instructions
● Problems with this approach
○ Easy for small-scale problems
○ Messy for larger problems
○ Hard to keep track of details
○ How do you know the right info is supplied to the right part of code

Data Science Education and Research www.insofe.edu.in 2


Example
Using bisection search to approximate square root: ● Reasonable piece of code, but
● Lacks general utility
○ Works only for specific values of x, epsilon
○ To reuse it, need to copy-and-paste the
code, possibly edit variable names
○ Can’t use this computation inside other,
more complex, computation
○ Have to edit code if we want cube roots
instead of square roots
○ If we want both cube roots and square roots,
or square roots more than once, will have
multiple chunks of identical code
○ Multiple chunks of identical code: more
chance for error, hard to maintain

Data Science Education and Research www.insofe.edu.in 3


Example
Using bisection search to approximate square root:

versus

Data Science Education and Research www.insofe.edu.in 4


Good programming
● More code is not necessarily a good thing
● Measure good programming by the amount of functionality
● Introduce functions
● Mechanism to achieve decomposition and abstraction

Data Science Education and Research www.insofe.edu.in 5


Example -- projector
● A projector is a black box
● Don’t know how it works
● Know the interface: input/output
● Connect any electronics to it that can communicate with that input
● Black box somehow converts image from input source to a wall, magnifying
it
● Abstraction idea: do not need to know how projects works to use it

Data Science Education and Research www.insofe.edu.in 6


Apply these ideas to programming
● Decomposition
○ Break problem into different, self-contained, pieces
● Abstraction
○ Suppress details of method to compute something from use of that
computation

Data Science Education and Research www.insofe.edu.in 7


Create structure with decomposition
● Divide code into modules
○ Are self-contained
○ Used to break up code
○ Intended to be reusable
○ Keep code organized
○ Keep code coherent
● This lecture: achieve decomposition with functions
● Next course: achieve decomposition with classes

Data Science Education and Research www.insofe.edu.in 8


Suppress details with abstraction
● In example, no need to know how to build projector
● In programming, think of a piece of code as a black box
○ Cannot see details
○ Do not need to see details
○ Do not want to see details
○ Hide tedious coding details
● Achieve abstraction with function specifications or docstrings

Data Science Education and Research www.insofe.edu.in 9


Decomposition and abstraction
● Powerful together
● Code can be used many times but only has to be debugged once!

Data Science Education and Research www.insofe.edu.in 10


Functions, Scoping and Abstraction
- Functions
Instructor: Prof. Ashwin Ganesan
International School of Engineering (INSOFE)

http://www.insofe.edu.in Data Science Education and Research


How to write and call/invoke a function

Data Science Education and Research www.insofe.edu.in 12


In the function body

Data Science Education and Research www.insofe.edu.in 13


Function definition in Python
● We’ve used (built-in) functions such as max and abs earlier
● Now we have the ability to define and use our own functions, as if they
were built-in, which is extremely convenient
● Function definition in Python is of the form:

def name of function (list of formal parameters):


body of function

● def is a reserved word


● Function body can be any piece of code, but the return statement can be
used only inside a function
Data Science Education and Research www.insofe.edu.in 14
Formal and actual parameters
● Example:

● Formal parameters of the function are the sequence of names within parantheses
following the function name (x, y in the above example)
● The function call (or function invocation) contains arguments (also called the actual
parameters)
● When the function is called, the formal parameters are bound to the actual
parameters (in above eg, the invocation maxVal(4,3) binds x and y to 4 and 3,
respectively)
Data Science Education and Research www.insofe.edu.in 15
Function calls as expressions
● A function call is an expression
○ Value of the expression is the value returned return by the function
○ Example:
■ maxVal(3,4) is an expression with value 4
■ maxVal(3,4)*maxVal(3,2) is an expression with value 12
● Return statements
○ After a return statement is executed
■ the rest of the code inside the function body is not executed, and
■ the point of execution is transferred to the code immediately following
the function invocation
○ Can have more than one return statement in the function body, but at most
one of them is executed
Data Science Education and Research www.insofe.edu.in 16
Quiz
What is the output of the program below?

def maxVal(x, y):


if x > y:
return x
else:
return y

z = 6
res = 2*maxVal(3+4, z)
print(res)

Data Science Education and Research www.insofe.edu.in 17


Variable types
● The arguments passed to the function can be of any type (unlike other languages
such as C, where the types are defined explicitly)
def times(x, y):
return x * y

a = times(3, 4)
print(a)
b = times('hello', 3)
print(b)

Output:

12
hellohellohello

Data Science Education and Research www.insofe.edu.in 18


Exercise
Write a function isIn that accepts two strings as arguments and returns True if either
string occurs anywhere in the other, and False otherwise. Hint: you might want to use the
built-in str operation in.

Data Science Education and Research www.insofe.edu.in 19


Functions, Scoping and Abstraction
- Scoping
Instructor: Prof. Ashwin Ganesan
International School of Engineering (INSOFE)

http://www.insofe.edu.in Data Science Education and Research


Variable scope
● Formal parameter gets bound to the value of actual parameter when function is
called
● New function scope/stack frame/environment/name space created when enter a
function
● Scope is mapping of names to objects
● Example:

Output: in f(x): x = 4
Back to main body: x = 3
Data Science Education and Research www.insofe.edu.in 21
Warning if no return statement
● Python returns the value None, if no return statement is given
○ Indicates the absence of value
○ To write a procedure (rather than function) f(x,y), just use def f(x,y): and
have no return statement
● Example:

Output: None
Data Science Education and Research www.insofe.edu.in 22
return vs. print
return print

● Return only has meaning inside ● print can be used outside


a function functions
● Only one return executed inside ● Can execute many print
a function statements inside a function
● Code inside function but after ● Code inside function can be
return statement not executed executed after a print statement
● Has a value associated with it, ● Has a value associated with it,
given to function caller outputted to the console

Data Science Education and Research www.insofe.edu.in 23


Functions as arguments
Arguments can be of any type, including functions:

Output:

inside func_a
None
inside func_b
7
inside func_c
inside func_a
None

Data Science Education and Research www.insofe.edu.in 24


Local variables
The name x used as a formal parameter is a
local variable inside f. Changing its value
inside f does not affect the value of the copy
outside the scope of f:

Output:

x = 4
z = 4
x = 3
y = 2

Data Science Education and Research www.insofe.edu.in 25


Lists in Python

When a list L is passed as an argument to a function, the value passed is the address
in memory where the contents of L are stored.

If L is modified inside the function, the changes are persistent (as in L1 below).

If you want to modify only a copy of L, do cloning to pass a copy as argument (as in
L2[:] below)

Output:

Inside f. 4 [1, 2] [1, 3]


After f. 4 [1, 6] [1, 3]

Data Science Education and Research www.insofe.edu.in 26


Functions as objects

Output:

[2, 4]
4
Abc
Abc
<class 'NoneType'>
None

Data Science Education and Research www.insofe.edu.in 27


Review question
What is the output of the following program?

Data Science Education and Research www.insofe.edu.in 28


Stack frames
● Each function defines a new name space or scope
● At top level (i.e. level of shell), a symbol table keeps track of all variable
names and their current bindings
● When a function is called, a new symbol table (stack frame) for f is created
○ Keeps track of names defined within function (including formal
parameters)
○ If another function is called within the function body, another stack
frame is created
● When the function completes, its stack frame goes away
● The stack frame at the lowest level is called the global/main program scope
● Call stack (activation stack) stores info about all active subroutines
Data Science Education and Research www.insofe.edu.in 29
Stacks
● In a call stack, the last (i.e. most recent) function pushed on top of the call
stack is the first one to be popped (removed) from the call stack
● A stack is a last-in first-out (LIFO) system
○ Think of a stack of plates in a cafeteria
○ A data type for (storing) a sequence of elements on which only specific operations can be
performed
■ Elements can be inserted or deleted only at one end
■ Most recent element inserted is the first one to be deleted

Data Science Education and Research www.insofe.edu.in 30


Scope
● Inside a function
○ can access a variable defined outside
○ cannot modify a variable defined outside
● Global variables versus local variables
○ If a variable x in an expression inside a function
■ is defined both as a local variable and as a global variable, the
local value will be used to evaluate the expression
■ Is defined only globally, the global value will be used

Data Science Education and Research www.insofe.edu.in 31


Scope examples
Local variables for a function def f(): Output:
print(x)
● If a variable occurs anywhere in 3
a function in the left hand side of def g():
print(x)
an assignment statement, it is UnboundLocalError:
x = 1 local variable 'x'
considered local to the function
referenced before
(even it occurs in RHS in an x = 3
assignment
f()
earlier statement)
x = 3
○ The order in which the references to
g()
a name occur is not relevant

Data Science Education and Research www.insofe.edu.in 32


Scope examples

def f(y): def g(y): def h(y):


x = 1 print(x) x = x + 1
x += 1 print(x + 1) x = 5
print(x) x = 5 h(x)
x = 5 g(x) print(x)
f(x) print(x)
print(x) Output:
Output:
Output: UnboundLocalError:
5 local variable 'x'
2 6 referenced before
5 5 assignment

Data Science Education and Research www.insofe.edu.in 33


Review question
What is the output of the following program?

Data Science Education and Research www.insofe.edu.in 34


Scope

Output:

in g(x): x = 4
4
3

Data Science Education and Research www.insofe.edu.in 35


Quiz (Function calls)
How many total lines of output will show up if you run the code below?

def add(x, y):


return x+y

def mult(x, y):


print(x*y)

add(1,2)
print(add(2,3))
mult(3,4)
print(mult(4,5))

(A) 0 (B) 2 (C) 3 (D) 4 (E) 5

Data Science Education and Research www.insofe.edu.in 36


Quiz (Functions as arguments)
What does the code below print?

def sq(func, x):


y = x**2
return func(y)

def f(x):
return x**2

calc = sq(f, 2)
print(calc)

(A) 4 (B) 8 (C) 16 (D) Nothing, it will show an error

Data Science Education and Research www.insofe.edu.in 37


Functions, Scoping and Abstraction
- Keyword Arguments and Default Values
Instructor: Prof. Ashwin Ganesan
International School of Engineering (INSOFE)

http://www.insofe.edu.in Data Science Education and Research


Binding formal parameters
● Two ways in Python to bind formal parameters to actual parameters
○ Positional method
■ First formal parameter is bound to first actual parameter
■ Second formal parameter is bound to second actual parameter
■ Etc
○ Keyword arguments
■ Name of formal parameter is used to do the binding

Data Science Education and Research www.insofe.edu.in 39


Keyword arguments
The four invocations of printName below are equivalent.

def printName(firstName, lastName, reverse):


if reverse:
print(lastName + ', ' + firstName)
else:
print(firstName, lastName)

printName("Ashwin", "Ganesan", False)


printName("Ashwin", "Ganesan", reverse = False)
printName("Ashwin", lastName = "Ganesan", reverse = False)
printName(lastName = "Ganesan", firstName = "Ashwin", reverse = False)

Output:
Ashwin Ganesan
Ashwin Ganesan
Ashwin Ganesan
Ashwin Ganesan
Data Science Education and Research www.insofe.edu.in 40
Keyword arguments
Once a formal parameter is mentioned in the function call, all later arguments must also mention formal
parameters. The function call below gives an error message because “lastName” is mentioned in the
second argument but the third argument doesn’t mention a formal parameter.

def printName(firstName, lastName, reverse):


if reverse:
print(lastName + ', ' + firstName)
else:
print(firstName, lastName)

printName("Ashwin", lastName = "Ganesan", False)

Output:
printName("Ashwin", lastName = "Ganesan", False)
^
SyntaxError: positional argument follows keyword argument

Data Science Education and Research www.insofe.edu.in 41


Default parameter values
Can mention default values for parameter in the function declaration. Allows programmer to call
function with fewer than specified number of arguments.

def printName(firstName, lastName, reverse = False):


if reverse:
print(lastName + ', ' + firstName)
Else:
print(firstName, lastName)

printName("Ashwin", "Ganesan") #third argument is False by default


printName("Ashwin", "Ganesan", True)
printName("Ashwin", "Ganesan", reverse = True)

Output:
Ashwin Ganesan
Ganesan, Ashwin
Ganesan, Ashwin
Data Science Education and Research www.insofe.edu.in 42
Functions, Scoping and Abstraction
- Specifications
Instructor: Prof. Ashwin Ganesan
International School of Engineering (INSOFE)

http://www.insofe.edu.in Data Science Education and Research


Specifications
● A specification (or input-output specs) for a function is a contract between the
implementer of a function and the client who will use it
○ Two parts: Assumptions and guarantees
● Assumptions
○ conditions that must be met by clients of the function
○ Typically constraints on values of parameters
○ The input values for function
● Guarantees
○ Conditions that must be met by the function, provided it has been called in a
manner consistent with assumptions
○ Has to do with the output (return parameters) of function

Data Science Education and Research www.insofe.edu.in 44


Example
Function specifications

● Are specified within triple double quotes. Called the docstring


● Optional, but tells programmer what the function does

def is_even( i ):
"""
Input: i, a positive int
Output: A boolean, equal to True if i is even, and False otherwise
"""
return i%2 == 0

print(is_even(3))

Output:
False

Data Science Education and Research www.insofe.edu.in 45


Docstrings
● To get help on what a function does, can print docstring from shell using the __doc__
command

Data Science Education and Research www.insofe.edu.in 46


Decomposition and abstraction
● Functions
○ Help create computational elements, essentially new (user-defined) primitives
● Decomposition
○ Creates structure
○ Allows us to break a program into parts
○ Each part is essentially self-contained and can be reused in different settings
● Abstraction
○ Hides detail: can use a piece of code as it it was a black box
● How large organizations use teams of programmers to get things done
○ You are given the specification for a module, and can start writing code to
implement that module
○ Others can work at the same time on their modules, and write code that uses
your module without knowing how your module will be implemented
Data Science Education and Research www.insofe.edu.in 47
References and Acknowledgements
Many of the examples, images and other content in these slides are taken (often
verbatim) from the following sources:

1. Eric Grimson, “6.00.1x: Introduction to Computer Science and Programming using


Python”, offered by MITx on edX. (Much of the content in the slides that follow is taken
(often verbatim) from this course.)

2. John Guttag, “Introduction to Computation and Programming Using Python with


Application to Understanding Data”, Second Edition, MIT Press, 2016.

Data Science Education and Research www.insofe.edu.in 48

You might also like