You are on page 1of 31

SALWAN PUBLIC SCHOOL,MAYUR VIHAR-III

CLASS – XII
COMPUTER SCIENCE

FUNCTIONS IN PYTHON
Functions are the subprograms that perform specific task. Functions are
the small modules. Reusing the same code is required many times
within a same program. Functions help us to do so. We write the things
we have to do repeatedly in a function then call it where ever required.
Through functions we implement ‘Modularity’ feature of modern
programming languages.
Advantages of Using functions:
1. Program development made easy and fast: Work can be divided
among project members thus implementation can be completed
fast.
2. Program testing becomes easy: Easy to locate and isolate a faulty
function for further investigation
3. Code sharing becomes possible: A function may be used later by
many other programs this means that a python programmer can
use function written by others, instead of starting over from
scratch.
4. Code re-usability increases: A function can be used to keep away
from rewriting the same block of codes which we are going use
two or more locations in a program. This is especially useful if the
code involved is long or complicated.
5. Increases program readability: It makes possible top down
modular programming. In this style of programming, the high level
logic of the overall problem is solved first while the details of each
lower level functions are addressed later. The length of the source
program can be reduced by using functions at appropriate places.
6. Function facilitates procedural abstraction: Once a function is
written, it serves as a black box. All that a programmer would have
to know to invoke a function would be to know its name, and the
parameters that it expects.

1/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


7. Functions facilitate the factoring of code: A function can be called
in other functions and programs

Types of Functions:
We can divide functions into the following three types:

1. Library Functions in Python: These functions are already built in


the library of python. For example: type( ), len( ), input( ), int(),
float() etc.

2. Functions defined in modules: These functions are defined in


particular modules. When you want to use these functions in
program, you have to import the corresponding module of that
function. Example: import math module and then use sin(), sqrt()…
3. User Defined Functions: The functions which are defined by the
user are called user defined functions.

User Defined Functions


Syntax of a UDF:
def function_name(parameters):
"""docstring"""
statement(s)
A function definition consists of the following components:
1. Keyword ‘def’ that marks the start of the function header.
2. A function name to uniquely identify the function. 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 the function header.
5. Optional documentation string (docstring) to describe what the
function does.

2/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


6. One or more valid python statements that make up the function
body. Statements must have the same indentation level (usually 4
spaces).
7. 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!")

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:

3/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


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.
def add2(a,b):
c=a+b
return c
We may have more than one return statements but, they should be
conditional like:
def absValue(num):
"""This function returns the absolute
value of the entered number"""
if num >= 0:
return num
else:
return -num

Calling/Invoking a function
To call a function we simply type the function name with appropriate
parameters. Once we have defined a function, we can call it from:
● Another function
● Program
● Python prompt

Working of a function:

4/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Parameters/Arguments:
Actual parameters are those arguments that appear in function call
statement and formal parameters appear in function definition.
def add2(a,b): # Formal parameters
c=a+b
return c
x=int(input(“Enter first number”))
y=int(input(“Enter second number”))
z=add2(x,y) # Actual parameters
print(z)
● Actual parameters in Python can be one of these value types:
● Literals
● Variables
● Expressions
● Formal parameters in Python have to be labels/variables since
they have to hold incoming values.
Flow of Execution:
● Program execution begins with first statement of __main__
function/block and then branches to the function, when the
function call is encountered.
● After executing function, it jumps back to next statement of
__main__ block.
__main__ block is defined internally by python and can be checked
by programmer through variable __name__ .
__name__ (A Special variable) in Python
Since there is no main() function in Python, when the command to
run a python program is given to the interpreter, the code that is at
level 0 indentation is to be executed. However, before doing that, it
will define a few special variables. __name__ is one such special

5/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


variable. If the source file is executed as the main program, the
interpreter sets the __name__ variable to have a value “__main__”. If
this file is being imported from another module, __name__ will be set
to the module’s name.
__name__ is a built-in variable which evaluates to the name of the
current module. Thus it can be used to check whether the current
script is being run on its own or being imported somewhere else by
combining it with if statement, as shown below.
File1:
if __name__ == "__main__":
print("File1 is being run directly")
else:
print("File1 is being imported")
File2:
import file1
if __name__ == "__main__":
print("File2 is being run directly")
else:
print("File2 is being imported")
Special Tip:
Dunder or magic methods in Python are the methods having two
prefix and suffix underscores in the method name. A dunder variable
is a variable that Python has defined so that it can use it in a “Special
way”. This Special way depends on the variable that is being used.
Dunder here means “Double Under (Underscores)”. These are
commonly used for operator overloading.
Different ways we can define functions:
1. No return type no parameter

def addUs():

6/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


n=int(input("Enter 1st number"))
m=int(input("Enter 2nd number"))
print(n+m)

# calculate sum
addUs()

Exercise : Write a program using UDF to print a pyramid of


stars of 7 lines.

2. No return type with parameter

def addUs(n,m):
print(n+m)

# calculate sum
x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
addUs(x,y)

Exercise : Write a program using UDF to accept a number and


print its table with proper format.

3. With return type but no parameter:

def addUs():
n=int(input("Enter 1st number"))
m=int(input("Enter 2nd number"))
return (n+m)

# calculate sum
c=addUs()
print(c)

7/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Exercise : Write a program using UDF to return the number of
stars in the pyramid generated with 7 lines of stars.

4. With return type and with parameter

#Example1
def addUs(n,m):
return(n+m)

# calculate sum
x=int(input("Enter 1st number"))
y=int(input("Enter 2nd number"))
z=addUs(x,y)
print(z)

#Example2
def power(m,n):
prod=1
for i in range(1,n+1):
prod=prod*m
return prod
# calculate value of sqr(x)-sqr(y)
x=int(input("Enter x"))
y=int(input("Enter y"))
z=power(x,2)-power(y,2)
print(z)

Exercise :
1. Write a program using UDF to return the factorial of a
number and use the same in generating the sum of
following series:
x/3! + x3/5! + x5/7! ….. xn/m!

8/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


2. Write a program using UDF to check whether the number is
prime or not. Check the same for n numbers entered in the
program till user wishes.

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.

Global and Local Variables in Python


Global variables are the one that are defined and declared outside a
function and we need to use them inside a function.
Local Variables are those variables that are defined in a block and the
scope is in that block only. It is not accessible outside the block. Such a
variable is called a local variable. Formal parameter identifiers also
behave as local variables.

9/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


# This function uses global variable str1
def func():
print(str1)

# Global scope
str1 = "I love programming"
func()
Output: I love programming
The variable str1 is defined as the string before we call the function
func(). The only statement in func() is the “print (str1)” statement. As
there is no local str1, the value from the global str1 will be used.

Exercise :
Write a program using UDF to return reverse of a number. (Use global
number in place of parameter)

# This function uses local variable str1


def func():
str1=”Hello” # local str1

10/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


print(str1)

# Global scope
str1 = "I love programming" # global str1
func()
Output: Hello
If a variable with the same name is defined inside the scope of function
as well then it will use the value given inside the function only and not
the global value.

# This function is trying to use local variable and global variable


with same name
def func():
print(str1) # global str1 hidden , local not yet defined
str1=”Hello”
print(str1)

# Global scope
str1 = "I love programming"
func()
Output: UnboundLocalError: local variable 'str1' referenced before
assignment
First solution to the above problem is use of globals() function
def func():
print(globals()['str1'])
str1="Hello"
print(str1)

11/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


# Global scope
str1 = "I love programming"
func()
print(str1)

Output:
I love programming
Hello
I love programming
Second solution to the above problem is Global keyword
Because, Only accessing of the global variables are allowed in the
function, modification is not allowed.
Example :
c = 1 # global variable
def add():
c = c + 2 # increment c by 2
print(c)
add()
When we run the above program, the output shows an error. This is
because we can only access the global variable but cannot modify it from
inside the function.
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.
Any variable can be changed or created inside of a function is local if it
hasn’t been declared as a global variable. To tell Python, that we want

12/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


to use the global variable, we have to use the keyword “global”, as can
be seen in the following example:
def func():
global str1
print("Global String",str1)
str1="Hello"
print("Local String",str1)

# Global scope
str1 = "I love programming"
func()
print("Global String",str1)

Output:
Global String I love programming
Local String Hello
Global String Hello

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 be able to write in a global variable
inside a function.
● Use of global keyword outside a function has no effect.

Difference between global and globals():

13/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Use of global variable will make Python understand that the local
variable is the same global variable that was defined in a global context.
Where as, globals() will fetch the value of global variable from the
dictionary maintained by Python. The dictionary's keys are the names of
objects, and the dictionary's values are the associated object's values.
Also, Once a variable is declared as global in a function, you cannot
undo the statement and function will always refer to this global variable
and local variable cannot be created of the same name.
Tip : For good programming practice , the use of global statement is
always discouraged as with this programmers tend to lose the control
over variables and their scopes.
LEGB Rule :
LEGB stands for Local, Enclosing, Global, Built-in. These are the possible
scopes of a variable in Python. We also use these words to describe
namespaces, which store variable names and values and are how Python
determines scope.

The order Local, Enclosing, Global, Built-in is the order of precedence for
scope resolution. That means Python searches for the value of a name in
each of these namespaces in turn. Namespaces are how Python keeps
track of variables. In a namespace, an object name maps to the object
itself. Namespaces keep track of all objects, not just user-defined
variables. For example, functions are also objects in Python. A namespace
can contain function names that map to the contents of those functions.
Namespaces are created and destroyed as a program runs.
Exercise:
Write a menu driven program using UDFs to :
a. Calculate square of a number
b. Cube of a number
c. Check whether number is prime
d. Check whether number is Armstrong
e. Return reverse of a number if integer.

14/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Creation of Global Variables to be used across Python modules
In Python, we can create a single module to hold global variables and
share information across Python modules within the same program.
Here is how we can share global variables across the python modules.

Create a myGlobal.py file, to store global variables

a = 10
b = 20
Create a test.py file, to test availability changes in value
import myGlobal
print(myGlobal.a)
print(myGlobal.b)
When we run the test.py file, the output will be
10
20

Types of Parameters/Formal arguments:

1. Positional
2. Default
3. Keyword
4. Variable length/arbitrary

Positional arguments:

When the function call statement should match the number and order of
parameters as defined in the function definition, it is called as positional
arguments. The process may also be called as required or mandatory
arguments.

If number of formal arguments and actual arguments differs, then Python


will raise an error.

def ci(p,t,r): #function definition


am=p*(pow(1+r/100,t))
i=am-p
return i
p1=float(input("Enter principal"))

15/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


t1=float(input("Enter time"))
r1=float(input("Enter rate"))
res=ci(p1,t1,r1) # function call
print(res)
In the above function call, number of arguments matches with the number
of received values.
Default Arguments

Function arguments can have default values in Python. We can provide a


default value to an argument by using the assignment operator (=). Here is
an example.

Example 1:
def Fibonacci (n=10):
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if n <= 0:
print("Please enter a positive integer")
elif n == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
nterms = int(input("How many terms? "))
fibonacci(nterms) # using
fibonacci() # using default parameter

Output :
How many terms? 5
Fibonacci sequence:

16/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


0 1 1 2 3

Fibonacci sequence:
0 1 1 2 3 5 8 13 21 34

Example 2

def area(l,b=5):
return l*b
ar=area(5,10)
print(ar)
ar=area(5)
print(ar)

Output:
50
25

Example 3
def area(l=5,b):
return l*b
ar=area(5,10)
print(ar)
ar=area(5)
print(ar)
Output:
Error - Non default argument follows default argument
IMPORTANT TIP:
In a function header, any parameter cannot have a default value
unless all parameters appearing on it’s right have their default values.
Purpose of Default arguments:
1. Used in situations where some parameters always have the same
value.
2. Greater flexibility to the programmer.
3. It combines similar functions into one.

Exercise :

17/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


1. Recall some library functions which take default arguments/values.
2. Write a menu driven program to calculate Compound interest using a
single UDF :
1. Calculate CI using customized values
2. Calculate CI using 5% as fixed rate
3. Calculate CI using 5% as fixed rate and 3 years as fixed period.
Solution 2.
def ci(p,t=3,r=5):
am=p*(pow(1+r/100,t))
i=am-p
return i
p1=float(input("Enter principal"))
t1=float(input("Enter time"))
r1=float(input("Enter rate"))
ch=0
while ch<4:
print("1.Custom Values\n2.Fixed rate 5%\n3. Fixed rate 5% and time 3
yrs.\n4.Exit\n")
ch=int(input("enter 1-2-3 choice\n"))
if ch==1:
res=ci(p1,t1,r1)
elif ch==2:
res=ci(p1,t1)
elif ch==3:
res=ci(p1)
print(res)

Exercise : Modify the above program with one more option using all
keyword parameters.

Keyword Arguments
The default arguments give you the flexibility to specify the default value to
the right most parameters so, that they can be skipped in the function call,
if needed. But, still we may not change the order of the parameters in the
function call statement. We have to remember the correct order while
giving the arguments.
Using keyword parameters is an alternative way to make function calls in
Python. The definition of the function doesn't change. But Python offers a

18/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


way of writing function calls where it provides a useful mechanism of using
the name of the formal argument as a keyword in function call. The
function will process the arguments even if they are not in the order
provided in the definition, because, while calling, values are explicitly
assigned to them.

An example:
def simpleInt(p,t,r):
return (p*t*r)/100
print(simpleInt(r=10,t=2,p=5000)
print(simpleInt(t=2,p=5000, r=10)
print(simpleInt(p=5000,r=10,t=2)
Output:
1000.0
1000.0
1000.0

Multiple arguments (Mixed arguments)


Python allows you to combine multiple arguments in a function call
statement using positional, default and keyword. But there are some
restrictions:
1. An argument list must first use positional arguments followed by any
keyword argument.
2. Should not specify a value for an argument more than once.
3. Avoid providing multiple values for any argument.
4. Use of correct names in keyword arguments.
5. Values for positional arguments should not be missing.
Example
def sumsub(a, b, c=0, d=0):
return a - b + c - d

print(sumsub(12, 4))
But if, we want to give a custom value
print(sumsub(42, 15, d=10)) # skipped c which will take default value
8
17
Keyword parameters can only be those, which are not used as
positional arguments. We can see the benefit in the example. If we

19/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


hadn't had keyword parameters, the second call to function would have
needed all four arguments, even though the c needs just the default value.
We can pass either use either positional arguments or keyword
arguments, not both at the same time. If you try to do you will get syntax
Error The positional argument follows keyword argument

Exercise:
I. Considering the above example, identify whether following calls
are valid or not:
1. sumsub(c=5,a=2,d=9,b=7) # -9
2. sumsub(a=5,b=2) #3
3. sumsub(a=2,d=9,b=7) # -14
4. sumsub(c=2,9,2) #positional argument
follows keyword argument
5. sumsub(10,a=5,c=2,d=7) # multiple values for a
6. sumsub(10,5,c=2,d1=7) # undefined variable
7. sumsub(10,c=2,d=7) # required parameter
missing
II. Write a program using function to find HCF or GCD. Use :
1. Only positional arguments
2. One value (5) as default argument
3. Only keyword arguments.

Variable length arguments/ Python Arbitrary Arguments

Sometimes, we do not know in advance the number of arguments that will


be passed into a function. Python allows us to handle this kind of situation
through function calls with an arbitrary number of arguments.

In the function definition, we use an asterisk (*) before the parameter name
to denote this kind of argument. Here is an example.

def avg(*n):
c=0
sum=0
for i in n:
sum+=i

20/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


c+=1
return sum/c

print(avg(3,5,8,1,12)) # 5.8
print(avg(10,20,15,20,15,10)) #15.0

Here, we have called the function with multiple arguments. These


arguments get wrapped up into a tuple before being passed into the
function. Inside the function, we use a for loop to retrieve all the
arguments back.
Example :
def myfun(*name):
print('Hello', name)
return name
myfun("aa","bb") #Hello ('aa', 'bb')
t=myfun("aa","bb") # if we use “return name”
print(t) # ('aa', 'bb')

Exercise :
1. WAP using function taking n number of parameters and finding
the minimum entered value.
2. WAP using function taking n number of marks of the students and
finding the count of failures.
3. WAP using function taking n number of names and find the name
with largest length.

Returning Multiple Values:

21/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Unlike other programming languages, Python allows you to return more
than one value from the function. Few things to be considered are:
1. Using comma operator while returning values in the return
statement in function definition
Example :
def calc(a,b):
return a+b,a-b,a*b,a/b
2. Function call statement may be used to receive or use the
returned values in one of the following ways:
a. Use a tuple variable to return the values
calc(10,5) # (15, 5, 50, 2.0)
a=calc(20,10)
print(a) # (30, 10, 200, 2.0)
type(a) # <class 'tuple'>
b. Using unpacking of the tuple
x,y,z,w=calc(30,10)
print(x,y,z,w) # 40 20 300 3.0

Exercise :

1. WAP using function which takes radius as input and returns area,
circumference and diameter.
2. WAP using function to take a number as input and return first four
factors of that number.
Python Lambda/ Anonymous function
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. 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. It returns a function object which is
assigned to an identifier.

22/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Syntax :
lambda arguments: expression

Example 1:
num = lambda a, b : a * b
print(num(5, 6))
Example 2:
func1=lambda a:3.14*a*a
print(func1(5))

Purpose of Lambda Functions


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(). Filter() takes
first parameter as a function and other as a list to filter and return the
items which satisfy the criteria laid by function.
l1 = [1, 5, 6, 8, 10, 15, 12]
l2 = list(filter(lambda x: (x%5 == 0) , l1))
>>> print(l2)
[5, 10, 15]

Or
List Comprehension method:
l1 = [1, 5, 6, 8, 10, 15, 12]
l2=[x for x in l1 if x%5==0]
>>> print(l2)
[5, 10, 15]

Exercise:

23/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


1. WAP using lambda functions to square a given number
2. WAP using lambda function to convert Celsius temp into
Fahrenheit
3. WAP using lambda function to filter multiples of 15 from a list
consisting of integers from 1 to 100

Mutable/Immutable properties of data objects with respect to


functions

Everything in Python is an object, and every object in Python can either


be mutable or immutable. Since everything in Python is an Object, every
variable holds an object instance. When an object is initiated, it is
assigned a unique object id. Its type is defined at runtime and once set
can never change, however its state can be changed if it is mutable.
Mutable objects: list, dict, set
Immutable objects: int, float, complex, string, tuple

How objects are passed to Functions:


1. Pass by value(Immutable)
2. Pass by reference (Mutable)

Pass by Value:

def updateNumber(n):
print(id(n))
n += 10
print(id(n))
b=5
print(id(b))
updateNumber(b)
print(b)
print(id(b))

OUTPUT
1691040064

24/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


1691040064
1691040224
5
1691040064

#In above function value of variable b is not being changed because it is


immutable that’s why it is behaving like pass by value

Call by reference

def updateList(list1):
print(id(list1))
list1 += [10]
print(id(list1))
n = [50, 60]
print(id(n))
updateList(n)
print(n)
print(id(n))
OUTPUT
34122928
34122928
34122928
[50, 60, 10]
34122928
#In above function list1 an object is being passed and its contents are
changing because it is mutable that’s why it is behaving like pass by
reference.

Exercise:

25/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


1. WAP using function to check whether a passed string is
palindrome or not.
2. WAP using a single function ‘convert’ to convert Celsius to
Fahrenheit and vice versa, according to parameters passed.

LEGB Rule:

1. The local scope or function scope is a Python scope created at


function calls. Every time you call a function, you’re also creating a
new local scope. On the other hand, you can think of each def
statement and lambda expression as a blueprint for new local
scopes. These local scopes will come into existence whenever
you call the function at hand.
def square(base):
result = base ** 2
print(f'The square of {base} is: {result}')
# print("the square of {} is:{}".format(base,result))

2. Enclosing (or non local) scope is a special scope that only exists
for nested functions. If the local scope is an inner or nested
function, then the enclosing scope is the scope of the outer or
enclosing function. This scope contains the names that you define
in the enclosing function. The names in the enclosing scope are
visible from the code of the inner and enclosing functions.
def func1():
a=10
def func2():
print(a)
func2()
print(a)
func1()
func2() #error
3. Global (or module) scope is the top-most scope in a Python
program, script, or module. This Python scope contains all of the

26/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


names that you define at the top level of a program or a module.
Names in this Python scope are visible from everywhere in your
code.
a=5
def func1():
print(a)
print(a)
4. Built-in scope is a special Python scope that’s created or loaded
whenever you run a script or open an interactive session. This
scope contains names such as keywords, functions, exceptions,
and other attributes that are built into Python. Names in this
Python scope are also available from everywhere in your code. It’s
automatically loaded by Python when you run a program or script.
__name__ is a built-in variable which evaluates to the name of the
current module

Check your Progress!


Output Questions:

1. def add(i):
if(i*3%2==0):
i*=i
else:
i*=4
return i
a=add(10)
print(a)

2. import math
def area(r):
return math.pi*r*r
a=int(area(10))
print(a)

3.def fun1(x, y):


x=x+y

27/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


y=x-y
x=x-y
a=5
b=3
fun1(a,b)
print('a=',a)
print('b=',b)

4. def div5(n):
if n%5==0:
return n*5
else:
return n+5
def output(m=5):
for i in range(0,m):
print(div5(i),'@',end=" ")
print('\n')
output(7)
output()
output(3)

5.def sum(*n):
total=0
for i in n:
total+=i
print('Sum=', total)
sum()
sum(5)
sum(10,20,30)

6. def func(b):
global x
print('Global x=', x)
y=x+b
x=7
z=x-b

28/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


print('Local x = ',x)
print('y = ',y)
print('z = ',z)
x=5
func(10)

7. def func(x,y=100):
temp = x + y
x += temp
if(y!=200):
print(temp,x,x)
a=20
b=10
func(b)
print(a,b)
func(a,b)
print(a,b)

8. def get(x,y,z):
x+=y
y-=1
z*=(x-y)
print(x,'#',y,'#',z)
def put(z,y,x):
x*=y
y+=1
z*=(x+y)
print(x,'$',y,'$',z)
a=10
b=20
c=5
put(a,c,b)
get(b,c,a)
put(a,b,c)
get(a,c,b)

29/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


Error based questions:

1. def in(x,y):
x=x + y
print(x.y)
x*=y
print(x**y)

2. def get(x=10,y):
x=x+y
print(x,\n,y)

3. // Program to compute result


def res():
eng = 56
math = 40
sci = 60
if eng<=35 || math<=35 || sci=35
print('Not Qualified')
else:
print("Qualified")

4. a=5, b=10
def swap(x,y):
x=a+b
y=x-y
x=x-y
swap(a)
swap(15,34)
swap(b)
swap(a,b)

5. def cal_dis(qty,rate=50,dis_rate): #discount rate = 5%


bil_amt = (qty*rate)*dis_rate
print(bil_amt)
caldis(10)

30/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3


cal_dis(10,50,0.05)

Theory based questions:

1. What is a function?
2. Why programmer need functions in python programming?
3. How to create a function in python? Explain in detail.
4. What are the parts of functions? Explain with suitable example.
5. How to call a function? Write steps.
6. What is the difference between global and globals()?
7. What is Lambda function? Explain the purpose.
8. Illustrate flow of execution in function call statement.
9. Write and explain types of functions supported by python.
10. Write the ways of import module in python program.
11. Differentiate between parameters and arguments.
12. What are the arguments supported by python? Explain each of
them with suitable example.
13. What is local variable and global variable? Explain with example.
14. What are dunder variables? Explain with the help of example.

31/CS-FUNCTIONS/POOJA DHINGRA/SALWAN PUBLIC SCHOOL,MV-3

You might also like