0% found this document useful (0 votes)
38 views57 pages

Unit III (OLD)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views57 pages

Unit III (OLD)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

UNIT III

FUNCTIONS
Contents:
• Functions: Function Parameters, Local variables, the
global statement, Default Argument values,
Keyword Arguments, varArgs parameters, the
return statement. Anonymous Functions (lambda),
Doc strings.
• Modules: The from import statement, A module’s
name, Making your own modules, The dir function,
packages.
• Brief Tour of the Standard Library: re, math, date
time, turtle, tkinter.
What are Functions
• Functions are reusable pieces of programs.
• They allow you to give a name to a block of
statements, allowing you to run that block using the
specified name anywhere in your program and any
number of times.
• This is known as calling the function.
• We have already used many built-in functions such
as len and range.
• The function concept is probably the most
important building block of any nontrivial software
(in any programming language).
• Functions are defined using the def keyword.
• After this keyword comes an identifier name for the
function, followed by a pair of parentheses which
may enclose some names of variables, and by the
final colon that ends the line.
• Next follows the block of statements that are part of
this function.
• An example will show that this is actually very
simple:
function1.py
def say_hello():
# block belonging to the function
print ('Hello World!')
# End of function

say_hello() # call the function


say_hello() # call the function again
Function Parameters
• A function can take parameters, which are values you supply
to the function so that the function can do something
utilising those values.
• These parameters are just like variables except that the
values of these variables are defined when we call the
function and are already assigned values when the function
runs.
• Parameters are specified within the pair of parentheses in
the function definition, separated by commas.
• When we call the function, we supply the values in the same
way.
• Note the terminology used - the names given in the function
definition are called parameters whereas the values you
supply in the function call are called arguments.
function_param.py
def print_max(a, b):
if a > b:
print (a, 'is maximum')
elif a == b:
print (a, 'is equal to', b)
else:
print (b, 'is maximum')
# directly pass literal values

print_max(3, 4)
x=5
y=7
# pass variables as arguments
Local Variables
• When you declare variables inside a function
definition, they are not related in any way to other
variables with the same names used outside the
function - i.e. variable names are local to the
function.
• This is called the scope of the variable.
• All variables have the scope of the block they are
declared in starting from the point of definition of
the name.
function_local.py
x = 50
def func(x):
print ('x is', x)
x=2
print ('Changed local x to', x)
func(x)
print ('x is still', x)
The global statement
• It is used to create global variables from a non-
global scope i.e., inside a function.
• You can specify more than one global variable using
the same global statement e.g. global x, y, z.
• Rules of global keyword:
• If a variable is assigned a value anywhere within the
function’s body, it’s assumed to be a local unless
explicitly declared as global.
• We Use global keyword to use a global variable
inside a function.
• There is no need to use global keyword outside a
function_global.py
x = 50
def func():
global x
print ('x is', x)
x=2
print ('Changed global x to', x)
func()
print ('Value of x is', x)
Types Of Python Function Arguments
• There are four types of Python Functions.

• Required arguments (Positional Arguments)


• Keyword arguments
• Default arguments
• Variable-length Arguments (varArgs).
Required arguments
• Required arguments are the arguments passed to a
function in correct positional order. Here, the number
of arguments in the function call should match exactly
with the function definition.
def printme( str ):
"This prints a passed string into this function"
print(str)
return;
# Now you can call printme function
printme()
• To call the function printme(), you definitely need to
pass one argument, otherwise it gives a syntax error.
Default Argument Values

• For some functions, you may want to make some


parameters optional and use default values in case
the user does not want to provide values for them.
• Note that the default argument value should be a
constant. More precisely, the default argument
value should be immutable.
function_default.py

def say(message, times=1):


print (message * times)
say('Hello')
say('World', 5)
Keyword arguments
• If you have some functions with many parameters
and you want to specify only some of them, then
you can give values for such parameters by naming
them - this is called keyword arguments - we use
the name (keyword) instead of the position (which
we have been using all along) to specify the
arguments to the function.

• The idea is to allow caller to specify argument name


with values so that caller does not need to
remember order of parameters.
function_keyword.py
def func(a, b=5, c=10):
print ('a is', a, 'and b is', b, 'and c is', c)

func(3, 7)
func(25, c=24)
func(c=50, a=100)
VarArgs parameters
• Sometimes you might want to define a function that
can take any number of parameters, i.e. variable
number of arguments, this can be achieved by using
the stars.

• We can have both normal and keyword variable


number of arguments
function_varargs.py
# Python program to illustrate
# *args for variable number of arguments
def myFun(*argv):
for arg in argv:
print (arg)

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


# Python program to illustrate
# **args for variable number of keyword arguments
def myFun(**args):
for key, value in args.items():
print ("%s = %s" %(key, value))

# Driver code
myFun(first ='Aditya', mid ='Engg.', last='College')
• When we declare a starred parameter such as
*param , then all the positional arguments from
that point till the end are collected as a tuple called
'param'.
• Similarly, when we declare a double-starred
parameter such as **param , then all the keyword
arguments from that point till the end are collected
as a dictionary called 'param'.
Pass-by-object-reference
• Python is different.
• As we know, in Python, “Object references are
passed by value”.
• A function receives a reference to (and will access)
the same object in memory as used by the caller.
• However, it does not receive the box that the caller
is storing this object in; as in pass-by-value, the
function provides its own box and creates a new
variable for itself.
• Let’s try appending again:
• def append(list):
• list.append(1)
• print (list)

• list = [0]
• append(list)
• print (list)
• def reassign(list):
• list = [0, 1]
• print (list)

• list = [0]
• reassign(list)
• print (list)
• Note that a return statement without a value is equivalent
to return None.
• None is a special type in Python that represents
nothingness. For example, it is used to indicate that a
variable has no value if it has a value of None.
• Every function implicitly contains a return None
statement at the end unless you have written your own
return statement.
• You can see this by running print some_function() where
the function some_function does not use the return
statement such as:
def some_function():
pass
• The pass statement is used in Python to indicate an empty
Python Lambda (Anonymous Functions)
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but
can only have one expression.
• def keyword is used to define the normal functions and
the lambda keyword is used to create anonymous functions.
• Syntax: lambda arguments: expression

• You don’t need to assign lambda function to a variable.

• (lambda x, y: x * y)(3,4)
• Expected Output:
12
• # Python code to illustrate cube of a number
• # showing difference between def() and lambda().

def cube(y):
return y*y*y;

print(cube(5))

g = lambda x: x*x*x;
print(g(5))
• A lambda function that adds 10 to the number
passed in as an argument, and print the result:

x = lambda a : a + 10
print(x(5))
• A lambda function that multiplies argument a
with argument b and print the result:
x = lambda a, b : a * b
print(x(5, 6))
DocStrings
• Python has a nifty feature called documentation
strings, usually referred to by its shorter name
docstrings.
• A string on the first logical line of a function is the
docstring for that function. Note that DocStrings
also apply to modules and classes.
• The convention followed for a docstring is a multi-
line string where the first line starts with a capital
letter and ends with a dot.
• Then the second line is blank followed by any
detailed explanation starting from the third line.
function_docstring.py
def print_max(x, y):
'''Prints the maximum of two numbers.

The two values must be integers.'''


# convert to integers, if possible
x = int(x)
y = int(y)
if x > y:
print (x, 'is maximum‘)
else:
print (y, 'is maximum‘)
print_max(3, 5)
Modules
• Modules in Python are simply Python files with a .py
extension.
• A Python module can have a set of functions, classes
or variables defined and implemented.
• Module is a file which contains python functions ,
global variables etc. It is nothing but .py file which has
python executable code / statement.
• A Python module is just a .py file that contains Python
code, such as custom function and class(custom data
type) definitions, and sometimes variables.
• A standard installation includes a set of modules
called the standard library.
Packages
• A package is basically a directory with Python files and a
file with the name __init__.py.
• This means that every directory inside of the Python
path, which contains a file named __init__.py, will be
treated as a package by Python.
• It's possible to put several modules into a Package.

• Package is namespace which contains multiple


package/modules.
• It is a directory which contains a special file __init__.py
• Ex: Numpy, SciPy e.t.c.,
• https://www.geeksforgeeks.org/create-access-python-package/
• https://realpython.com/python-modules-packages/
• Library
• It is collection of various packages. There is no difference
between package and python library conceptually.
• Ex: Pandas (Python Data Analysis Library)
• Framework
• It is a collection of various libraries which architects the
code flow.
• Let’s take example of Django which has various in-built
libraries like Auth, user, database connector etc.
• A framework or application that is built and shipped as a
single unit.
• So, let's recap:
• library: collection of related functionality
• framework: Inversion of Control
• module: abstract interface with explicit exports and imports,
implementation and interface are separate, there may be
multiple implementations and the implementation is hidden.
• Too many heavy word ? Let’s recap in funny fashion :
• module = your fingers
• library = your hands
• framework = your body
• Writing packages
• They are simply directories, but with a twist.
• Each package in Python is a directory which MUST
contain a special file called __init__.py.
• This file can be empty, and it indicates that the
directory it contains is a Python package, so it can
be imported the same way a module can be
imported.
Byte-compiled .pyc files
• Importing a module is a relatively costly affair, so
Python does some tricks to make it faster.
• One way is to create byte-compiled files with the
extension .pyc which is an intermediate form that
Python transforms the program into (remember the
introduction section on how Python works?).
• This .pyc file is useful when you import the module
the next time from a different program - it will be
much faster since a portion of the processing
required in importing a module is already done.
• Also, these byte-compiled files are platform-
independent.
The from … import statement
• If you want to directly import the argv variable into
your program (to avoid typing the sys. everytime for
it), then you can use the from sys import argv
statement.
• In general, you should avoid using this statement
and use the import statement instead since your
program will avoid name clashes and will be more
readable.
• Example:
>>> from math import sqrt
>>> print ("Square root of 16 is", sqrt(16))
A module’s name attribute
• Every module has a name and statements in a
module can find out the name of their module.
• Whether the module is being run standalone or
being imported.
• As mentioned previously, when a module is
imported for the first time, the code it contains gets
executed.
• Using name attribute, We can make the module
behave in different ways
- it is being used by itself or
- being imported from another module.
Example (save as
module_using_name.py ):

if __name__ == '__main__':
print ('This program is being run by itself‘)
else:
print ('I am being imported from another module')
Making Your Own Modules

• Creating your own modules is easy, you’ve been


doing it all along! This is because every Python
program is also a module.
• You just have to make sure it has a .py extension.
• The following example should make it clear.
• Example (save as mymodule.py ):
def say_hi():
print ('Hi, this is mymodule speaking.‘)
__version__ = '0.1'
Another module (save as mymodule_demo.py ):

import mymodule
mymodule.say_hi()
print ('Version', mymodule.__version__)

Output:
$ python mymodule_demo.py
Hi, this is mymodule speaking.
Version 0.1
from..import syntax (save as
mymodule_demo2.py ):

from mymodule import say_hi, __version__


say_hi()
print ('Version', __version__)
The dir function
• The built-in dir function to list the identifiers that an
object defines.
• For example, for a module, the identifiers include
the functions, classes and variables defined in that
module.
• When you supply a module name to the `dir()`
function, it returns the list of the names defined in
that module.
• When no argument is applied to it, it returns the list
of names defined in the current module.
# get names of attributes for current module
>>> dir()
['__builtins__', '__doc__','__name__', '__package__']

$ python
>>> import sys
# get names of attributes in sys module
>>> dir(sys)
['__displayhook__', '__doc__',
'argv', 'builtin_module_names',
'version', 'version_info']
# only few entries shown here
• Note that the dir() function works on any object.
• For example, run dir(str) for the attributes of the str
(string) class.
• There is also a vars() 2 function which can
potentially give you the attributes and their values,
but it will not work for all cases.
Packages
• By now, you must have started observing the
hierarchy of organizing your programs.
• Variables usually go inside functions.
• Functions and global variables usually go inside
modules.
• What if you wanted to organize modules?
• That’s where packages come into the picture.
• Packages are just folders of modules with a special
init.py file that indicates to Python that this folder is
special because it contains Python modules.
Brief Tour of the Standard Library:
• re,
• math,
• datetime,
• time
• turtle, and
• tkinter.
Re https://docs.python.org/3/library/re.html
• Some people, when confronted with a problem, think, “I
know, I’ll use regular expressions.”
—Jamie Zawinski
• The re module contains support for regular expressions.
• If you’ve heard about regular expressions, you probably
know how powerful they are; if you haven’t, prepare to be
amazed.
• You should note, however, that mastering regular
expressions may be a bit tricky at first.
• The key is to learn about them a little bit at a time—just look
up the parts you need for a specific task.
• There is no point in memorizing it all up front.
• This section describes the main features of the re module
• Most of the standard escapes supported by
Python string literals are also accepted by the
regular expression parser:
• \a \b \f \n \r \t \u \U \v \x \\
• Python Regex: re.match(), re.search(), re.findall() with Example
• What is Regular Expression?
• A regular expression in a programming language is a special text string
used for describing a search pattern. It is extremely useful for
extracting information from text such as code, files, log, spreadsheets
or even documents.
• While using the regular expression the first thing is to recognize is that
everything is essentially a character, and we are writing patterns to
match a specific sequence of characters also referred as string. Ascii or
latin letters are those that are on your keyboards and Unicode is used
to match the foreign text. It includes digits and punctuation and all
special characters like $#@!%, etc.
• https://www.guru99.com/python-regular-expressions-complete-tutori
al.html
Python Datetime
• A date in Python is not a data type of its own, but
we can import a module named datetime to work
with dates as date objects.
>>> import datetime
>>> x = datetime.datetime.now()
>>> print(x)
Output: 2019-08-10 13:53:18.381749
The date contains year, month, day, hour, minute,
second, and microsecond.
>>> import datetime
>>> x = datetime.datetime(2020, 5, 17)
>>> print(x)

>>> x.year
>>> x.month
>>> x.day
>>>import datetime
>>> x = datetime.date.today()
>>> x.year
>>> x.month
>>> x.day
>>> import datetime
>>> print(dir(datetime))

You might also like