Python Expt 4
Python Expt 4
Institute of Technology
An Autonomous Institution under VTU
Python Programming
EXPT4
Title: Functions, Modules.
AIM:
• Write a function to compute GCD, LCM of two numbers.
• Write a python program to define a module to find Fibonacci
Numbers and import the module to another program.
Introduction to Functions
• Functions are used to divide complicated programs into manageable
pieces.
• A function in Python is a block of statements that has a name and
can be executed by calling it from some other place in the program
Using functions has several advantages:
• Different people can work on different functions simultaneously.
• If a function is needed in more than one place in a program or
different programs, we can write it once and use it many times
Defining and Calling a Function
❑In Python a function is defined using the def keyword
❑To call a function, use the function name followed by parenthesis.
Example:
def message(): #Function Definition
print('Hello, how are you?')
print('I am function.')
message() # Function Call
Output
• Hello, how are you?
• I am function.
Nesting of function call
def main():
print('Inside main')
message() #calling another function
print('Inside main again') Output
def message(): Inside main
print('Hello, how are you?') Hello, how are you?
print('I am function.') I am function.
main() # Function Call Inside main again
Passing Arguments to Functions
Data can be passed into functions as arguments. Arguments are specified inside
the parentheses as shown in the following example:
import math
def c_area(radius):
area = math.pi*radius*radius
print('Area of circle is', area)
a = int(input(‘Enter the radius of the circle’))
#function call Output
A function can return a value back into the calling code as the result. Use the return statement in function to return a
value. Here is an example of a value returning function
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
15
25
45
def factorial(number):
fact = 1
for i in range(1,number+1):
fact = fact * i
return fact
n=int(input(‘Enter an integer’))
f = factorial(n)
print('Factorial of', n,'is', f)
Output
Factorial of 5 is 120
Modifying Argument Inside Function
All arguments in the Python are passed by object reference.
If you pass immutable arguments like integers, strings or tuples to a function,
they can't be changed within the function because they are immutable.
Program
def change(yourtext):
yourtext = 'I am updated text’ Output
print(‘Your text=’,yourtext)
Your text= I am updated text
mytext = 'I am original text'
My text I am original text
change(mytext)
print(‘My text’,mytext)
Modifying Argument Inside Function
If we pass mutable arguments like lists and def change(yourlist):
yourlist[0] = 'mango'
dictionaries to a function, they can be changed
yourlist[1] = 'orange'
within the function. But we have to consider
two cases: def create_new(yourlist):
yourlist = ['mango','orange']
➢ When a list / dictionary is passed as an
argument and the elements of a list changed mylist = ['apple','banana']
❑ Local variables defined inside a function can only be accessed in the body of that function.
def f(n):
x=9
print('x=',x,'n=',n)
f(5)
#Below statement will generate an error
print('x=',x,'n=',n)
Global variable
❑ Global variable can be used in any function in the program.
❑ It is usually declared at the start of the program.
x = 100 # global variable
def f():
print("x =", x)
def b(): Output
print("x =", x) x = 100
print("x =", x) x = 100
f() x = 100
b()
Global variable x = 100
If you want to access / modify def f():
the global variable inside
function, you need to use the global x
keyword global. x=9
print("x =", x)
print("x =", x)
Output
f() x = 100
❑ When one or more top-level parameters have the form parameter = expression,
the function is said to have "default parameter values."
❑ For a parameter with a default value, the corresponding argument may be
omitted from a call, in which case the parameter's default value is substituted.
❑ If a parameter has a default value, all following parameters must also have a
default value.
In the following example rate parameter has a default value, therefore, time
parameter also must have default value.
print(si)
Output
simple_interest(1200)
96.0
simple_interest(1200,11)
132.0
simple_interest(1200,11,4)
528.0
Positional Arguments
Positional argument: Positional argument is an argument that is not a
keyword argument. positional arguments are used in the following calls:
def simple_interest(principle, rate, time):
si = principle * rate * time / 100
print(si)
simple_interest(1200, 11, 4)
Keyword Arguments
Keyword argument: Keyword argument provides the flexibility to pass the arguments in any
order. You can pass arguments using the key = value pair.
The following example demonstrates this:
def greet(*names):
"""This function greets all Output
the person in the names tuple.""" Hello Monica
Hello Mary
# names is a tuple with arguments Hello Adam
for name in names: Hello John
Hello Abc
print("Hello", name) Hello Xyz
greet("Monica", “Mary", “Adam", "John") Hello Pqr
greet(‘Abc’,’Xyz’,’Pqr’)
3. a) Write a function to compute GCD, LCM of two numbers.
Description:
Greatest Common Factor (GCD): The greatest common factor to any two or more two integer numbers is
known as the HCF of these numbers. For example, the HCF of 12 and 18 is 6.
Lowest Common Multiple (LCM): The smallest or lowest common multiple of any two or more than two
integer numbers is termed an LCM. For example, the LCM of 12 and 18 is 36.
Also,
GCD * LCM= product of two numbers
Therefore
LCM= a*b/GCD(a,b)
Finding HCF Using Euclid’s Division Lemma
Consider two positive numbers 418 and 33 and we have to find the HCF of these two numbers.
Step 1: The larger integer which is 418 is taken and
using Euclid’s Division, a = b q +r we get,
→ 418 = 33 x 12 + 22
Where
a = 418; b = 33; q = 12; r = 22
Step 2: Now if the divisor is 33 represented as ‘a’ and 22 as ‘b’, on applying Euclid’s Division
Algorithm, we get
→ 33 = 22 x 1 + 11
Step 3: Again if we take 22 as divisor ‘a’ and 11 as ‘b’ and we apply Euclid’s Division Algorithm,
we get
→ 22 = 11 x 2 + 0
Step 4: The remainder we obtain is 0 and thus we cannot do the process further.
The last divisor that is obtained is 11 and the HCF we get off 418 and 33 is 11.
Algorithm: GCD (a,b)
Inpur: Two positive numbers Step 1: a mod b = R
Output : GCD and LCM of two numbers Step 2: Let a = b and b = R
Step 1: Start Step 3: Repeat Steps 1 and 2 until a mod b is
Step 2: Read two integer numbers greater than 0
Step 3: Cal the function GCD(a,b) Step 4: GCD = b
Step 4: Print GCD of two numbers Step 5 : Return GCD
Step 5 : Cal the function LCM(a,b)
Step 6: Print LCM of two numbers LCM(a,b)
Step 5: Stop Step 1: Determine LCM using the formula
LCM=a*b/GCD(a,b)
Step 2: Return LCM
Program:
def gcd(a, b): output:
while b:
a, b = b, a % b
return a
def lcm(a,b):
lcm_no=int(a*b/gcd(a,b))
return (lcm_no)
# Reading numbers from user
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
# Function call & displaying output GCD and LCM
print(f ‘HCF or GCD of {first} and {second} is', gcd( first, second))
print(f ‘LCM of {first} and {second} is‘, lcm(first,second))
Python Recursion
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.
Write a function to find the factorial of a number using recursion
Program:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input(“Enter a positive integer”))
print("The factorial of", num, "is", factorial(num))
Write a function to find the factorial of a number using recursion
Program:
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input(“Enter a positive integer”))
print("The factorial of", num, "is", factorial(num))
Find sum=1+2+3+4+5+……+n using recursion
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
Python Modules
• Modular Programming is the practice of segmenting a single,
complicated coding task into multiple, simpler, easier-to-manage
sub-tasks. These subtasks are called modules
Benefits
• Simplification
• Flexibility
• Reusability
Python Modules
A document with definitions of functions and various statements written in Python is called a
Python module.
A module is a file containing Python code, definitions of functions, statements, or classes.
Creating a module
# square_num.py
# Python program to show how to create a module.
def square( number ):
"""This function will square the number passed to it"""
result = number ** 2
return result
Import Modules in Python
(a) import square_num
import square_num
result=square_num.square(4)
print("By using the module square of number is:",result)