135. Reviewer Certificate in Journal of Engineering
functions notes.pdf python functions and opp
1.
2. FUNCTIONS
A function is a block of organized, reusable code that is
used to perform a single, related action.
Functions provide better modularity for the applications.
Functions provide a high degree of code reusing.
3. RULES FOR DEFINING FUNCTION IN PYTHON
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses.
We also define parameters inside these parentheses.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an
expression to the caller.
A return statement with no arguments is the same as return None.
4. Function Syntax
The keyword
def
introduces a
function
definition.
Input Parameter is placed within the
parenthesis() and also define
parameter inside the parenthesis.
Return statement exits a
function block. And we can also
use return with no argument.
The code block
within every
function starts
with a colon(:) .
5.
6. Passing arguments :-when the user defined function is called ,values are
transferred from calling function to called function.These values are
called as arguments.
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable length arguments
PASSING ARGUMENTS
7. REQUIRED ARGUMENT VALUES
VALUES
Required arguments are mandatory for the function call
First the required argument should be listed,then
the default argument should be listed.
EXAMPLE:
Output:
In this code, argument ‘b’
has given a default value.
ie(b=10),and a is
required argument.
When the value of ‘b’ is not passed
in function ,then it takes default
argument.
def sum(a,b=10):
return(a+b)
print("sum=",sum(10,20))
print("sum=",sum(20))
print("sum=",sum(10))
Sum=30
Sum=30
Sum=20
8. DEFAULT ARGUMENT VALUES
Default Argument- argument that assumes a default value if a value is not
provided in the function call for that argument.
The default value is evaluated only once.
EXAMPLE:
Output:
In this code, argument ‘b’
has given a default value.
ie(b=90)
When the value of ‘b’ is not passed
in function ,then it takes default
argument.
9. DEFAULT ARGUMENTS
The default value is evaluated only once. This makes a difference when the
default is a mutable object such as a list, dictionary, or instances of most
classes.
Example:
if we don’t want the default value to be shared between subsequent calls,
then
Example :
Output:
Output:
10. KEYWORD ARGUMENTS
Keyword arguments are related to the function calls.
Using keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
Allows to skip arguments or place them out of order, the Python interpreter
use the keywords provided to match the values with parameters.
Example:
Output:
Caller identifies the keyword
argument by the parameter name.
Calling of the argument Order
doesn’t matter .
12. ARBITRARY ARGUMENT LISTS
Variable-Length Arguments: more arguments than we specified while defining
the function.
These arguments are also called variable-length arguments .
An asterisk (*) is placed before the variable name that holds the values of all non
keyword variable arguments.
This tuple remains empty if no additional arguments are specified during the
function call.
Syntax :
def function_name([formal_args], *var_args_tuple ):
statement 1……
statement 2……
return [expression]
This is called
arbitrary argument
and asterisk sign is
placed before the
variable name.
13. ARBITRARY ARGUMENT LISTS
EXAMPLE 1:
Output: Output:
EXAMPLE 2:
Any formal parameter which
occur after the *args
parameter are keyword-only
arguments.
If formal parameter are not
keyword argument then error
occurred.
Monika
Ranbir
Purva
Lalit
def fun2(*variable,value="Monika"):
print(value)
for val in variable:
print(val)
return
fun2("Ranbir","Purva","Lalit")
14. LAMBDA EXPRESSIONS
Small functions can be created with the lambda keyword also known as
Anonymous function.
Used wherever functions object are required.
These functions are called anonymous because they are not declared in the
standard manner by using the def keyword. .
Syntax :
EXAMPLE:
lambda [arg1 [,arg2,.....argn]]:expression
Output:
The function returns the multiply of
two arguments.
Lambda function is restricted to a
single expressions.
Anonymous
Functions
15. Returning Statement
The return statement is used to return the
values from user-defined function to
calling statement.
Return keyword is used to return values
16. Returning values
Example Description
return c Returns c from the function
return 100 Returns constant from a function
return lst Return thelist that contains values
return z,y,z Returns more than one value
17. Returning M values
# A function that returns two results
def sum_sub(a, b):
c = a + b
d = a – b
return c, d
# get the results from sum_sub() function
x, y = sum_sub(10, 5)
# display the results
print("Result of addition: ", x)
print("Result of subtraction: ", y)
18. Recursive Function
A function which calls itself is called recursive function
EXAMPLE:
def pr(a):
if(a>0):
print(a)
pr(a-1)
else:
return()
pr(5)
Output
5
4
3
2
1
19. Local and Global Variables
KEY DIFFERENCE
Local variable is declared inside a function whereas Global variable is declared outside the
function.
Local variables are created when the function has started execution and is lost when the function
terminates, on the other hand, Global variable is created as execution starts and is lost when the
program ends.
Local variable doesn’t provide data sharing whereas Global variable provides data sharing.
Local variables are stored on the stack whereas the Global variable are stored on a fixed location
decided by the compiler.
Parameters passing is required for local variables whereas it is not necessary for a global variable
20. LOCAL VARIABLE
Local Variable is defined as a type of variable declared within programming block or
subroutines. It can only be used inside the subroutine or code block in which it is declared.
The local variable exists until the block of the function is under execution. After that, it will
be destroyed automatically.
Example of Local Variable
#local variable
def funct():
z=10
print("local variable value",z)
funct()
print("local variable outside value",z)
21. GLOBAL VARIABLE
A Global Variable in the program is a variable defined outside the subroutine or
function. It has a global scope means it holds its value throughout the lifetime of the
program. Hence, it can be accessed throughout the program by any function
defined within the program, unless it is shadowed.
EXAMPLE:
#global variable
z=10
def funct():
print("global variable value",z)
funct()
print("global variable outside value",z)
22. DIFFERENCE BETWEEN LOCAL /GLOBAL
Parameter Local Global
Scope It is declared inside a function. It is declared outside the function.
Value If it is not initialized, a garbage value is stored If it is not initialized zero is stored as default.
Lifetime
It is created when the function starts
execution and lost when the functions
terminate.
It is created before the program's global
execution starts and lost when the program
terminates.
Data sharing
Data sharing is not possible as data of the local
variable can be accessed by only one function.
Data sharing is possible as multiple functions
can access the same global variable.
Parameters
Parameters passing is required for local
variables to access the value in other function
Parameters passing is not necessary for a
global variable as it is visible throughout the
program
Modification of variable value
When the value of the local variable is
modified in one function, the changes are not
visible in another function.
When the value of the global variable is
modified in one function changes are visible in
the rest of the program.
Accessed by
Local variables can be accessed with the help
of statements, inside a function in which they
are declared.
You can access global variables by any
statement in the program.
Memory storage It is stored on the stack unless specified.
It is stored on a fixed location decided by the
compiler.
23. USING GLOBAL STATEMENT
It is used to declare the variable as global variables,once the variable is declared
as global the corresponding variable can be used in any other function
#global statement
def ff():
global m
m=10
print("m value inside function ",m)
ff()
print("m value outside function ",m)
24. MODULES
A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier to understand and use.
A module is a Python object with arbitrarily named attributes that you can bind and
reference.
Simply, a module is a file consisting of Python code.
A module can define functions, classes and variables. A module can also include
runnable code.
25. Create a Module
To create a module just save the code you want in a file with the file extension .py:
def greeting(name):
print("Hello, " + name)
26. Importing elements of a Module
Importing all elements
Importing specific elements of a module
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("John")
27. Built-in Modules
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The dir() function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)