CH-3 Notes and Questions-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

CHAPTER- 3rd

WORKING WITH FUNCTIONS

INTRODUCTION

Functions in Python is a block of statements that return the


specific task. The idea is to put some commonly or repeatedly
done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we
can do the function calls to reuse code contained in it over and
over again.

Some Benefits of Using Functions

 Reducing duplication of code


 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding

Python Function Declaration


The syntax to declare a function is:
UNDERSTANDING FUNCTIONS

In order to understand what a function is, in terms of a


programming language, read the following lines carefully.

You have worked with polynomials in Mathematics. Say we have


following polynomial:
2x2

For x=1, it will give result as 2×12=2


For x=2, it will give result as 2x22=8
For x=3, it will give result as 2x3² = 18 and so on.

Now, if we represent above polynomial as somewhat like


f(x) = 2x²

Then we can say (from above calculations) that


f(1)=2 ...(1)
f(2)=8 ...(2)
f(3)=18 ...(3)

For instance, above mentioned mathematical function f(x) can


be written in Python like this:

def calcSomething (x):


r=2*x**2
return r

where:
 def means a function definition is starting
 identifier following 'def' is the name of the function, i.e.,
here the function name is calcSomething
 the variables/identifiers inside the parentheses are the
arguments or parameters (values given to function),
i.e., here x is the argument to function calcSomething.
 there is a colon at the end of def line, meaning it
requires a block
 the statements indented below the function, (i.e., block
below def line) define the functionality (working) of the
function. This block is also called body-of-the-
function.
Here, there are two statements in the body of function
calcSomething
 The return statement returns the computed result.

Calling/Invoking/Using a Function

To use a function that has been defined earlier, you need to write
a function call statement in Python. A function call statement
takes the following form:

<function-name>(<value-to-be-passed-to-argument>)

For example, if we want to call the function calcSomething()


defined above, our function call statement will be like:
calcSomething(5) #value 5 is being sent as argument

Another function call for the same function, could be like:


a =7
calcSomething(a) #this time variable a is being sent as
argument

Carefully notice that number of values being passed is same as


number of parameters.
Consider one more function definition given below:
def cube(x):
r = x** 3 # cube of value in x
return r # return the computed value

As you can make out that the above function's name is cube()
and it takes one argument. Now its function call statement(s)
would be like the ones shown below:

(i) Passing literals as argument in function call


cube(4) # it would pass value as 4 to argument x

(ii) Passing variable as argument in function call


num=10
cube(num) # it would pass value as variable num to
argument x

(iii) taking input and passing the input as argument in function


call
mynum int(input("Enter a number :"))
cube (mynum) # it would pass value as variable
mynum to argument x

(iv) using function call inside another statement


print (cube(3)) # cube(3) will first get the computed result

(v) using function call inside expression


doubleofcube = 2*cube(6) # function call’s result will be
then printed
Python Function Types

Python comes preloaded with many that you can use as per your
needs. You can even create new functions. Broadly, Python
functions can belong to one of the following three categories:

1. Built-in functions: These are pre-defined functions and are


always available for use. You have used some of them – (len),
type(), int(), input() etc.
2. Functions defined in modules: These functions are pre-
defined in particular modules and can only be used when the
corresponding module is imported.
For example, if you want to use pre-defined functions inside a
module, say sin(), you need to first import the module math (that
contains definition of sin()) in your program.
3. User defined functions: These are defined by the programmer.
As programmers you can create your own functions.
In this chapter, you will learn to write your own Python functions
and use them in your programs.

DEFINING FUNCTION IN PYTHON


A function once defined can be invoked as many times as
needed by using its name, without having to rewrite its code.
The syntax to declare a function is:

def function_name(arguments):
# function body
return
Here,

 def - keyword used to declare a function


 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function
Let's see an example,
def test():
print('Hello World!')

Or
def sum(x,y):
s = x+y
return s

Here,
we have created a function named test(). It simply prints the
text Hello World!.

Structure of a Python Program using Functions


Example:
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return

hello()
Here,
 This code defines a function called hello().
 When the function is called, it prompts the user to enter their
name using the input() function and stores the input as a
string in the variable name.
 The code then checks if name is not an empty string using
the if statement.
 If name is not empty, the function prints "Hello" followed by
the value of name.
 If name is empty, the function prints "Hello World".
 Finally, the function returns None as there is no explicit return
value specified.
 When the code is run, the hello() function is called,
prompting the user to enter their name and printing the
appropriate greeting based on the input.

Flow of Execution In a Function Call

In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which
is called the flow of execution.
Execution always begins at the first statement of the program.
Statements are executed one at a time, in order from top to
bottom.
unction definitions do not alter the flow of execution of the
program, but remember that statements inside the function are
not executed until the function is called.

Example:
def firstPrint():
print("First")
secondPrint()

def secondPrint():
print("Second")
thirdPrint()

def thirdPrint():
print("Third")

firstPrint()
Arguments and Parameters

Parameters: A parameter is the variable defined within the


parentheses during function definition. Simply they are written
when we declare a function.
Example: # Here a,b are the parameters
def sum(a,b):
print(a+b)

sum(1,2)

Arguments: An argument is a value that is passed to a function


when it is called. It might be a variable, value or object passed
to a function or method as input. They are written when we are
calling the function.
Example: def sum(a,b):
print(a+b)

# Here the values 1,2 are arguments


sum(1,2)

An argument is a variable (which contains data) or a parameter


that is sent to the function as input. Before getting into argument
types, let’s get familiar with words formal and actual arguments.
Formal arguments: When a function is defined it (may) has
(have) some parameters within the parentheses. These
parameters, which receive the values sent from the function call,
are called formal arguments.
Actual arguments: The parameters which we use in the function
call or the parameters which we use to send the values/data
during the function call are called actual arguments
Example: formal and actual function arguments in python
def sum(a, b):
c = a + b # a and b are formal arguments
print(c)
# call the function
x = 10
y = 15
sum(x, y) # x and y are actual arguments

Types of formal arguments:


1. Positional arguments (Required arguments)
2. Default arguments
3. Keyword arguments (named arguments)

Positional arguments: Positional arguments are those arguments


where values get assigned to the arguments by their position when
the function is called. For example, the 1st positional argument must
be 1st when the function is called. The 2nd positional argument needs
to be 2nd when the function is called, etc.
Example: Program to subtract 2 numbers using positional arguments.

def add(a, b):


print(a - b)

add(50, 10) # Output 40


add(10, 50) # Output -40
Default Arguments: In a function, arguments can have default values.
We assign default values to the argument using the ‘=’
(assignment) operator at the time of function definition. You can
define a function with any number of default arguments.
The default value of an argument will be used inside a function if we
do not pass a value to that argument at the time of the function call.
Due to this, the default arguments become optional during the
function call.

Example:

# function with 2 keyword arguments grade and school


def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)

# without passing grade and school


# Passing only the mandatory arguments
student('Jon', 12)

# Output: Student Details: Jon 12 Five ABC School

Passing one of the default arguments:


If you pass values of the grade and school arguments while calling a
function, then those values are used instead of default values.

Example:

# function with 2 keyword arguments grade and school


def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)

# not passing a school value (default value is used)


# six is assigned to grade
student('Kelly', 12, 'Six')

# passign all arguments


student('Jessa', 12, 'Seven', 'XYZ School')

Output:
Student Details: Kelly 12 Six ABC School
Student Details: Jessa 12 Seven XYZ School
Keyword Arguments: Usually, at the time of the function call, values
get assigned to the arguments according to their position. So we must
pass values in the same sequence defined in a function definition.
For example, when we call student('Jon', 12, 'Five', 'ABC School'), the
value “Jon” gets assigned to the argument name, and similarly, 12
to age and so on as per the sequence.

Keyword arguments are those arguments where values get assigned


to the arguments by their keyword (name) when the function is
called. It is preceded by the variable name and an (=) assignment
operator. The Keyword Argument is also called a named argument.

Example:

# function with 2 keyword arguments


def student(name, age):
print('Student Details:', name, age)

# default function call


student('Jessa', 14)

# both keyword arguments


student(name='Jon', age=12)

# 1 positional and 1 keyword


student('Donald', age=13)

Output:
Student Details: Jessa 14
Student Details: Jon 12
Student Details: Donald 13

RETURNING VALUES FROM FUNCTIONS


Functions in Python may or may not return a value. You already know
about it. There can be broadly two types of functions in Python:
 Functions returning some value (non-void functions)
 Functions not returning any value (void functions)

1. Functions returning some value (Non-void functions)


The functions that return some computed result in terms of a value,
fall in this category. The computed value is returned using return
statement as per syntax:
return <value>
Example-
def sum (x, y):
s=x+y
return s
a= sum(5, 10)
print(a)

2. Functions not returning any value (Void functions)


The functions that perform some action or do some work but do not
return any computed value or final value to the caller are called void
functions. A void function may or may not have a return statement.
Example-
def greet():
print(“Hello”)
a = greet()
print(a)

SCOPE OF A VARIABLES

In programming languages, variables need to be defined before


using them. These variables can only be accessed in the area where
they are defined, this is called scope. You can think of this as a block
where you can access variables.

1. Local Scope
Local scope variables can only be accessed within its block.
Example.
a = 10
def function():
print(“Hello”)
b = 20
function()
print(a)
print(b)
Output:
Hello
10
Traceback (most recent call last):
File “main.py”, line 7, in <module print(b)
NameError: name ‘b’ is not defined
In the above example, we see that Python prints the value of variable
a but it cannot find variable b. This is because b was defined as a local
scope in the function so, we cannot access the variable outside the
function. This is the nature of the local scope.

2. Global Scope
The variables that are declared in the global scope can be accessed
from anywhere in the program. Global variables can be used inside
any functions. We can also change the global variable value.
Example-
msg = “global variable”
def function():
msg = “local variable”
print(msg)

function()
print(msg)
Output:
local variable
global variable

As you can see, if we declare a local variable with the same name as
a global variable then the local scope will use the local variable.
If you want to use the global variable inside local scope then you will
need to use the “global” keyword.

3. Enclosing Scope
A scope that isn’t local or global comes under enclosing scope.
Example-
def vehicle():
fun= “Start”
def car():
model= “Toyota”
print(fun)
print(model)
car()
vehicle()

Output:
Start
Toyota

In the example code, the variable fun is used inside the car() function.
In that case, it is neither a local scope nor a global scope. This is called
the enclosing scope.

4. Built-in Scope

This is the widest scope in Python. All the reserved names in Python
built-in modules have a built-in scope.
When the Python does not find an identifier in it’s local, enclosing or
global scope, it then looks in the built-in scope to see if it’s defined
there.
Example-
a = 5.5
int(a)
print(a)
print(type(a))

Python would see in the local scope first to see which of the variables
are defined in the local scope, then it will look in the enclosing scope
and then global scope.
If the identifier is not found anywhere then, at last, it will check the built-
in scope.
Here, the functions int(), print(), type() does not need to be defined
because they are already defined in the built-in scope of Python.

Global and Nonlocal keyword

Remember we talked about the problem “What would happen if we


declare variables with the same name in different scopes?” For these
types of situations, we have “global” and “nonlocal” keywords.

1. global Keyword
Example-
a = 100
def method():
a = 50
print(a)
method()
print(a)
Output:
50
100

The above code will print the values 50 and 100 because in the local
scope variable, a is referenced to 50 and outside the method ()
function, it is being referenced to the global variable.

But, what if we wanted to access the global variable inside the method
() function.
Example-
a = 100
def method():
global a
a = 50
print(a)
method()
print(a)
Output:
50
50

Now we see that by using the global keyword, we can declare that we
want to use the variable a which is defined in the global scope.

So, when assigning the 50 to the variable, we also changed the value
outside the function.

2. nonlocal Keyword

Like the global keyword, we have a “nonlocal” keyword for times when
we need to change a nonlocal variable.
Example-
a = "global variable"
def method():
a = "nonlocal variable"
def function():
a = "local variable"
print(a)
function()
print(a)
method()
print(a)
Output:
local variable
nonlocal variable
global variable

In the function(), a is referring to “local variable”, in method(), a is


referring to “nonlocal variable” and outside these functions, a refers to
“global variable”.
Example-
a = "global variable"
def method():
a = "nonlocal variable"
def function()
nonlocal a
a = "local variable"
print(a)
function()
print(a)
method()
print(a)
Output:
local variable
local variable
global variable

We used the nonlocal keyword on “a” variable inside the function().

This is why when we changed the nonlocal variable value it also


changed the value of “a” variable that is defined in method() function.
QUESTIONS BANK WITH ANSWER

Multiple Choice Questions

1. What is the default return value for a function that does not
return any value explicitly ?
(a) None (b) int
(c) double (d) null

2. Which of the following items are present in the function header?


(a) function name only
(b) both function name and parameter list
(c) parameter list only (d) return value

3. Which of the following keywords marks the beginning of the


function block?
(a) func (b) define
(c) def (d) function

4. What is the name given to that area of memory, where the


system stores the parameters and local variables of a function
call?
(a) a heap (b) storage area
(c) a stack (d) an array

5. Pick one the following statements to correctly complete the


function body in the given code snippet.
def f(number): #Missing function body
print(f(5))

(a) return "number" (b) print(number)


(c) print("number") (d) return number
6. Which of the following function headers is correct?
(a) def f(a=1, b): (b) def f(a=1, b, c = 2):
(c) def f(a=1, b=1, c=2): (d) def f(a=1, b=1, c=2, d):

7. Which of the following statements is not true for parameter


passing to functions?
(a) You can pass positional arguments in any order.
(b) You can pass keyword arguments in any order.
(c) You can call a function with positional and keyword arguments.
(d) Positional arguments must be before keyword arguments in a
function call.

8. Which of the following function calls can be used to invoke the


below function definition?
def test(a, b, c, d)

(a) test(1, 2, 3, 4) (b) test(a=1, 2, 3, 4)


(c) test(a= 1, b=2, c=3, 4) (d) test(a=1, b=2, c=3, d=4)

9. Which of the following function calls will cause Error while


invoking the below function definition
def test (a, b, c, d)
s

(a) test(1, 2, 3, 4) (b) test(a=1, 2, 3, 4)


(c) test(a= 1, b=2, c=3, 4) (d) test(a=1, b=2, c=3, d=4)

10. What is a variable defined outside all the functions referred to


as ?
(a) A static variable (b) A global variable
(c) A local variable (d) An automatic variable

11. What is a variable defined inside a function referred to as


(a) A static variable (b) A global variable
(c) A local variable (d) An automatic variable
12. Carefully observe the code and give the answer.
def function1(a):
a = a+ '1'
a=a*2
function1("hello")

(a) indentation Error


(b) cannot perform mathematical operation on strings
(c) hello2 (d) hello2hello2

13. What is the result of this code?


def print_double(x):
print(2**x)
print_double(3)

(a) 8 (b) 6
(c) 4 (d) 10

14. What the order of resolving scope of a name in a Python


program ?
(L: Local namespace, E: Enclosing namespace, B: Built-In
Namespace, G: Global namespace)
(a) BGEL (b) LEGB
(c) GEBL (d) LBEG

15. Which of the given argument types can be skipped from a


function call?
(a) positional arguments (b) keyword arguments
(c) named arguments (d) default arguments
SUBJECTIVE TYPE QUESTIONS

1. What is the significance of having functions in a program?


Ans. Creating functions in programs is very useful. It offers following
advantages:
(i) The program is easier to understand:
Main block of program becomes compact as the code of functions is
not part of it, thus is easier to read and understand.
(ii) Redundant code is at one place, so making changes is easier:
Instead of writing code again when we need to use it more than once,
we can write the code in the form of a function and call it more than
once. If we later need to change the code, we change it in one place
only. Thus, it saves our time also.
(iii) Reusable functions can be put in a library in modules:
We can store the reusable functions in the form of modules. These
modules can be imported and used when needed in other programs.

2. From the program code given below, identify the parts


mentioned below:
def processNumber(x):
x=72
return x + 3
y=54
res = processNumber(y)
Identify these parts: function header, function call, arguments,
parameters, function body, main program
Ans.
Function header : def processNumber(x) :
Function call : processNumber(y)
Arguments : y
Parameters : x
Function body : x = 72
return x + 3
Main program : y = 54
res = processNumber(y)
3. Find and write the output of the following python code:
def ChangeVal (M, N):
for i in range(N):
if M[i]%5== 0:
M[i]//=5
if M[i]%3==0:
M[i]//=3
L=[ 25,8,75,12]
ChangeVal (L, 4)
for i in L:
print(i, end = '#')
Ans.
5#8#5#4#

4. Write the output of the following Python code:


def Update (X = 10):
X+=15
print(‘X=', X)
X=20
Update()
print( 'X = ', X)
Ans. X= 25
X= 20

5. Trace the following code and predict output produced by it.


def power (b, p):
y=b**p
return y
def calcSquare(x):
a = power (x, 2)
return a
n=5
result = calcSquare(n) + power (3, 3)
print(result)
Ans. 52
6. Differentiate between actual parameter(s) and a formal
parameter(s) with a suitable example for each.
Ans. Actual Parameter is a parameter, which is used in function
call statement to send the value from calling function to the
called function. It is also known as Argument.
Formal Parameter is a parameter, which is used in function
header of the called function to receive the value from actual
parameter. It is also known as Parameter.
For example-
def addEm(x, y, z):
print(x + y + z)
addEm(6, 16, 26)
In the above code, actual parameters are 6, 16 and 26; and formal
parameters are x, y and z.

7. Consider a function with following header:


def info(object, spacing= 10, collapse = 1):

Here are some function calls given below. Find out which of these
are correct and which of these are incorrect stating reasons:
a. info(obj1)
b. info(spacing=20)
c. info( obj2, 12)
d. info( obj11, object = obj12)
e. info( obj3, collapse = 0)
f. info()
g. info(collapse = 8, obj3)
h. info( spacing=15, object=obj4)

Ans.
(a) Correct : oby1 is for positional parameter object; spacing gets
its default value of 10 and collapse gets its default value of 1.
(b) Incorrect: Required positional argument (object) missing;
required arguments cannot be missed.
(c) Correct: Required parameter object gets its value as obj2;
spacing gets value 12 and for skipped argument collapse, default
value 1 is taken.
(d) Incorrect: Same parameter object is given multiple values - one
through positional argument and one through keyword(named)
argument.
(e) Correct: Required parameter object gets its value as obj3;
collapse gets value 0 and for skipped argument spacing, default value
10 is taken
(f) Incorrect: Required parameter object's value cannot be
skipped.
(g) Incorrect: Positional arguments should be before keyword
arguments.
(h) Correct: Required argument object gets its value through a
keyword argument.

8. What will following code print ?


def addEm(x, y, z):
print(x+y+z)
def prod (x, y, z):
return x * y* z
a= addEm(6, 16, 26)
b= prod (2, 3, 6)
print(a, b)

Ans. 48
None 36

9. What is the difference between a local variable and a global


variable? Also, give a suitable Python code to illustrate both.
Ans.
Local Variable: (1) It is a variable which is declared within a
function or within a block
(2) It is accessible only within a function/block in which it is
declared
Global Variable:
(1) It is variable which is declared outside all the functions
(2) It is accessible throughout the program

For example, in the following code, x, xCubed are global variables


and n and cn are local variables.
def cube(n):
cn=n*n*n
return cn
x = 10
xCubed = cube(x)
print(x, "cubed is", xCubed)

10. Explain the use of global key word used in a function with the
help of a suitable example.
Ans. global keyword: In Python, global keyword allows the
programmer to use a global variable in the local context. A
variable declared inside a function is by default local and a
variable declared outside the function is global by default. The
keyword global is written inside the function to use its global
value. Outside the function, global keyword has no effect.
For Example-
c = 10
def add():
global c # now on c will refer to global variable
c=c+2 #global value of c is incremented by 2
print("Inside add():", c)
add()
c = 15
print("In main:",c)

Output
Inside add(): 12
In main: 15
11. Which names are local, which are global and which are built-
in in the following code fragment?
invaders=“Big names”
pos = 200
level = 1
def play():
max_level = level + 10
print(len (invaders) == 0)
return max_level
res = play()
print(res)

Ans.
Global names: invaders, pos, level, res
Local names: max_level
Built-in: len

12. Find and write the output of the following python code:
a=10
def call():
global a
a=15
b=20
print(a)
call()
Ans. 15

13. Predict the output of the following code fragment?


def func(message, num=1):
print(message*num)
func(‘Python’)
func("Easy", 3)
Ans. Python
EasyEasyEasy

14. Find and write the output of the following python code:
def fun(s):
k= len(s)
m=” “
for i in range(0, k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+’bb’
print(m)
fun('school2@com')

Ans.
SCHOOLbbbbCOM

15. Predict the output of the following code fragment?


def check(n1=1, n2=2):
n1= n1+n2
n2+=1
print(n1, n2)
check()
check(2, 1)
check(3)
Ans.
33
32
53
16. What is the output of the following code?
a=1
def f():
a = 10
print(a)

Ans. The code will print 1 to the console.

17. What will be the output of following code?


def interest (prnc, time = 2, rate = 0.10):
return (prnc * time * rate)

print(interest (6100, 1))


print(interest (5000, rate = 0.05))
print(interest (5000, 3, 0.12))
print(interest (time = 4, prnc = 5000))

Ans.
610.0
500.0
1800.0
2000.0

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy