Docsity

Functions and Modularity, Lecture notes of Programming Languages

Partial preview of the text

Download Functions and Modularity and more Lecture notes Programming Languages in PDF only on Docsity!

Unit IV

FUNCTIONS AND MODULARITY

A function is a reusable block of code that perform a specific task.

It helps to organize code, reuse it and avoid repetition.

A function is created using the def keyword.

SYNTAX:

def function_name (parameters): #

code block(Indentation)

return value #optional

Note:

Indentation is very important in python.

return statement is optional. If not

use, the function returns None.

Why use Function?

Reuse code

Make programs short and

cleaner

Improve readability

Make debugging easier

Divide large programs into

smaller

parts

How a Function works

Use the def keyword to define a function

Give the function a name

Write the code inside the

function (indentation)

Call the function using its name

followed by parentheses.

Note:

Function name follows the same rules as variable names in Python

Types of Function

1. Function without

Parameter

2. Function with Parameter

A function that contain parameter.

def greet( ):

print(“Hello Python”)

# function call

greet()

def add( a , b):

result = a + b

return result

# function call

sum = add( 5 , 3 )

print(“Sum

is :” , sum)

Types of Function

3. Function with Multiple Parameter

4. Function with return

value

A function can have more than

one parameter.

def information( name, age, city ):

print(“Name”, name)

print(“Age”, age)

print(“City”, city)

# function call

information(“karma”,

0, “Thimphu”)

def square( num ):

return num * num

# function call

result = square( 4 )

print(“Square

is :” , result)

Calling a Function

A function cannot run on its own. It run only when we call it. That

means a function is executed only when it is called using its

name.

Example: A function that accept two values and finds their sum.

Returning Result form a Function

def sum( a, b):

c = a + b

print(“Sum=”,c)

# calling the

function

sum(10,15)

The return statement is used inside the function

body to

return value out of the function. A function

can return one or more values.

def sum( a, b):

c = a + b

return c

# return

result

sum(10,15)

Function Argument in Python(Formal and Actual)

In Python, function arguments are the value you pass to

function when you call it. They allow a function to work

with different input.

When a function is defined, it may have some parameters.

These parameters are useful to receive values from outside

of the function. These parameter are called “Formal

argument”. When we call the function, we should pass the

actual data or values to the function.

These values are called “Actual Arguments”

Types of formal and actual arguments

1. Positional Argument

The arguments passed to a function in correct positional order. Here, the

number of the argument and their positions in the function definition should

be match exactly with the

number and the position of the arguments in the function call.

Example:

def attach(s1,s2):

s3 = s1 + s

print(“Total string :” +s3)

#call attach() and pass 2 string

attach(‘ New ’, ‘York’) # positional

argument

Cont.…………….

2. Keyword Argument

Keyword argument are the arguments that identify the parameters by

their name, so the order doesn’t matter.

Example:

def grocery (item, price):

print(“Item = %s”

%item) print(“Price =

%.2f” %price)

call grocery() and pass

argument grocery(item =

“sugar”, price = 50.75)

Cont.…………….

4. Variable Length Argument

A variable length argument is an argument that can accept any number

of variables. The variable length argument is written with a “ * “ symbol

before it in the function

definition as:

def add (frag, * args): # * args can take 0 or more

value

print(“ Formal argument = “ , frag)

print(“Sum of variable args =“,

sum(args))

call add() and pass argument

add(5,10)

add(5,10,20,

Cont.…………….

5. Variable Length Keyword Argument

Uses ** kwarg to accept any number of keyword arguments

Example : def person(** details):

print(details)

person(name=“sonam”, age=25, city

=“Thimphu”)

Local and Global Variable

Local Variable

When we declare a variable inside a function, it become a local variable.

A local variable is a variable whose scope is limited only to that function

where it is created. That means the local variable value is available only

in that function and not outside

of that function. Exampl

e:

def myfunction():

a = 1 # this is local

variable a+ = 1 #

increment it print(a) #

display 2

myfunction() # call the

function print(a) # error,

Cont. ………..

Global Variable

When a variable is declared above a function, it become global

variable. Such variable are available to all the function which are

written after it. Exampl

e:

a = 1 # global

varable

def myfunction():

b = 2 # this is local

variable

print(‘a’ =

a )

print(‘b’ =

b)

#display global

variable

#display local

variable

myfunction() # call the

function

print(

a)

print(

b)

available

error, not

available

Ngawang

Example Cont.…………

a = 1 # global varable

def myfunction():

a = 2 # local variable

print(‘a’ = a ) # display local

variable myfunction() # call the

function

print(‘a’ = a) # display global variable

Outpu

t: a =

2

a = 1

Output:

10

global a = 1

modified a

= 2 global a

=

a = 1 # global varable

def myfunction():

b = 10 # local

variable print(b) #

display 10

global a # refer to global

variable print(“global a =“,

a) # display 1

a = 2 #modified global

variable print(“Modified

a=”, a)

Recursive Function

A function that calls itself is known as recursive

function It is useful to solve complex program in

fewerExample: steps Factorial of any number

def factorial(n):

if n == 0:

result =

1 else:

result = n* factorial(n

  • 1 ) return result