You are on page 1of 30

Programming with Python

Maya Nair
A function is a set of statements that take inputs, do some
specific computation and produces output.
Python
Types of functions:
Functions
• Built-in functions- pre-defined functions available with various
modules in python
• User defined functions – user-specific function defined by the
user

Advanced Python Session 2020 Maya Nair 2


Syntax of function definition:
def func_name(formal parameters list):
function body
return [Expression]
# if no return statement is used , the function by default returns a None type value

Syntax for function call :


func_name(actual parameters list )
Python
A function is not executed unless it is made a call to.
Functions eg.:
def factorial(n): Output:
Factorial of 5 is 120
fact=1
for i in range(1,n+1):
fact*=i
return fact
print(f ’ Factorial of 5 is {factorial(5)}’) 3
When we pass a variable to a function, a new reference to the
object is created( pass-by-object reference)

Immutable objects behave like pass by value


• Any change made on formal parameters does not affect
Python the actual parameters
Functions Mutable objects behave like pass by reference unless
completely redefined inside function body
• Any modification on a mutable formal parameter is
retained in actual parameter.

Advanced Python Session 2020 Maya Nair 4


Different ways of passing arguments are:

Python • Default Arguments


Functions • Keyword Arguments
• Variable length arguments

Advanced Python Session 2020 Maya Nair 5


A default argument is a parameter that assumes a
default value if a value is not provided in the
function call for that argument.

Python e.g.
Functions- def personal_details(name,phoneno,age=None):
Default if age==None:
arguments print(f"Age not provided by {name}")
else:
print(f"Age of {name} is {age}")
Output:
personal_details("Suresh",895653883) Age not provided by Suresh
Age of Ramesh is 29
personal_details("Ramesh",767767623,29)

Advanced Python Session 2020 Maya Nair 6


In Keyword argument method caller specifies argument name with
Python values so that caller does not need to remember order of parameters.
Functions- e.g.
Keyword def personal_details(name,phoneno):
Arguments
print(f" Your name is {name} and your phone no is {phoneno}")
personal_details(name="Ramesh",phoneno=98987654)
personal_details(phoneno=767767623,name="Suresh"))
Output:
Your name is Ramesh and your phone no is 98987654
Your name is Suresh and your phone no is 767767623
7
Python provides variable length argument method with
which the number of formal parameters are not fixed. It can
vary with the list passed by the caller. An asterisk (*) is
Python placed before the variable name that holds the values of all
Functions- nonkeyword variable arguments. Output:
Variable Mahesh's friends:
e.g.
length Ramesh
Arguments def myfriends(name,*argv): Suresh
Paresh
print(f"{name}'s friends:") Sam's friends:
Alex
for arg in argv: Lucy
print(arg)
myfriends("Mahesh","Ramesh","Suresh","Paresh")
myfriends("Sam","Alex","Lucy") 8
Not all variables can be accessed from anywhere in a program.
The part of a program where a variable is accessible is called its
scope.There are four major types of variable scope and is the
basis for the LEGB rule. LEGB stands for Local -> Enclosing
-> Global -> Built-in.
• Local Scope
Python
• Whenever you define a variable within a function, its scope lies
Functions- ONLY within the function. It is accessible from the point at which
Scope of it is defined until the end of the function and exists for as long as
the function is executing.
Variables
e.g:
(LEGB rule)
def func1():
Output:
a=20 20
print(a)# printing a within its scope Name Error
func1()
print(a)#printing a out of scope

Advanced Python Session 2020 Maya Nair 9


• Enclosing Scope
• In a nested function scenario , where a function is defined inside another
function, all variables in the outer function has a scope within the inner
function but vice versa is not true.
• E.g.:
Python
def outer():
Functions-
Scope of first=12
Variables def inner(): Output:
(LEGB rule) second=24
12 24
Name Error :Second not defined
print(first,second) # first is in scope of inner
inner()
print(first,second) # second is not in scope of outer
outer()
Advanced Python Session 2020 Maya Nair 10
• Global Scope
• 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.

Python • name=“ ABC”


Functions- def func1():
Scope of print(“hello”,name)
Variables
# name is in scope of func1 Output:
(LEGB rule)
def func2(): hello ABC
Good Morning ABC
print(“Good Morning”,name) ABC is everywhere
# name is in scope of func2
func1()
func2()
Advanced Python Session 2020
print(f ’{name} isMayaeverywhere’)
Nair 11
# name is in scope outside all functions.
But if a function completely redefines a global variable, it will be
considered as its local variable witin the function
Python • E.g
Functions- name=“ ABC”
Scope of def func1():
Variables
(LEGB rule) name=“XYZ”
print(“hello”,name) # name is now a local variable of func1
func1()
print(f ’name is still {name}’) # change made in func1 does not
Output: affect name
hello XYZ
name is still ABC
Advanced Python Session 2020 Maya Nair 12
To resolve this issue , we can make use of ‘global’ keyword.
This tells the interpreter to use the global variable instead of creating a
local variable.
• E.g.
Python name=“ ABC”
Functions- def func1():
Scope of
global name
Variables
(LEGB rule) name=“XYZ”
print(“hello”,name) # name is now a local variable of func1
func1()
print(f ’name has changed to {name}’) # changes made by func1 is
Output:
reflected in global variable
hello XYZ
name has changed to XYZ
13
Built-in Scope
This is the widest scope in python. All the special reserved keywords
fall under this scope. We can call the keywords anywhere within our
Python
program without having to define them before use.
Functions-
Scope of
Variables
LEGB (Local -> Enclosing -> Global -> Built-in) is the logic followed
(LEGB rule)
by a Python interpreter when it is executing your program. For any
variable referenced it checks first in Local if not found it goes for
Enclosing again if not found goes for Global and finally it checks the
Built-in scope.

Advanced Python Session 2020 Maya Nair 14


Anonymous function means that a function is without a name.
Unlike the def keyword which is used to define the normal
functions , we use lambda keyword to create anonymous
functions. They are single line statement which can be defined
Python any where , even as an expression within a compound statement.
Functions- This function can have any number of arguments but only one
expression, which is evaluated and returned.
Anonymous/
Lambda Syntax:
functions lambda arglist: expression
e.g. cube=lambda x : x*x*x Output:
cube(2) 8
512
cube(8)
Lambda functions are used with filter() and map() functionalities
15
Object oriented programming is a programming paradigm which provides a
structuring in which properties and behaviors are bundled into individual objects.
They are natural way of representing real life entities. An object can be used to
represent a person with properties such as name, mobile no, address etc. and
behaviors such as eating, talking ,sleeping etc.
Python
Object Objects provide a way to club together a set of data(properties) with a set of
Oriented methods(behavior) which can operate on that data. This leads to the concept of
Concepts data hiding and data abstraction.
Before creating or instantiating objects we need to define how the objects are to be
formed. This is done with a class. A class is a blue print for objects and objects
are instances of a class. Once a class is defined ,we can create any number of
objects out of it. We can say class is an idea without actual existence where as
objects created out of it has individual existence with associated memory

16
Python Classes and Objects: Python is an object oriented language where every
variable you create is an object of a particular class. In fact, everything is a class
in Python.
E.g
>>> a=1.3
Python >>> type(a)
Object
<class 'float'>
Oriented
>>> l=[1,2,3]
Concepts
>>> type(l)
<class 'list'>

17
Syntax for creating a class:
All methods have an instance
class class_name: reference parameter ’ self ’ in
variables addition to other parameters

methods
Python e.g.:
Object Initialiser method which
Oriented class person: is automatically called
when an object of the
Concepts def __init__(self,name,age): class is created
self.name=name
self.age=age
def display(self):
print(f'Name is {self.name} and age is {self.age}’)

18
Syntax for creating objects :
Object_name=class_name(parameters to initializer if any)

Python e.g.
Object person1=Person(“Andrews”,35)
Oriented
person2=Person(“Maria”,25)
Concepts
person1.display()
Person2.display()
Output:
Name is Andrews and age is 35
Name is Maria and age is 25
19
• Write a program to create a class Department with instance variables
Dept_id, Dept_name and Manager. Apart from constructor two methods
have to be defined namely
• display() –displays all the information about the Department.
• updatemanager()-changes manager as per parameter.

Programming with Python I Maya Nair 02-12-2020 20


• Write a python program to create a class Product with instance variables
• pid,prodname and quantity and with below functions apart from initialize
• function.
• i. display() –displays all the information about the Product
• ii. updateqty()-changes quantity as per parameter

Programming with Python I Maya Nair 02-12-2020 21


Class variables and instance variables :
Class variables refers to attributes which are common to an entire class shared by all objects of the class whereas
instance variables are specific to instances. All variables referred with self are instance variables.
e.g.
class example:
counter =0 #class variable counter shared by all objects
def __init__(self,value):
self.value=value
Python example.counter+=1

Object def total(self): Output:


Oriented
return example.counter Value is 10
def display(self):
no of objects created is 1
Concepts print(f"Value is {self.value}")
Value is 50
e1=example(10)
e1.display()
no of objects created is 2
print(f" no of objects created is {e1.total()}")
e2=example(50)
e2.display()
print(f" no of objects created is {e2.total()}")
22
Data Hiding, Data encapsulation and Data Abstraction
Encapsulation is seen as the bundling of data with the methods that operate on that data. Information hiding on the other hand is the
principle that some internal information or data is "hidden", so that it can't be accidentally changed.
Data Abstraction = Data Encapsulation + Data Hiding
To implement data encapsulation , we can bind all the instance variables with getter and setter methods, which are used to retrieve the value and change the
value of the variables.
e.g.
class A:
def __init__(self,name=None):
self.name=name
def getName(self):
return self.name
def setName(self,newname):
Python self.name=newname
Object a1=A()
Oriented a2=A("ABC")
a1.setName("XYZ")
Concepts print(a1.getName())
Output:
a2.setName("PQR")
XYZ
print(a2.getName()) PQR
23
Data Hiding indicate that data should be hidden from direct external use . In python we cannot achieve complete isolation of
data but can simulate it with concept of private variables. We can declare that an instance variable is private by using double
underscore (__) before the variable name. Such variables can be directly accessed only within the class methods. e.g.
class A:
def __init__(self,name=None):
self.__name=name
def getName(self):
return self.__name
def setName(self,newname):

Python self.__name=newname
a1=A()
Object Output:
a2=A("ABC")
Oriented XYZ
a1.setName("XYZ")
PQR
Concept print(a1.getName())
AttributeError: 'A' object has no
a2.setName("PQR")
s print(a2.getName()) attribute '__name'
print(a1.__name)# here name can not be accessed
#outside the class without
#getter/setter function
#print(a1._A__name)# But we can access the private variable by using
# the notation _classname__variablename 24

#nothing is private in python


Inheritance.
One of the major advantages of Object Oriented Programming is re-use.
Inheritance is one of the mechanisms to achieve the same. In inheritance,
a class (usually called superclass) is inherited by another class (usually
Python called subclass). The subclass adds some attributes to superclass.
Object
Oriented Superclass Employee(empcode,department)

Concepts

Subclass Subclass
Manager(empcode,department,no_of_emp) Typist(empcode,department,typingspeed)
25
Syntax for inheritance
class subclass_name(superclass_name):
additional attributes
additional methods
e.g.
class Employee(object):
def __init__(self,empcode,department):
self.empcode=empcode
self.department=department
def display(self):

Python print(f"Emp code :{self.empcode} ,Department :{self.department}")


class Manager(Employee):
Object def __init__(self,empcode,department,no_of_emp):

Oriented Employee.__init__(self,empcode,department)
Output:
self.no_of_emp=no_of_emp
Concepts def display(self): Emp code :Emp001 ,Department :IT
Employee.display(self) Number of Employees managed 30
print(f" Number of Employees managed {self.no_of_emp}")
manager1=Manager("Emp001","IT",30)
manager1.display() 26
Filter() and Map()functions
The filter() function in Python takes in a function and a list as arguments.
This offers an elegant way to filter out all the elements of a sequence
“sequence”, for which the function returns True.
e.g.

List List1=[1,2,3,4,5,6,7,8,9,10]
Manipulation even_list=list( filter( ( lambda x:x%2==0),list1) )
and >>> even_list
Comprehension
[2, 4, 6, 8, 10]
>>> odd_list=list( filter( ( lambda x:x%2!=0),list1) )
>>> odd_list Let Marks=[45,90,25,50,85,35] be a list of marks obtained by
certain students. Write Filter function to create a list of students
[1, 3, 5, 7, 9] with marks>40.
Advanced Python Session 2020 Maya Nair 27
The map() function in Python takes in a function and a list as argument. The
function is called with a lambda function and a list and a new list is returned
which contains all the lambda modified items returned by that function for
List each item.
Manipulation
e.g.
and
Comprehension list1=[1,2,3,4,5,6,7,8,9,10]
power_list=list(map(lambda x: x**2,list1))
>>> power_list
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Advanced Python Session 2020 Maya Nair 28


Comprehension: Comprehensions in Python provide us with a short and concise way to construct new
sequences (such as lists, set, dictionary etc.) using sequences which have been already defined.

Rather than filtering and mapping lists using filter() and reduce() functions with the help of lamda functions ,
Python provides a very compact method called as list comprehensions.
Syntax:
output_list = [output_exp for var in input _list if (var satisfies this condition)]
List #list comprehension may or may not contain an if condition. List
Manipulati #comprehensions can contain multiple for (nested list
on and #comprehensions
Comprehen list1=[1,2,3,4,5,6,7,8,9,10]

sion even_list1=[ x for x in list1 if x%2==0 ]


>>> even_list1
[2, 4, 6, 8, 10]
power_list1=[x**2 for x in list1 ]
>>> power_list1
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 29
Dictionary Comprehension:
Syntax:
output_dict = { key:value for (key, value) in iterable if (key, value satisfy this condition)}
E.g. Suppose we want to create an output dictionary which contains only the odd numbers that are present in the input list as keys and their cubes
as values.
input_list = [1,2,3,4,5,6,7]

>>> dict1 = {x : x ** 3 for x in input_list if x % 2 != 0}


Python >>> dict1
{1: 1, 3: 27, 5: 125, 7: 343}
String,List
revisited E.g. Given two lists containing the names of countries and their corresponding capitals, construct a dictionary which maps
the states with their respective capitals.
Countries=["India","Australia","Canada","Germany"]
Capitals=["New Delhi","Canberra","Ottawa","Berlin"]
dict2 = {key:value for (key, value) in zip(Countries, Capitals) }
dict2
{'India': 'New Delhi', 'Australia': 'Canberra', 'Canada': 'Ottawa', 'Germany': 'Berlin’}
# here purpose of zip() is to map the similar index of multiple containers so that they #can be used just using as single
entity.
30

You might also like