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

WORKING WITH FUNCTION IN PYTHON

FUNCTIONS:

 A Function is a collection of statements which is made to perform a specific task.


 Instead of writing a large program ,we can write small functions as a specific part of program to
accomplish the task.
 TO execute function , we have to call it in the program.
 Once written , a function can also be used in other programs as library functions.

Types of functions:

i) Built-in functions
ii) Functions defined in module
iii) User defined functions

Built –in functions:

 These are pre-defined functions and are always available for use.
 In order to use these functions , there is no need to import any module.
 We can directly use it , in our program.

Ex: len( ) , int() , type(), print(), input() , id()

Functions define in modules:

 These functions are pre-defined in particular modules.


 These can only be used when the corresponding module is imported.
 Math module: sin(),sqrt(),ceil(),cos(),fabs(),floor()
 Statstics module : mean(),median(),mode()
 Random module : random() , randrange(), randint(),uniform(),choice(),shuffle()

User – defined functions:

 These functions are defined by the programmer.


 Functions that we define ourselves to do certain specific task are referred as user-defined functions.

Ex: add(),area(),fact(),display(),compute(),LCM()

Syntax of user-defined functions:

Def functionName([parameters]):

<statement>

[<statement>]

 Keyword def marks the beginning of the function header.


 Function name must follow the naming rules same as for identifiers.
 Function may or may not contain arguments.
 A colon(:) marks the end of function header.
 Function can take one or more statements to perform a specific task.
 An optional return statement to return a value from the function.
 Function must be called/invoked to execute its code.
 All statements within the same block must have same indentation.
Ex1: def Display():
Print(“never give up!!!”)
Display()
Ex2: def Display1():
Print(“good morning….”)
Print(“…………………”)
def Display2():
print(“********”)
def Display3():
print(“-----------------“)
Display1()
Display2()
Dispaly3()
Ex: def Add():
Num1 = int(input(“enter first number:”))
Num2=int(input(“enter second number:”))
Result=num1+num2
Print(“addition =”,result)
Add()
Output: enter first number:14
Enter second number:25
Addition =39

Variations in user defined functions:

 Functions with no argument and no return value.


Ex: def Add():
X=int(input(“number 1:”))
Y=int(input(“number2 :”))
Print(“Addition=”,x+y)
Add()
 Functions with arguments but no return value.
Ex: Def Add(x,y):
Print(“Addition =”,x+y)
X=int(input(“number 1:”))
Y=int(input(“number 2:”))
Add(x,y)
 Functions with arguments and return value.
Ex: Def Add(a,b):
Print(“Addition =”,a+b)
X=int(input(“number 1:”))
Y=int(input(“number 2:”))
Add(x,y)
 Functions with no argument but return value.
Ex: Def Add(a,b):
C=a+b
Return C
X=int(input(“number 1:”))
Y=int(input(“number 2:”))
Print(Add(x,y))
 The return statement ends the function even if it is in the middle of the function. The statements written
after return statement will not get executed.
 If a function does not return any value by default it returns None.
Ex: def greater(a,b):
If a>b:
Return a
Else:
Return b
Print (“statement after return statement”)
Num1=int(input(“enter first no:”))
Num2=int(input(“enter second no:”))
Result =greater (num1,num2)
Print(“greater number is :”,result)

This statement will not get executed, as return statement


will transfer the control outside the function.

Can function return more than one value?

Yes , a function can return more than one value in the form of tuple.

Arguments and parameters:


Ex:

Flow of execution:

 The flow of execution refers to the order in which statements are executed during a program run.
Ex:

Passing parameters:

 Positional / required arguments


 Default arguments
 Keyword/named arguments
 Variable length arguments

Positional /required arguments:

 Positional arguments are arguments passed to a function in correct positional order. If we


change their order,then the result will be changed. If we change the number of arguments passed,
then it shall result in an error.
 When the functions call statement must match the number and order of arguments as defined
in the function definition this is called positional argument matching.
Ex:

Default arguments:

 Default is an argument that assumes a default value if a value is not provided in the function
call for that argument.
 If you are not passing any value, then only default values will be considered.
 Non default arguments cannot follow default arguments.
 In a function header,any parameter cannot have a default value unless all parameter appearing on
its right have their default values

Ex:

Keyword/ named arguments:

 The default arguments gives flexibility to specify default value for a parameter so that it can be
skipped in the function call,if needed.
 However, still we can not change the order of arguments in function call.
 To get control and flexibility over the values sent as arguments , python offers keyword
arguments.
 This allows to call function with arguyments in any order using name of the arguments.
 Ex:
Rules for combining all three types of arguments:

 An argument list must first contain positional arguments followed by any keyword arguments.
 Keyword arguments should be taken from the required arguments preferable.
 You cannot specify a value for an argument more than once.

Scope of a variable:

 Scope of a variable is the portion of a program where the variable is recognized.


 SCOPE means part of a program in which a variable can be used.
 Local scope , global scope

Local scope:

 The variables declared inside the function definition are called local variables.
 Ex: def func():

L=20 here,L is a local variable

Print(“inside func1..”,L)

Func1( )

Global scope:

 The variables declared outside the function definition are called global variables.
 Ex:
 If in any program, there are two variables with same name one is local and one is global,to use he
global variable in a function we have to use the global keyword with variable name.
 When a function changes the value of a global variable,it will be reflected back outsine the
function also.
LEGB rule:
1. Local scope
 Contains names defined inside the current definition.
2. Enclosing scope
 Contains names defined inside any and all enclosed function.
3. Global scope
 Contains names defined at the top level of the script or module.
4. Built in scope
 Contains names built-in to the python language.
MUTABLE AND IMMUTABLE PROPERTIES OF DATA OBJECTS:

 Depending upon the mutability or immutability of the data type , a variable behaves differently.
 Mutable type , immutable type

Immutable type:

 If a variable is referring to an immutable type then, any change in its value will also change the
memory address it is referring to.
 Any change in the value of a immutable type will not get reflected in the original value outside the
function.

Mutable type:

 If a variable is referring to mutable type,and then any change in the value of mutable type will not
change the memory address of the variable,it will change the value in place.
 Any change in the value of a mutable type will get reflect in the original value outside the function
also.

Note:

 If a parameter is assigned a new name or different data type value, then changes will not reflected
back in original value.

You might also like