UNIT – 2
Functions and its use: Function is a group of related statements that perform a
specific task. Functions help break our program into smaller and modular
chunks. As our program grows larger and larger, functions make it more
organized and manageable. It avoids repetition and makes code reusable.
Basically, we can divide functions into the following two types:
1. Built-in functions - Functions that are built into Python.
Ex: abs(),all().ascii(),bool()………so on….
integer = -20
print('Absolute value of -20 is:', abs(integer))
Output:
Absolute value of -20 is: 20
2. User-defined functions - Functions defined by the users themselves.
def add_numbers(x,y):
sum = x + y
return sum
print("The sum is", add_numbers(5, 20))
Output:
The sum is 25
Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function 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.
5. Function calls are like a bypass in the flow of execution. Instead of going to
the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.
#example for flow of execution
print("welcome")
for x in range(3):
print(x)
print("Good morning college")
Output:
welcome
0
1
2
Good morning college
PROGRAM 2
def hello();
print(“Good morning”)
print(“Karnataka”)
print(“hi”)
print(“hello”)
hello()
print(“done”)
Output:
hi
hello
Good morning
karnataka
done
Parameters and arguments:
Parameters are passed during the definition of function while Arguments are
passed during
the function call.
Example:
#here a and b are parameters
def add(a,b): #//function definition
return a+b
#12 and 13 are arguments
#function call
result=add(12,13)
print(result)
output:
25
There are three types of Python function arguments using which we can call a
function.
1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments
Syntax:
def function name():
statements
.
.
.
functionname()
Function definition consists of following components:
1. Keyword def indicates the start of function header.
2. A function name to uniquely identify it. 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 function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body.
Statements must have
same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.
Example:
def hf():
hello world
hf()
In the above example we are just trying to execute the program by calling the
function. So it
will not display any error and no output on to the screen but gets executed.
To get the statements of function need to be use print().
#calling function in python:
def hf():
print("hello world")
hf()
Output:
hello world
def add(x,y):
c=x+y
print(c)
add(5,4)
Output:
9
def add(x,y):
c=x+y
return c
print(add(5,4))
Output:
9
Ex:
def add_sub(x,y):
c=x+y
d=x-y
return c,d
print(add_sub(10,5))
Output:
(15, 5)
The return statement is used to exit a function and go back to the place from
where it was called. This statement can contain expression which 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 hello_f():
return "hellocollege"
print(hello_f().upper())
Output:
HELLOCOLLEGE
# Passing Arguments
def hello(wish):
return '{}'.format(wish)
print(hello("bijapur"))
output:
bijapur
Here, the function wish() has two parameters. Since, we have called this
function with two arguments, it runs smoothly and we do not get any error. If
we call it with different number of arguments, the interpreter will give errors.
def wish(name,msg):
"""This function greets to
the person with the provided message"""
print("Hello",name + ' ' + msg)
wish("ravi","Good morning!")
Output:
Hello ravi Good morning!
#Default Arguments
Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator
(=)
def hello(wish,name='you'):
return '{},{}'.format(wish,name)
print(hello("good morning"))
Output:
good morning,you
Example:
def hello(wish,name='you'):
return '{},{}'.format(wish,name) //print(wish + ‘ ‘ + name)
print(hello("good morning","nirosha")) // hello("good morning","nirosha")
Output:
good morning,nirosha // good morning nirosha
Program:
#Program to find area of a circle using function use single return value
function with
argument.
pi=3.14
def areaOfCircle(r):
return pi*r*r
r=int(input("Enter radius of circle"))
print(areaOfCircle(r))
Output:
Enter radius of circle 3
28.259999999999998
#Program to write sum different product and using arguments with return
value
function.
def calculate(a,b):
total=a+b
diff=a-b
prod=a*b
div=a/b
mod=a%b
return total,diff,prod,div,mod
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
s,d,p,q,m = calculete(a,b)
print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m)
#print("diff= ",d)
#print("mul= ",p)
#print("div= ",q)
#print("mod= ",m)
Output:
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5
#program to find biggest of two numbers using functions.
def biggest(a,b):
if a>b :
return a
else :
return b
a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
big= biggest(a,b)
print("big number= ",big)
output:
Enter a value 5
Enter b value-2
big number= 5
#program to find biggest of two numbers using functions. (nested if)
def biggest(a,b,c):
if a>b :
if a>c :
return a
else :
return c
else :
if b>c :
return b
else :
return c
a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
#function call
big= biggest(a,b,c)
print("big number= ",big)
Output:
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7
#Writer a program to read one subject mark and print pass or fail use
single return
values function with argument.
def result(a):
if a>40:
return "pass"
else:
return "fail"
a=int(input("Enter one subject marks"))
print(result(a))
Output:
Enter one subject marks 35
Fail
Python Recursive Function
We know that in Python, a function can call other functions. It is even possible
for the
function to call itself. These type of construct are termed as recursive functions.
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.
Following is an example of recursive function to find the factorial of an integer.
# Write a program to factorial using recursion
def fact(x):
if x==0:
result = 1
else :
result = x * fact(x-1)
return result
print("zero factorial",fact(0))
print("five factorial",fact(5))