0% found this document useful (0 votes)
23 views70 pages

Unit 4

Python Programming

Uploaded by

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

Unit 4

Python Programming

Uploaded by

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

Unit-IV

By:
Prof. Mani Butwall,
Asst. Prof. (CSE)
Contents
• Functions
• Defining a function
• calling a function
• Types of functions
• Function Arguments
• Anonymous functions
• Keyword and Optional Parameters
• Local and global variables
• Defining recursion and its application
• programming through recursion
• Passing Collection to a function
Function
• A function is a set of statements that take inputs, do some
specific computation and produces output. The idea is to put
some commonly or repeatedly done task together and make a
function, so that instead of writing the same code again and
again for different inputs, we can call the function.
Python provides built-in functions like print(), etc. but we can
also create your own functions. These functions are called
user-defined functions.
• 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.
Syntax
• Above shown is a function definition that consists of the following
components.
• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function.
They are optional.
• A colon (:) to mark the end of the function header.
• Optional documentation string (docstring) to describe what the
function does.
• One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
• An optional return statement to return a value from the function.
Example
• def greet(name):
• """ This function greets to the person passed in as a parameter
"""
• print("Hello, " + name + ". Good morning!")

• How to call a function in python?


• Once we have defined a function, we can call it from another
function, program or even the Python prompt. To call a
function we simply type the function name with appropriate
parameters.
• greet(‘Mani')
• Output: Hello Mani Good morning!
Example
• # A simple Python function to check
• # whether x is even or odd
• def evenOdd( x ):
• if (x % 2 == 0):
• print "even"
• else:
• print "odd"

• # Driver code
• evenOdd(2)
• evenOdd(3)
• Output
• even
• odd
Docstrings
• Docstrings
• The first string after the function header is called the docstring
and is short for documentation string. It is briefly used to
explain 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 the __doc__ attribute of the function.
• print(greet.__doc__)
• (This function greets to the person passed in as a parameter)
Return Statement
• The return statement
• The return statement is used to exit a function and go back to
the place from where it was called.
• Syntax of return
• return [expression_list]
• This statement can contain an expression that gets evaluated
and the value is returned.
• If there is no expression in the statement or
the return statement itself is not present inside a function,
then the function will return the None object.
Example
• def absolute_value(num):
• """This function returns the absolute value of the entered
number"""
• if num >= 0:
• return num
• else:
• return -num

print(absolute_value(2))
print(absolute_value(-4))
How Function Works
Scope and Lifetime of Variables
• Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the
variable is recognized. Parameters and variables defined inside
a function are not visible from outside the function. Hence,
they have a local scope.
• The lifetime of a variable is the period throughout which the
variable exits in the memory. The lifetime of variables inside a
function is as long as the function executes.
• They are destroyed once we return from the function. Hence,
a function does not remember the value of a variable from its
previous calls.
• Here is an example to illustrate the scope of a variable inside a
function.
• Here, we can see that the value of x is 20 initially. Even though
the function my_func() changed the value of x to 10, it did not
affect the value outside the function.
• This is because the variable x inside the function is different
(local to the function) from the one outside. Although they
have the same names, they are two different variables with
different scopes.
• On the other hand, variables outside of the function are
visible from inside. They have a global scope.
• We can read these values from inside the function but cannot
change (write) them. In order to modify the value of variables
outside the function, they must be declared as global variables
using the keyword global.
Types of Functions
• Basically, we can divide functions into the following two types:
1. Built-in functions- Functions that are built into Python.
2. User-defined functions- Functions defined by the users
themselves.
Parameter Passing in Python
• 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 Java.
• # 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]
• 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]
• Another example to demonstrate that reference link is broken if we
assign a new value (inside the function).
• def myFun(x):

• # After below line link of x with previous
• # object gets broken. A new object is assigned
• # to x.
• x = 20

• # Driver Code (Note that lst is not modified
• # after function call.
• x = 10
• myFun(x);
• print(x)
• Output: 10
Default Arguments
• Default argument:
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
• # 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
• Keyword arguments:
The idea 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 =‘Mani', lastname =‘Butwall')
• student(lastname =‘Butwall', firstname =‘Mani')
• Output:(‘Mani', ‘Butwall') (‘Mani', ‘Butwall')
Variable Length Arguments
• Variable length arguments:
We can have both normal and keyword variable number of
arguments.
• # Python program to illustrate
• # *args for variable number of arguments
• def myFun(*argv):
• for arg in argv:
• print (arg)

• myFun('Hello', 'Welcome', 'to', ‘Python')
• Output:Hello Welcome to Python
Example
• # Python program to illustrate
• # *kargs for variable number of keyword arguments

• def myFun(**kwargs):
• for key, value in kwargs.items():
• print ("%s == %s" %(key, value))

• # Driver code
• myFun(first ='Geeks', mid ='for', last='Geeks')
• Output:last == Geeks mid == for first == Geeks
Anonymous Functions
• Anonymous functions: In Python, anonymous function means
that a function is without a name. As we already know that
def keyword is used to define the normal functions and the
lambda keyword is used to create anonymous functions.

• # Python code to illustrate cube of a number


• # using lambda function

• cube = lambda x: x*x*x
• print(cube(7))
• Output:343
Recursion
• What is recursion?
• Recursion is the process of defining something in terms of
itself.
• A physical world example would be to place two parallel
mirrors facing each other. Any object in between them would
be reflected recursively.
• Python Recursive Function
• In Python, we know that a function can call other functions. It
is even possible for the function to call itself. These types of
construct are termed as recursive functions.
• The following image shows the working of a recursive function
called recurse.
How Recursion Works
• Following is an example of a recursive function to find the
factorial of an integer.
• Factorial of a number is the product of all the integers from 1
to that number. For example, the factorial of 6 (denoted as 6!)
is 1*2*3*4*5*6 = 720.
Example
• In the above example, factorial() is a recursive function as it
calls itself.
• When we call this function with a positive integer, it will
recursively call itself by decreasing the number.
• Each function multiplies the number with the factorial of the
number below it until it is equal to one. This recursive call can
be explained in the following steps.
• Our recursion ends when the number reduces to 1. This is
called the base condition.
• Every recursive function must have a base condition that stops
the recursion or else the function calls itself infinitely.
• The Python interpreter limits the depths of recursion to help
avoid infinite recursions, resulting in stack overflows.
• By default, the maximum depth of recursion is 1000. If the
limit is crossed, it results in RecursionError. Let's look at one
such condition.
Exercise: Using recursion to determine whether a word is a
palindrome
• So here's how we can recursively determine whether a string
is a palindrome. If the first and last letters differ, then declare
that the string is not a palindrome. Otherwise, strip off the
first and last letters, and determine whether the string that
remains—the subproblem—is a palindrome.
• Declare the answer for the shorter string to be the answer for
the original string. Once you get down to a string with no
letters or just one letter, declare it to be a palindrome. Here's
a visualization of that for two words that we discussed:
Pseudocode
• If the string is made of no letters or just one letter, then it is a
palindrome.
• Otherwise, compare the first and last letters of the string.
• If the first and last letters differ, then the string is not a
palindrome.
• Otherwise, the first and last letters are the same. Strip them
from the string, and determine whether the string that
remains is a palindrome. Take the answer for this smaller
string and use it as the answer for the original string.
Advantages and Disadvantages
• Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-
problems using recursion.
• Sequence generation is easier with recursion than using some
nested iteration.
• Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow
through.
• Recursive calls are expensive (inefficient) as they take up a lot
of memory and time.
• Recursive functions are hard to debug.
Application of Recursion:
• The practical applications of recursion are near endless. Many
math functions cannot be expressed without its use. The more
famous ones are the Fibonacci sequence. It’s through math
functions that many software applications are built. Take for
example Candy Crush which uses them to generate
combinations of tiles.
• If you’re not familiar with Candy Crush (You should be) then
chess is another example of recursion in action. Almost all
searching algorithms today use a form of recursion as well. In
this day and age where information is key, recursion becomes
one of the most important methods in programming.
Lambda Function or Anonymous Function

• What are lambda functions in Python?


• In Python, an anonymous function is a function that is defined
without a name.
• While normal functions are defined using the def keyword in
Python, anonymous functions are defined using
the lambda keyword.
• Hence, anonymous functions are also called lambda functions.
• How to use lambda Functions in Python?
• A lambda function in python has the following syntax.
• Syntax of Lambda Function in python
• lambda arguments: expression
• Lambda functions can have any number of arguments but only
one expression. The expression is evaluated and returned.
Lambda functions can be used wherever function objects are
required.
• Example of Lambda Function in python
• Here is an example of lambda function that doubles the input
value.
• # Program to show the use of lambda functions
• double = lambda x: x * 2
• print(double(5))
• Output
• 10
• In the above program, lambda x: x * 2 is the lambda function.
Here x is the argument and x * 2 is the expression that gets
evaluated and returned.
• This function has no name. It returns a function object which
is assigned to the identifier double. We can now call it as a
normal function. The statement
• double = lambda x: x * 2
• is nearly the same as:
• def double(x):
• return x * 2
• Use of Lambda Function in python
• We use lambda functions when we require a nameless
function for a short period of time.
• In Python, we generally use it as an argument to a higher-
order function (a function that takes in other functions
as arguments). Lambda functions are used along with built-in
functions like filter(), map() etc.
Example use with map()
• The map() function in Python takes in a function and a list.
• The function is called with all the items in the list and a new
list is returned which contains items returned by that function
for each item.
• Here is an example use of map() function to double all the
items in a list.
• Program to double each item in a list using map()

• my_list = [1, 5, 4, 6, 8, 11, 3, 12]


• new_list = list(map(lambda x: x * 2 , my_list))
• print(new_list)
• [2, 10, 8, 12, 16, 22, 6, 24]
Example use with filter()
• The filter() function in Python takes in a function and a list as
arguments.
• The function is called with all the items in the list and a new
list is returned which contains items for which the function
evaluates to True.
• Here is an example use of filter() function to filter out only
even numbers from a list.
• Program to filter out only the even items from a list

• my_list = [1, 5, 4, 6, 8, 11, 3, 12]


• new_list = list(filter(lambda x: (x%2 == 0) , my_list))
• print(new_list) [4, 6, 8, 12]
Global Variables
• Global Variables
• In Python, a variable declared outside of the function or in
global scope is known as a global variable. This means that a
global variable can be accessed inside or outside of the
function.
• Let's see an example of how a global variable is created in
Python.
• In the above code, we created x as a global variable and
defined a foo() to print the global variable x. Finally, we call
the foo() which will print the value of x.
• What if you want to change the value of x inside a function?
• The output shows an error because Python treats x as a local
variable and x is also not defined inside foo().
Local Variables
• Local Variables
• A variable declared inside the function's body or in the local
scope is known as a local variable.
• The output shows an error because we are trying to access a
local variable y in a global scope whereas the local variable
only works inside foo() or local scope.
• In the above code, we declare x as a global and y as a local
variable in the foo(). Then, we use multiplication operator * to
modify the global variable x and we print both x and y.
• After calling the foo(), the value of x becomes global
global because we used the x * 2 to print two times global.
After that, we print the value of local variable y i.e local.
• In the above code, we used the same name x for both global
variable and local variable. We get a different result when we
print the same variable because the variable is declared in
both scopes, i.e. the local scope inside foo() and global scope
outside foo().
• When we print the variable inside foo() it outputs local x: 10.
This is called the local scope of the variable.
• Similarly, when we print the variable outside the foo(), it
outputs global x: 5. This is called the global scope of the
variable.
Non Local Variables
• Nonlocal Variables
• Nonlocal variables are used in nested functions whose local
scope is not defined. This means that the variable can be
neither in the local nor the global scope.
• Let's see an example of how a nonlocal variable is used in
Python.
• We use nonlocal keywords to create nonlocal variables.
• In the above code, there is a nested inner() function. We
use nonlocal keywords to create a nonlocal variable.
The inner() function is defined in the scope of another
function outer().
• Note : If we change the value of a nonlocal variable, the
changes appear in the local variable.
Global Keyword
• What is the global keyword
• In Python, global keyword allows you to modify the variable outside
of the current scope. It is used to create a global variable and make
changes to the variable in a local context.
• Rules of global Keyword
• The basic rules for global keyword in Python are:
• When we create a variable inside a function, it is local by default.
• When we define a variable outside of a function, it is global by
default. You don't have to use global keyword.
• We use global keyword to read and write a global variable inside a
function.
• Use of global keyword outside a function has no effect.
• In the above program, we define c as a global keyword inside
the add() function.
• Then, we increment the variable c by 1, i.e c = c + 2. After that,
we call the add() function. Finally, we print the global
variable c.
• As we can see, change also occurred on the global variable
outside the function, c = 2.

• Output:

• Before calling bar: 20


• Calling bar now
• After calling bar: 20
• x in main: 25
• In the above program, we declared a global variable inside the
nested function bar(). Inside foo() function, x has no effect of
the global keyword.
• Before and after calling bar(), the variable x takes the value of
local variable i.e x = 20. Outside of the foo() function, the
variable x will take value defined in the bar() function i.e x =
25. This is because we have used global keyword in x to create
global variable inside the bar() function (local scope).
• If we make any changes inside the bar() function, the changes
appear outside the local scope, i.e. foo().
Passing Collection to a Function
• In Python, we can also pass a collection as a list, tuple, set, or
dictionary as a parameter to a function.
• Here the changes made to the collection also affect the
collection outside the function.
• But if it is redefined then the collection outside the function
does not gets affected. Because the redefined collection
becomes local for the function.

You might also like