Nothing Special   »   [go: up one dir, main page]

Python Functions 1

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

FUNCTIONS

Definition : A Function is a named group of related statements


that perform a specific task.

A Function is a named block of organized reusable code that is


used to perform a single related action.

Need for Functions :

1. Help to implement modular programming :


Functions help to break our program into smaller and
modular chunks. As our program grows larger and larger,
functions make it more organized and manageable.

2. Implement Code reusability :


They avoid repetition and make code reusable.
Syntax of function

def function_name ( parameters ) : # Function header


[“ “ “ docstring “ ” ”]
<statement > } # Function definition
[<statement>] }
:
:
:

The above shown function definition consists of following


components .

1. Keyword def marks the start of function header


2. A Function name to uniquely identify it.
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 ahat
the function does.
6. One or more valid python statements that make up the
function body. Statements must have same indentation level.
7. An optional return statement to return a value from the
function.
Python Function to compute sum of two numbers.

def calcsum(x,y): # Function declaration


s=x+y
return s

print (calcsum(2,8)) # Method 1 of calling the function

def calcsum(x,y): # Function declaration


s=x+y
return s

sum=calcsum(4,16) # Method 2 of calling the function


print(sum)

def calcsum(x,y): # Function declaration


s=x+y
return s

print(calcsum(2,8)) # Method 3 of calling the function

def calcsum(x,y): # Function declaration


s=x+y
return s

num1=int(input(“Enter first number”))


num2=int(input(“Enter second number”))
sum=calcsum(num1,num2) # Method 4 of calling the function
print(“Sum of two numbers=”,sum)
Python Function to compute cube of a number

def cube(x):
return x**3

print(cube(2))

def cube(x):
return x**3

result=(cube(2))
print(result)

def cube(x):
return x**3

num=int(input(“Enter a number”))
result=cube(num)
print(“Cube =”,result)

3. Python function to compute product of two numbers


def multiply( a , b ): or def multiply( a , b ):
prod=a*b return a*b
return prod

result = multiply(3,9)
print (“product= ”,result)
or

num1=int(input(“Enter first number”))


num2=int(input(“Enter second number”))
result=multiply(num1,num2)
print(“Product=”,result)
or

print(multiply(3,9))

4. Python function to check if a number passed to it as argument


is even or odd. No return statement
def evenodd ( x ) :
if ( x % 2 == 0 )
print (“Even”)
else
print (“Odd”)

evenodd(2)
evenodd(3)

or

num1=int(input(“Enter a number”))
evenodd(num1)

5. Function to compute area of square


def areaofsquare ( side )
area=side*side
return area

print ( areaofsquare(4))

or

s = int(input(“Enter side of square”))


result = areaofsquare ( s )

6. Function to greet a person by his/her name .

def greet (name ) :


“ ” ” This function greets to the person passed in as
parameter “ “ “
print ( “ Hello , “ + name + “.Good Morning !”)

greet (“Paul”) # Function call

Output

Hello, Paul.Good Morning!

7. Function to compute area of rectangle


8. Function to compute area and perimeter of rectangle.
9. Function to compute simple interest
10. Function to compute area and circumference of circle
11.
12.Program to implement 4 function calculator using functions.
13.Program to pass tuple as an argument to a function.
14. Program to pass list as an argument to a function.
15. Passing dictionary as argument to a Function
Passing PARAMETERS

Python supports 3 types of formal arguments/parameters

1. Positional arguments (Required arguments)


2. Default arguments
3. Keyword ( or named arguments )

1. Positional arguments

For example , if a function definition header is like :


def check (a, b, c ):

then possible function calls for this can be :

check(x, y, z) # 3 values ( all variables passed)


check( 2, x, y) # 3 values ( literal + variables ) passed
check ( 2, 5, 7 ) # 3 values ( all literals ) passed

2. Default Arguments

def interest( prin , rate , time = 2 )

interest ( 5000, 3 ) # third argument missing


interest ( 3000, 4, 5 ) # no argument missing
def SayHello(name=”Guest”):
print(“Hello “ + name )
return

SayHello() #No value being passed

Hello Guest # Output

SayHello(‘Tom’)

Hello Tom # Output

3. Keyword or named Arguments

interest( prin = 2000, time=2,rate=0.10)


interest( time= 4, prin = 2500, rate = 0.09 )
interest (time = 2, rate = 0.12, prin = 2000)

All the above function calls are valid now, even if the order of
arguments does not match the order of parameters as defined
in the function header.
Returning values from functions
1.Functions returning some value ( non-void functions )

2.Functions not returning any value ( void functions )

1. Functions returning some value


(Non-void functions )
The functions that return some computed result in terms
of a value , fall in this category. The computed value is
returned using return statement as per syntax :

return <value>

The value being returned can be one of the following

❖ a literal
❖ a variable
❖ an expression
for example

def sum(x,y):
s=x+y
return s

result=sum(5,10)
2. Functions not returning any value
(void functions )
The void functions do not return a value but they return a legal
empty value of Python i.e None. Every void function returns
value None to its caller. So if need arises you can assign the
return value somewhere as per your needs .
Consider the above code , None is printed as value stored in a
because greet() returned value None , which is assigned to
variable a.

So, we see that in Python you can have 4 possible


combinations of functions :
(i) Non-void functions without any arguments
(ii) Non-void functions with some arguments
(iii) void functions without any arguments
(iv) void functions with some arguments

Returning Multiple values

return<value1/variable1/expression1>,<value2/variabl
e2/expression2>,…
Q. Program to arrange 2 numbers in ascending order using function.
Function returning multiple values.
Function with Default Arguments :Compute area of rectangle.
h.w dt. 09-04-2020
Pass by Object reference.
Recall that everything in Python is an object. So a variable for an object, is actually a
reference to the object. In other words, a variable stores the address where an object
is stored in the memory. It doesn’t contain the actual object itself.

When a function is called with arguments, it is the address of the object stored in the
argument is passed to the parameter variable. However, just for the sake of simplicity,
we say the value of an argument is passed to the parameter while invoking the
function. This mechanism is known as Pass By Value. Consider the following
example:

1 def func(para1):
2     print("Address of para1:", id(para1))
3     print(para1)

5 arg1 = 100
6 print("Address of arg1:", id(arg1))
7 func(arg1)
Output:
1 Address of arg1: 1536218288
2 Address of para1: 1536218288
3 100
Notice that the id values are same. This means that
variable arg1 and para1 references the same object. In other words,
both arg1 and para1 points to the same memory location where int object (100) is
stored.
This behavior has two important consequences:

1. If arguments passed to function is immutable, then the changes made to the


parameter variable will not affect the argument.
2. However, if the argument passed to the function is mutable, then the changes
made to the parameter variable will affect the argument.
Let’s examine this behavior by taking some examples:

Example 1: Passing immutable objects to function.

1 def func(para1):
2     para1 += 100 # increment para1 by 100
3     print("Inside function call, para1 =", para1)

5 arg1 = 100
6 print("Before function call, arg1 =", arg1)
7 func(arg1)
8 print("After function call, arg1 =", arg1)
Output:

1 Before function call, arg1 = 100


2 Inside function call, para1 = 200
3 After function call, arg1 = 100
In line 7, func() is called with an argument arg1 (which points to an immutable
object int). The value of arg1 is passed to the parameter para1. Inside the function
value of para1 is incremented by 100 (line 2). When the function ends, the print
statement in line 8 is executed and the string "After function call, arg1 =
100" is printed to the console. This proves the point that no matter what function does
to para1, the value of arg1 remains the same.
If you think about it this behavior makes perfect sense. Recall that the contents of
immutable objects can’t be changed. So whenever we assign a new integer value to a
variable we are essentially creating a complete new int object and at the same time
assigning the reference of the new object to the variable. This is exactly what’s
happening inside the func() function.

Example 2: Passing mutable objects to function

1 def func(para1):
2     para1.append(4)
3     print("Inside function call, para1 =", para1)

5 arg1 = [1,2,3]
6 print("Before function call, arg1 =", arg1)
7 func(arg1)
8 print("After function call, arg1 =", arg1)
Output:
1 Before function call, arg1 = [1, 2, 3]
2 Inside function call, para1 = [1, 2, 3, 4]
3 After function call, arg1 = [1, 2, 3, 4]
The code is almost the same, but here we are passing a list to the function instead of
an integer. As the list is a mutable object, consequently changes made by
the func() function in line 2, affects the object pointed to by variable arg1.

Q. Function to exchange the values of 2 variables.


Q. Program to print the largest element in a list using a function.
Q. Program to print the largest element in a list and its position using a
function.

Q.Program using function bubblesort to sort a list in ascending


order.

Q. Program using function Lsearch to search for an element in a list.


Scope of variable

Parts of a program within which a name is legal and accessible, is


called scope of the variable.
There are broadly 2 kinds of scopes in python
1. Global scope
2. Local scope.

1. Global scope
The name declared in top level segment (_main_) of a program is
said to have global scope and is usable inside the whole program
and all blocks( functions, other blocks) contained within the
program.
2. Local scope
The name declared in a function body is said to have local scope
i.e., it can be use only within this function and other blocks
contained under it. The names of formal arguments also have
local scope.
Scope Example 1
Global Variables : Variable defined outside all functions are
global variables.

x=5
def func(a):
b=a+1
return b

y = input(“Enter number”)
z = y + func (x)
print (z)
Scope Example 2 :
Name resolution ( Resolving Scope of a name )

For every name reference within a program i.e., when you access a
variable from within a program or function, Python follows name
resolution rule, also known as LEGB rule.

● Local(L) : Defined inside a function/class or enclosed within a nested


loop or conditional construct.

● Enclosd(E): Defined inside enclosing functions  (Nested functions)

● Global(G): Defined at the topmost level

● Built-in(B): that contains all built-in variables and functions of python


i.e Reserved Keywords in Python built-in functions/modules/classes. If
there is a variable with the same name, Python uses the value.

Otherwise python would report the error.

In simple terms, it is the order in which the namespaces are to be searched


for scope resolution.

Note: Namespaces are named program regions used to limit the


scope of variables inside the program.

Case 1: Variable in global scope but not in local scope

def calcsum(x,y):
s=x+y
print(num1)
return s

num1=int(input(“Enter first number : “))


num2=int(input(“enter second number : “))
print (“Sum=” ,calcsum(num1,num2))

Case 2: Variable neither in local scope nor in global scope


def greet():
print(“Hello !”,name)

greet()

This would return error as name is neither in local environment nor in global
environment.

Case 3: Same Variable name in local scope as well as in global scope.

def state1( ) :
tigers =15
print ( tigers )

tigers = 95
print tigers
state1( )
print ( tigers )

Output :
95
15
95

That means a local variable created with same name as that of global variable ,
hides the global variable. As in above code , local variable tigers hides global
variable tigers in function state1( )

How to access global variable inside local scope ?


global <variable name>

def state1( ) :
global tigers #This is an indication not to create local
tigers = 15 variable with the name tigers, rather use
print ( tigers ) global variable tigers.

tigers = 95
print tigers
state1( )
print ( tigers )

Output
95
15
15

Once a variable is declared global in a function, you cannot undo the


statement. That is, after a global statement , the function will always
refer to the global variable and local variable cannot be created of the
same name.

# Python program to demonstrate


# passing dictionary as argument
  
  
# A function that takes dictionary
# as an argument
def func(d):
      
    for key in d:
        print("key:", key, "Value:", d[key])
          
# Driver's code

D = {'a':1, 'b':2, 'c':3}


func(D)

Output:
key: a Value: 1
key: b Value: 2
key: c Value: 3

In the code given below we pass given dictionary as an argument to a python function and then call the
function which works on the keys/value pairs and gives the result accordingly

 Example
d = {'a' : 1, 'b' : 2, 'c' : 3}

def f(dict):

    for k, v in dict.iteritems():

        print k, 2*v

f(d)

Output
a 2
c 6
b 4

Mutable vs Immutable Objects in Python


Every variable in python holds an instance of an object. There are two types of
objects in python i.e. Mutable and Immutable objects. Whenever an object is
instantiated, it is assigned a unique object id. The type of the object is defined at
the runtime and it can’t be changed afterwards. However, it’s state can be
changed if it is a mutable object.
To summarise the difference, mutable objects can change their state or contents
and immutable objects can’t change their state or content.
● Immutable Objects : These are of in-built types like int, float, bool,
string, unicode, tuple.
● In simple words, an immutable object can’t be changed after it is created.
# Python code to test that 
# tuples are immutable 

    
tuple1 = (0, 1, 2, 3) 
tuple1[0] = 4
print(tuple1)
Error :

Traceback (most recent call last):


File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment

# Python code to test that 


# strings are immutable 
  
message = "Welcome to Class 12"
message[0] = 'p'
print(message)
Error :
Traceback (most recent call last):
File
"/home/ff856d3c5411909530c4d328eeca165b.py",
line 3, in
message[0] = 'p'
TypeError: 'str' object does not support item
assignment
● Mutable Objects : These are of type list, dict, set .
Custom classes are generally mutable.

# Python code to test that 
# lists are mutable 
color = ["red", "blue", "green"]
print(color)
color[0] = "pink"
color[-1] = "orange"
print(color)
Output:
['red', 'blue', 'green']
['pink', 'blue', 'orange']

Conclusion
1. Mutable and immutable objects are handled differently in python.
Immutable objects are quicker to access and are expensive
to change because it involves the creation of a copy.
Whereas mutable objects are easy to change.

2. Use of mutable objects is recommended when there is a need to change


the size or content of the object.

3. Exception : However, there is an exception in immutability as well. We


know that tuple in python is immutable. But the tuple consists of a
sequence of names with unchangeable bindings to objects.
Consider a tuple
tup = ([3, 4, 5], 'myname')
The tuple consists of a string and a list. Strings are immutable so we can’t
change its value. But the contents of the list can change. The tuple itself
isn’t mutable but contain items that are mutable.

As a rule of thumb, Generally Primitive-like types are probably immutable and


Customized Container-like types are mostly mutable.
Python | Passing string value to the function
Here, we will learn by example, how to pass the strong value to the function in
Python?

We have to define a function that will accept string argument and print it. Here, we
will learn how to pass string value to the function?
Example:
Input:
str = "Hello world"

Function call:
printMsg(str)

Output:
"Hello world"
Program:

# Python program to pass a string to the function

# function definition: it will accept


# a string parameter and print it
def printMsg(str):
# printing the parameter
print str

# Main code
# function calls
printMsg("Hello world!")
printMsg("Hi! I am good.")
Output
Hello world!
Hi! I am good.
Write function that will accept a string and return total number of vowels
# function definition: it will accept
# a string parameter and return number of vowels
def countVowels(str):
count = 0
for ch in str:
if ch in "aeiouAEIOU":
count +=1
return count

# Main code
# function calls
str = "Hello world!"

print "No. of vowels are {0} in


\"{1}\"".format(countVowels(str),str)

str = "Hi, I am good."


print "No. of vowels are {0} in
\"{1}\"".format(countVowels(str),str)
Output
No. of vowels are 3 in "Hello world!"
No. of vowels are 5 in "Hi, I am good."

You might also like