python function ©️Ⓢ
python function ©️Ⓢ
Function is a named block of statements used to carry out a well defined task.
FUNCTION
Function can be categorized into the following three types:
(i) Built-in function
(ii) Function defined in modules
(iii) User defined function
Built-in function: These are predefined function and are always available for use. For example
– len( ), type( ), int ( ), input ( ) etc.
User defined function: A user-defined Python function is created or defined by the def
statement followed by the function name and parentheses as shown in the next slide.
A function is a programming block of codes which is used to perform a specific task
(computation). It only runs when it is called. It contains line of codes that are executed
sequentially from top to bottom by python interpreter. They are most important building
blocks for any software in python.
keyword Function
name
Header
def Sum(x):
total=0
for i in range(x):
indent
Function body
total=total+i
print ("The sum= ",total)
Sum(5) Function call
statement
Function Header: The first line of function definition that begins with keyword def
and ends with a colon (:), specifies the name of the function and its parameters.
Parameters: Variables that are listed within the parentheses of a function header.
def f1(x,y):
print (x*y)
f1(20,30)
Here x,y are formal arguments whereas 20,30 are actual arguments.
Default parameters
5 res=greatest(x,y,z) Arguements
when integers, floats, strings or tubles are placed to the function as parameter that
is said to be immutable arguments. The changes made to these parameters are not
reflected back in their respective arguments.
Eg.
def change(n):
print(n)
n=n+10
print(n) Output:
a=15 15
print(a) 15
change(a) 25
print(a) 15
Mutable Arguments:-
Global Scope
With global scope variable can be used anywhere in the program.
Local Scope
With local scope variable can be used only within the function/ block that it is created.
a=10
global def update()
X=50 global a
a=15
def test(): local
print(a+10)
y=20 Update()
print()
print(‘value of x is’,x,’y is’,y)
print(‘value of x is’,x,’y is’,y) Output:
25
15
On execution the code will get value of x is 50, y is 20.
the next print statement will produce an error because the variable y is not
accessible outside the def().
Note: To access global variable inside the function as global prefix keyword global can be
used with the variable. Thus Variable can be used inside and outside of the function as well.