Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

FUNCTIONS

Definition:

A function is a group of statements that exists within a program for the purpose of performing a
specific task. Instead of writing a large program as one long sequence of instructions, it can be
written as several small functions, each performing a specific part of the task.

Category of functions:

1. Built-in functions: The predefined functions that are already available in python library.
Python has many useful built-in functions to make programming easier and faster and more
powerful.
Some of built-in functions in python are:
A. type conversion functions
B. input function
C. eval function
D. min and max functions
E. abs function
F. type function
G. len function
H. round function
I. range function
2. Modules: A module is file containing functions and variables defined in separate files. A
module is simply a file that contains python code or a series of instructions.
Modules also make it easier to reuse the same code in more than one program.
3. User-defined Functions: A user-defined function is a set of statements defined by the user to
fulfil his/her specific requirement.
The use of functions improves a program’s clarity and readability and makes programming
more efficient by reducing code duplication and breaking down complex tasks into more
manageable pieces.
e.g.
def add():
a=int(input("Enter a number:"))
b=int(input("Enter another number:"))
print("Addition of two numbers:", a+b)

add()
add()
add()

A user-defined function is created or defined by the def statement followed by the function
name and parenthesis() as shown in the above example.

A function definition consists of the following components:

a. Keyword def marks the start of function header.


b. A function name to uniquely identify it. Function naming flows the same rules as the
rules of writing identifiers in python.
c. Parameters/arguments through which we pass values to a function. They are
optional.
d. A colon(:) to mark the end of function header.
e. Optional documentation string to describe what the function does.
f. One or more valid python statements that make up the function body. Statements
must have same indentation level(usually 4 spaces).
g. An optional return statement to return a value from the function

How function returns a value?

def fact(n):
f=1
while n>0:
f=f*n
n=n-1
return f

num=int(input("Enter a number:"))
res=fact(num)
print("Factorial of ", num, "=", res)

num n>0 f res


5 5 1 120
4 5
3 20
2 60
1 120

0 120

#Write a python program to read the 5 subject marks of a student and find percentage of marks by
defining

#a user-defined function and returning the percentage to find the grade obtained by the student.

def percent(a, b, c, d, e):

total=a+b+c+d+e

per=total/500*100

print("Total Marks:", total)

return per

e=int(input("Enter english marks:"))

p=int(input("Enter physics marks:"))

c=int(input("Enter chemistry marks:"))


m=int(input("Enter maths marks:"))

cs=int(input("Enter computer sc marks:"))

per=percent(e, p, c, m, cs)

print("Marks Percentage:", per)

if per>90:

print("A Grade")

elif per>75:

print("B Grade")

elif per>60:

print("C Grade")

elif per>45:

print("D Grade")

else:

print("Fail")

# returning more than one value from a function:

def percent(a, b, c, d, e):

total=a+b+c+d+e

per=total/500*100

return total, per

e=int(input("Enter english marks:"))

p=int(input("Enter physics marks:"))

c=int(input("Enter chemistry marks:"))

m=int(input("Enter maths marks:"))

cs=int(input("Enter computer sc marks:"))

tot, per=percent(e, p, c, m, cs)

print("Total Marks:", tot)

print("Marks Percentage:", per)

if per>90:

print("A Grade")
elif per>75:

print("B Grade")

elif per>60:

print("C Grade")

elif per>45:

print("D Grade")

else:

print("Fail")

Write a user-defined function EvenSum (numbers) to add those values in the tuple of numbers
which are even.

Some of the important terms used in functions:

i. Function header: It is the first line of the function definition that begins with keyword def and ends
with a colon(:) specifies the name of the function and its parameters.

ii. Parameters/Arguments: Variables that are listed within the parenthesis of a function header.

iii. Function body: The block of statement/indented statements enclosed within function header
that defines the action performed by the function.

iv. Indentation: The blank spaces in the beginning of a statement within a block. All statements
within same block have same indentation.

v. Function Calling: After defining the function, the function calling statement is written, that directs
the function definition to perform its action. It consists of function name followed by a pair of
parentheses that encloses parameters within it. The arguments may have literals, variables or
expressions.

e.g. # Parameters

def func(a, b): # function header

c=a+b

print(c) #function body

func(4, 5) # Arguments

func(x, y)

func(4+5, 8*3)

Arguments and parameters:

Already, we have discussed function header and function calling statements that requires some
values to process the function, that are known as parameters/arguments. To perform action by the
function, you need define variables to receive values in function definition and send values via a
function call statement.

Arguments: Python refers to the values being passed as arguments and

Parameters: Values being received as parameters.

Types of parameters passed with function:

Python supports three types of formal arguments/parameters:

i. Positional argument (required arguments)


ii. Default arguments
iii. Keyword or named arguments

Positional argument (required arguments): When the function call statement must match the
number and order of arguments as defined in the function definition, this is called the Positional
argument (required arguments/mandatory arguments).

e.g

def func(a, b, c):

func(x, y, z)

func(5, x, y)

func(5, 8, 2)

Default arguments: A parameter having default value in the function header is known as default
arguments.

Note: In a function header, the parameters with default values must be placed at the end of the
parameters list.

e.g.

def simple_int(p, t=2, r=5):

si=(p*t*r)/100

print("Simple Interest:", si)

x=int(input("Enter the principle amount:"))

y=int(input("Enter the time period:"))

simple_int(x, y) #The value of t will be replaced by the value of y and value of r remains 5.

simple_int(1260) #Here, default value of t and r will be used.

simple_int(1500, 3, 7.5) # the value of t and r will be replaced by 3 and 7.5 respectively
simple_int(x, y, 7.5)

Output:

Enter the principle amount:2500

Enter the time period:3

Simple Interest: 375.0

Simple Interest: 189.0

Simple Interest: 150.0

Simple Interest: 562.5

Keyword or named arguments: Keyword arguments are the named arguments with assigned values
being passed in the function call statement.

e.g.

def simple_int(p, t, r=5):

si=(p*t*r)/100

print("Simple Interest:", si)

x=int(input("Enter the principle amount:"))

y=int(input("Enter the time period:"))

simple_int(p, t=y)

simple_int(p=1260, r=7.5, t=y)

Output:

Enter the principle amount:2500

Enter the time period:3

Simple Interest: 375.0

Simple Interest: 283.5

While using keyword arguments, the following points should be kept in mind:

 An argument list must have any positional arguments followed by any keyword arguments.
 Keywords in arguments list should be from the list of parameters name only.
 No parameter should receive value more than once.
 Parameter names corresponding to positional arguments cannot be used as keywords in the
same calls.

Que: Write a user-defined function to sum all the numbers in a list.

e.g. List=[4, 5, 6, 7]

Output:

Sum of all elements: 22


Passing array/list to functions:
Array are the collection of homogeneous type data whereas Lists are the collection of
heterogeneous type data. Lists are created by using the function list() whereas arrays are created by
using the function array(). But array() needs to import a module named numpy.

Example:

import numpy as n

def fun(x):

for i in range(0, len(x)):

print(x[i]**2)

x=n.array([2, 9, 6, 7, 5])

print("Array:\n", x)

fun(x)

y=list([5, 7, 9, 10, 55])

print("Lists:\n", y)

fun(y)

Output:

Array:

[2 9 6 7 5]

81

36

49

25

Lists:

[5, 7, 9, 10, 55]

25

49

81

100

3025

Passing String to functions:


Example:
import numpy as n

def fun(x):

ccap=0

cdi=0

for i in x:

if i>='A' and i<='Z':

ccap=ccap+1

elif i>='0' and i<='9':

cdi=cdi+1

print("No. of Capitlal letter in the string:", ccap)

print("No. of Digits in the string:", cdi)

x="Bokaro Steel City, Sector-5"

fun(x)

Output:

No. of Capital letter in the string: 4

No. of Digits in the string: 1

Scope of the Variable:

All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.

Scope of variables refers to the part of the program where it is visible. i.e. area where you can
refer(use) it. There are two types of scope of variables-global scope and local scope.

 Global Scope/variable:
o Names assigned at the top of a module or directly in the interpreter.
o Names declared global in the function
 Local scope/variable:
o Names assigned inside a function definition or loop

e.g.

x=2 #global variable

def fun(x):

x=20 #local variable

print("Value of local x:", x)

fun(x)

print("Value of global x:", x)


Output:

Value of local x: 20

Value of global x: 2

Using Main() as a function:

Including a main() function is not mandatory in python. It can structure our python programs in a
logical way that puts the most important components of the program into one function. It can also
make our programs easier for non-python programmers to read.

e.g.

x=2 #global variable

def fun(x):

x=20 #local variable

print("Value of local x:", x)

def main():

fun(x)

print("Value of global x:", x)

main()

Output:

Value of local x: 20

Value of global x: 2

Recursion:
Recursion is one of the most powerful tools in a programming language. It is a function calling itself
again and again. Recursion is defined as defining anything in terms of itself. In other words, it is a
method in which function calls itself one or more times in its body.

Example:

def sum_ser(x):

if x<=1:

return x

else:

return x+ sum_ser(x-1)

print("Sum of series : \n", sum_ser(10))

Dry Run:

x x + sum_ser(x-1)

10 10+sum_ser(9) 10+45=55
9 9 + sum_ser(8) 9+36=45

8 8+sum_ser(7) 8+28=36

7 7+sum_ser(6) 7+21=28

6 6+sum_ser(5) 6+15=21

5 5+sum_ser(4) 5+10=15

4 4+sum_ser(3) 4+6=10

3 3+sum_ser(2) 3+3=6

2 2+sum_ser(1) 2+1=3

1 1

OutPut:

Sum of series :

55

Example:

def factorial(x):

if x<=1:

return x

else:

return x * factorial(x-1)

n=int(input("Enter a number:"))

print("Factorial of ", n, " : ", factorial(n))

6= 6*5*4*3*2*1

Dry Run:

x x * factorial(x-1)

6 6* factorial(5) 6*120=720

5 5* factorial(4) 5*24=120

4 4* factorial(3) 4*6=24

3 3* factorial(2) 3*2=6

2 2* factorial(1) 2*1=2

Output:
Enter a number:6

Factorial of 6 : 720

Conditions for implementing recursion:

i. There must be a terminating condition for the problem which we want to solve with
recursion. This condition is called the base case for that problem.
ii. Reversal in the order of execution is the characteristics of every recursive problem i.e. when
a recursive program is taken for execution, the recursive function calls are not executed
immediately. They are pushed onto stack as long as the terminating condition is
encountered. As soon as the terminating condition is encountered, the recursive calls which
were pushed onto stack are removed in reverse order and executed one by one. It means
the last call made will execute first, then the second last call will execute and so on until the
stack is empty.
iii. Each time a new recursive call is made, a new memory space is allocated to each local
variable used by the recursive routine. In other words, during each recursive call to recursive
function, the local variable of the recursive function gets a different set of values, but with
the same name.
iv. The duplicated values of the local variables of a recursive call are pushed onto the stack with
its respective call, and all these values are available to the respective function call when it is
popped off from the stack.

You might also like