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

B.N.M.

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

c_area(a) Area of circle is 78.5


Value-Returning Functions

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']

inside functions, list / dictionary will be print(mylist)


create_new(mylist) Output
changed in the caller's scope.
print(mylist) ['apple', 'banana']
➢ When a new list / dictionary is assigned to change(mylist) ['apple', 'banana']
the name, the old list / dictionary will not be print(mylist) ['mango', 'orange']
affected.
Local Variable
❑ A local variable is a variable that is either a variable declared within the function or a
parameter of that function.

❑ 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

print("x =", x) x=9


x=9
Default Arguments

❑ 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.

def simple_interest(principle, rate = 8, time = 1):


si = principle * rate * time / 100

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 simple_interest(principle, rate, time):


si = principle * rate * time / 100
print(si)
simple_interest(rate = 11, principle = 1200, time = 4)
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, use an asterisk (*) before the parameter name to denote this
kind of argument.

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)

(b) Importing and also Renaming


import square_num as sq
result=sq.square(4)
print("By using the module square of number is:",result)
(c) Python from...import Statement
We can import specific names from a module without importing the module as a whole.
Here is an example
from square_num import square
result=square(4)
print("By using the module square of number is:",result)

(d) from square_num import *


c) Write a python program to define a module to find Fibonacci Numbers and
import the module to another program.
Algorithm:
Input: A positive integer n
Output : Fibonacci Series upto n
Step 1 : Start
Step 2 : import fibonacci module
Step 3: input a positive number
Step 4 :Call the function ‘fib’to find Fibonacci series upto ‘n’
Step 5: Stop
Fibonacci.py module
Step 1: Define a function fib(a,b)
Step 2: a=0 , b=1
Step 3: print b
Step 4: compute a,b=b,a+b
Step 5: Repeat steps 3 and 4 until b <=50
c) Write a python program to define a module to find Fibonacci Numbers and
import the module to another program.
fibonacci.py
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
print(a,end=“ “)
while b < n:
print(b, end =" ")
a, b = b, a+b
main.py
#import fibonacci module
import fibonacci
num=int(input("Enter any number to print Fibonacci series "))
fibonacci.fib(num)

You might also like