0% found this document useful (0 votes)
9 views

Unit 2 User Defined Functions Stds

This document provides an overview of user-defined functions in Python, explaining their purpose, benefits, and how to create and call them. It covers different types of functions, function arguments, variable scope, and the concept of returning values from functions. Additionally, it includes examples to illustrate the usage of various function types and argument styles.

Uploaded by

mafeef051
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Unit 2 User Defined Functions Stds

This document provides an overview of user-defined functions in Python, explaining their purpose, benefits, and how to create and call them. It covers different types of functions, function arguments, variable scope, and the concept of returning values from functions. Additionally, it includes examples to illustrate the usage of various function types and argument styles.

Uploaded by

mafeef051
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Unit 2: User defined functions in Python

Function : Python function is a block of related statements that performs a specific , well defined
task. These block of statements are executed only when we call a function.
Here we put some commonly or repeatedly done tasks together in a one function so that instead of
writing the same code again and again for different inputs, we can reuse the code by making function
calls many times we want.
Some Benefits of Using Functions
 Increase Code Readability
 Increase Code Reusability
Need of Function :
1. Use of functions make debugging, testing and maintenance of program easy .
2. Function provides code re-usability, we need not to rewriting same code again and again in a program.
3. The length of the program is reduced which saves our lot of time and make our code cleaner..
Types of Functions : In python functions can be broadly classified into three major categories :
1. Built in functions
2. User-defined Functions
3. Functions defined in Modules
1. Built-in functions are those functions that are pre-defined in the Python interpreter . These are part of
the python standard library and we can use them directly without importing any module or library. E.g ;
print( ), len ( ) , range ( ) etc.
2. Functions defined in Modules : Some functions in python are defined in particular modules. A
module is a file containing definition of functions, classes, variables, constants or any other Python object.
Contents of this file can be made available to any other program. Python has the import keyword for this
purpose.
3. User defined functions : In addition to the built-in functions and functions in the built-in modules, you
can also create your own functions. These functions are called user-defined functions.It enables user to
define his own code to accomplish a particular task.
Creating a function :
To create a function in python, use keyword def followed by function name, parentheses for
parameters ( if any) and a colon :
The general syntax for creating a function is :
Syntax :
Keyword def < function name> ( [Parameters]) : ] function header
< statement>

Body of function
< statement>
return value ( optional)

 Function block begin with the keyword def followed by the function name which is any valid
identifier and parentheses ( ( ) ).
 After function name , a list of parameters is given inside the parentheses separated by comma
which act placeholder for data .
 The first statement of a function can be an optional statement; the documentation string of the
function or docstring., a brief explanation of what the function does.
 Colon (:) at the end of the definition statement marks the beginning of the block of code and
further body of function starts.
 The function body contains code to be executed. It is an indented block which defines the
behavior of function .
 The statement return [expression] is used to return a value from the function to the place where
it has been called . It is optional statement . A function may or may not have return statement.
Calling /Invoking a function : The process of using a function in a program after defining it is called
calling a function or invoking a function. The statement that is written to calla function is known as a
function call.
Syntax :
< function name > ( input values as arguments)
Example 1: Program to find Even or Odd using functions
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")

evenOdd(2) # Call to function


evenOdd(3) # No. 2 and 3 can be entered from KB also

Output : even
Odd
Example 2 : To find square of a Number using functions.
def square( num ):
return num**2
sq = square(5)
print( “The square of the given number is: “, sq )

Output : The square of the given number is: 25

Function Arguments

The following are the types of arguments that we can use to call a function:
1. Default arguments
2. Keyword arguments
3. Required arguments
4. Variable-length arguments

1. Positional or required argument : These are the arguments that are passed to the function in the same
order as the parameters defined in the function definition.That means , the number of arguments in the
function call should match exactly with the function definition. It must provide arguments for every
parameter. Values to be passed as arguments must match with the parameters position wise and order
wise. Otherwise error will be generated.

Example :

def std(name , age):

print("My name is", name + " and my Age is " , age)

std(" yehya ", 20)

Output : My name is yeyha" and my Age is 20

2. Default argument : A default arguments are arguments in a function that have a default value
specified in the function definition. So default argument assumes a default value if a value is not
provided in the function call for that argument. And if a value is provided in the function call for default
argument , the default value is overridden. The following example gives an idea on default arguments, it
prints default age if it is not passed.
Example :

def Stdinfo( name, age = 45 ):


"Below Stmts print the information passed into this function"
print ("Name: ", name)
print ("Age ", age)
return;

# Now you can call Stdinfo function


Stdinfo ( "Faizan" )
Stdinfo ( "Athar", 50 )
Stdinfo ( 60, "Iqbal" ) # this will swap value of name and age leading to error

Output :

Name: Faizan
Age 45
Name: Athar
Age 50
Name: 60
Age: Iqbal

Any number of arguments in a function can have a default value. But once we have a default
argument, all the arguments to its right must also have default values. It means positional arguments must
be defined before giving the default value. Otherwise error will occur.
The main advantage of using default argument is that if you skip the value in function call , the default
value is considered .The only constraint in the default argument is that you cannot change the order of
arguments in the function call.
3. Keyword argument : The keyword arguments or named arguments a provide flexibility to provide
values as parameters in any order and sequence. So we can change the order of the arguments while
passing the values to the function in the function call, provided you mention the names of arguments.

Example :
def Stdinfo( name , age , rollno ):
"This prints a passed info into this function"
print ("Name : ", name)
print ("Age : ", age)
print ("Rollno : ", rollno)
return;

# Now you can call Stdinfo function


Stdinfo ( age= 18,rollno = 111, name="Athar" )

Output :
Name : Athar
Age : 18
Rollno : 111
4. Variable-length arguments : Arbitrary arguments / variable length arguments can pass a
variable number of arguments to a function using special symbols.These are useful when we do not know
how many arguments that will be passed into our function at the time of function definition and hence
helps in creating flexible function that can accept different no of parameters.
These are of two types :
a. Arbitrary Positional arguments / variable length Positional arguments (*args): These arguments
are used when we don’t know how many positional argument a function will receive. An asterisk (*) is
placed before the variable name ( that holds the values of all nonkeyword variable arguments. ) that
allows us to pass a variable number of positional arguments to the function which are then accessed as a
tuple inside the function.
Example :
def myclass(*argv):
for arg in argv : # using for loop
print(arg)

myclass('Hello', 'Welcome', 'to', 'Computer class')

Output :
Hello
Welcome
to
Computer class
b. Arbitrary Keyword arguments / variable length Keyword arguments (**kwargs): These
arguments are used when we don’t know how many keyword arguments a function will receive. An
asterisk (**) is placed before the variable name that allows us to pass a variable number of keyword
arguments to the function which are then accessed as a dictionary inside the function.
Example :
def myclass(**argv):
print ("my name is : " + argv['name'])
print (" my year is :" + argv['year'])

myclass( year ='12th', name ='Hassan' )


Output :
my name is : Hassan
my year is :12th

Things to Remember:

 *args and **kwargs are special keyword which allows function to take variable length
argument.
 *args passes variable number of non-key worded arguments and on which operation of the
tuple can be performed.
 **kwargs passes variable number of keyword arguments dictionary to function on which
operation of a dictionary can be performed.

Scope of variable : Scope of a variable is the region in the code where the variable is available /
accessible.

In python supports two main types of variable scope : local and global

Local variable : These variables are defined / initialized within a function and are unique to that
function. It cannot be accessed outside of that function. So they have got local scope. Local variables
are created when function is called and destroyed when function returns or completes its execution.

Example : y
def f( ):
# local variable
locl = "Scope of local variable"
print( ' Inside function : ' , locl)
f()
Output
Inside function : Scope of local variable

If we will try to use this local variable outside the function then let’s see what will happen.

def f():
# local variable
locl = "Scope of local variable"
f( )
print(locl)

Output:

NameError: name 's' is not defined


Global variable : These are the variables that are defined and declared outside any function and are
not specified to any function. They can be used by any part of the program and thus have got global
scope. These are created when program starts and persist until the program terminates. It is useful
when multiple functions need to access same data.

Example:
Lg = "Scope of global variable"
def f( ):
print( ' Inside function : ' , Lg)
# Global variable
f()
print( ' Outside function : ' , Lg)

Output
Inside function : Scope of global variable
Outside function : Scope of global variable

Global and Local Variables with the Same Name : When a variable with the same name is defined inside
and outside the function , then it will print the value given inside the function only and not the global
value.
Example :
s = 10
def f( ):
s= 20
print( ' Value of s Inside function : ' , s)

f()
Output :
Value of s Inside function : 20

Though we can access a global variable from within a function, we cannot modify it. To avoid this
error and modify the global variable from within a function, we need to use the keyword ‘global’.

Example :
s=4
def f( ):
# Global variable 's' can be accessed from inside function
# but to modify its value we have declare it global
global s
s = s+1
print( ' Inside function : ' , s)
# Global variable
f()
print( ' Outside function : ' , s)
Output : Inside function : 5
Outside function : 5

Function Returning values :


In general, a function takes arguments (if any), performs some operations, and returns a value (or
object). The value that a function returns to the caller is generally known as the function's return value.
All Python functions have a return value, either explicit or implicit.The function return statement is used
to exit from a function and go back to the function caller and return the specified value or data item to the
caller. Functions that return value are called non void functions and those that do not return value are
called void functions.
The syntax for the return statement is:
return [expression_list]

The return statement can consist of a variable, an expression, or a constant which is returned at the
end of the function execution. If none of the above is present with the return statement a None object is
returned.

Void functions : This function is called void if it does not return any value or has empty return
statement.

Example 1
def add(a, b):
total = a+b # add( ) without return

sum= add( 20,50)


print (sum)
print("Execution will start now from here") :
Output : None
Execution will start now from here
Example 2:
def add(a, b):
total = a+b
return # add ( ) with return but with no arguments
sum= add( 20,50)
print (sum)
Output : None
Example 3:
def add(a, b):
total = a+b
return total
sum= add( 20,50)
print (sum)
Output : 70

Example 4:
def add ():
a=10
b=20
return a,b
sum= add( )
print (sum)
Output : (10,20) # two values will be returned as tuple

Prog : To Swap two numbers using a user defined function. Swapping of Numbers.py

def swap( x, y ):
x, y = y, x
return x, y
x = 50
y = 100
print("Before swapping :")
print(" x =", x, " y =", y)
x , y = swap ( x, y) # print(swap( x,y)) then no need to assign them to x,y
print("After swapping :")
print(" x =", x, " y =", y)

You might also like