SlideShare une entreprise Scribd logo
1  sur  29
UNIT I
DATA, EXPRESSIONS,
STATEMENTS
DATA, EXPRESSIONS, STATEMENTS
• Python interpreter and interactive mode
• Values and types
• Variables, expressions, statements, tuple assignment
• Precedence of operators
• Comments
• Functions
• Modules
• Illustrative programs:
• exchange the values of two variables
• circulate the values of n variables
• distance between two points
FUNCTIONS
• A function is a set of instructions that are used to perform specified task
• Functions provide better modularity and a high degree of code reusing.
• complex tasks can be sub-divided into manageable tasks.
• Routines, subroutines, procedures, methods, subprograms.
• Python offers many built-in functions like print(), input()
• It also supports to generate our own functions called as user-defined
functions
FUNCTIONS[Contd..]
• Need-user-defined functions
– Complex program – no. of problems, too large and complex
– Debugging, testing and maintenance becomes difficult.
– Program – Divided into parts – independently coded and later
combined into single program.
– Code is repeated in the program, designed as a function, called and
used – required.
– It save both time and memory
FUNCTIONS[Contd..]
• Advantages
1. The length can be reduced by dividing it into smaller functions.
2. It is easy to locate and debug an error.
3. User defined functions used whenever necessary.
4. Avoids coding of repeated instructions.
5. Build customised library of repeatedly used routines.
6. Top-down programming approach.
FUNCTIONS[Contd..]
• Function elements:
– Function Definition
– Function Invocation(call)
• Function Definition:
– The function definition contains the code that determines the function behaviour.
• Component of function definition:
– Starts with the keyword def followed by the function name – pair of parenthesis ().
– Function name is used to identify it.
– The values are passed as parameters (or) arguments which must be placed inside the
parenthesis.
– A colon (:) symbol is used to indicate end of function header.
– The first statement – optional statement – docstring.
– The function body consists of one or more valid python statements with similar
indentation level
– The last statement return [expression] exits a function
• Syntax
def funtionname(parameters):
“functiondocstring ”
Function body
return [expression];
FUNCTIONS[Contd..]
• Function Invocation [function call]:
• Once the structure of the function is defined, the function can be executed by calling it from
other function or program or even from python prompt.
• Program 1:
def count_to_5():
“ this function prints the value between 1 to 5”
for i in range(1,6):
print(i)
print (‘Function call to print numbers:’)
count_to_5()// fn call
print (‘Function call to print nos.again:’)
count_to_5()// fn call
• Output:
Function call to print numbers: Function call to print no’s again:
1 1
2 2
3 3
4 4
5 5
FUNCTIONS[Contd..]
• Program 2:
def cube(x=3):
“ this function will return the cube of a number”
y = x * x * x
print(y)
cube(3)// fn call
• Output:
27
• Program 3:
def odd_even(85):
if(number%2==0):
print (‘The number’,number,’is even’)
else:
print(‘The number’,number,’is odd’)
return
result = int(input(‘Enter a number:’))
odd_even(result)// fn call
• Output:
Enter a number: 85
The number 85 is odd
FUNCTIONS[Contd..]
• Function argument:
– User-defined functions can take different types of arguments.
– The arguments types and their meanings are predefined and can’t be changed.
1. Required Arguments:
– Required arguments are the arguments passed to a function in correct positioned order
• Example:
def printing(str):
‘“The prints string passed to the function”’// doc string
print(str)
return;
printing()
FUNCTIONS[Contd..]
2. Keyword arguments:
– Functions can be called using keyword arguments.
– Caller identifies the arguments by the parameter name.
– When the function is called in this method, the order(ie) the position of the arguments can be
changed.
• Example:
def printinfo(name,phno):
print(“Name:”,name)
print(“phone no:”, phno)
return;
#A function with 2 keyword arguments
printinfo (name=’xxx’, phno = 123456789) // fn call
#A fn.call with out of order arguments
printinfo(phno= 123456789, name=’xxx’)
#A fn.call with 2 positional arguments
printinfo(‘xxx’. 123456789)
#A fn.call with | positional arguments & keyword argument
printinfo(‘xxx’,phno=123456789)
FUNCTIONS[Contd..]
• Default Arguments:
– A default value can be given to the parameter by means of the assignment operator.
– Several no. of parameter in a function can have a default value.
– But once the function has a default parameter, all the arguments to its right must also
have default value
• Example:
def printfinfo (name,phno=’123456789’):
print(‘name=’,name)
print(phoneno=’,phone)
return;
printinfo(name=’xxx’)
printinfo(name=’xxx’,phno=’567891234’)
• In this function, the parameter name does not have a default value and is required during a
call. The parameter phno has a default value of ‘12456789’. So it is optional during a call. If a
value is provided, it will overwrite the default value.
def printinfsso(name=’AAA’,phno)
• Syntax Error: non-default argument follows default argument.
FUNCTIONS[Contd..]
• Variable-length arguments:
– Not be familiar with the no. of arguments that will be passed to a function.
– Function calls with subjective number of parameters.
– asterisk(*) before the arguments name is used to indicate variable-length arguments.
• Example:
def greeting (*person-name):// fn definition
for name in person-name:
print(“Hai”,name)
return;
greeting(“XXX”, “YYY”, “ZZZ”)//fn call
• Output:
Hai XXX
Hai YYY
Hai ZZZ
FUNCTIONS[Contd..]
• An asterisk (*) is placed before the variable name that will hold the values of all non keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call. For example:
def printinfo( arg1, *vartuple ):
"This is test"
print "Output is: "
print arg1
for var in vartuple:
print var
return;
printinfo( 10 );
printinfo( 70, 60, 50 );
• This would produce following result:
Output is:
10
Output is:
70
60
50
The Anonymous Functions
• The lambda keyword to create small anonymous functions. These functions are
called anonymous because they are not declared in the standard manner by using
the def keyword.
• Lambda forms can take any number of arguments but return just one value in the
form of an expression. They cannot contain commands or multiple expressions.
• An anonymous function cannot be a direct call to print because lambda requires an
expression.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Although it appears that lambda's are a one-line version of a function, they are not
equivalent to inline statements in C or C++, whose purpose is by passing function
stack allocation during invocation for performance reasons.
• Syntax:
lambda [arg1 [,arg2,.....argn]]:expression
Example
• Following is the example to show how lambda form of function works:
sum = lambda arg1, arg2: arg1 + arg2;
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
Scope of Variables
• All variables in a program may not be accessible at all locations in that program.
This depends on where you have declared a variable.
• The scope of a variable determines the portion of the program where you can access
a particular identifier. There are two basic scopes of variables in Python:
Global variables
Local variables
• Global vs. Local variables:
• Variables that are defined inside a function body have a local scope, and those
defined outside have a global scope.
• This means that local variables can be accessed only inside the function in which
they are declared whereas global variables can be accessed throughout the program
body by all functions. When you call a function, the variables declared inside it are
brought into scope.
Example
total = 0; # This is global variable.
def sum( arg1, arg2 ):
"Add both the parameters"
total = arg1 + arg2;
print "Inside the function local total : ", total
return total;
# Now you can call sum function
sum( 10, 20 );
print "Outside the function global total : ", total
• This would produce following result:
Inside the function local total : 30
Outside the function global total : 0
FUNCTIONS[Contd..]
• Function parameters:
– Specified within pair of parentheses in the function definition.
– The values of their variables are defined in function call.
– The names given in the function definition are called parameters
– The values supplied in function call are called arguments.
def find_max (a,b):
if a>b:
print(a,’is max’ )
elif a==b:
print (a, ‘is equal to’,b)
else:
print(b,’is max’)
find_max(5,9)
x=46
y=76
find_max(x,y)
MODULES
• A file that contains a collection of related functions.
• A module allows user to logically organize python code grouping
• Python has many built-in modules
• e.g.) math module
• >>>import math
• This statement creates a module object named math.
• < module ‘math’ (built-in)>
• Contains the function and variables.
• To access the function within module specify the name of the module and
name of the function separated by a dot.
• Example:
>>> math.log10(200)
2.3010299956639813
3.1622776601683795
MODULES[Contd..]
• Writing Modules
• Any file that contains python code can be imported as a module. Assume a
file add Module.py with the following code
def add (a,b):
c= a+b
print(c)
add(10,20)
• We can import this like
>>>import add Module
30
• Now we have a module object add Module.
• This module provides add() function.
>>>add Module. add(100,200)
300
MODULES[Contd..]
• The drawback with this is that when module is imported it runs the test
code at the bottom.
• To avoid it, add the following idiom :
if _name_==’_main_’;
• _name_ is a built in variable that is set when the program starts.
If the program is running as a script, _name_ has the value _main_, in the case,
the test code runs. Otherwise, if the module is imported, the test code is
skipped
def add (a,b):
c=a+b
print(c)
if _name_==_main_:
add(10,20)
• Now on importing addModule, the test case will not run
• >>>import addModule.
ILLUSTRATIVE PROGRAM
Exchange the values of a variables
1. Exchange the values of a variables
• Exchange values of 2 variables can be done in different ways.
– Using temporary variable
– Without using temporary variable.
• Using temporary variable
a= int (input(‘Enter first value :’))
b= int (input(‘Enter second value :’))
temp=a
a=b
b= temp
print (‘After Swapping’)
print (‘First value:’, a)
print (‘second value:’, b)
ILLUSTRATIVE PROGRAM
Exchange the values of a variables [Contd..]
OUTPUT:
Enter first value : 10
Enter second value : 20
After Swapping
First value : 20
Second value : 10
ILLUSTRATIVE PROGRAM
Exchange the values of a variables [Contd..]
• Without using temporary variable
1. Using tuple assignment:
a= int (input (‘ Enter first value:’))
b= int (input (‘Enter second value:’))
a,b=b,a
print (‘After Swapping’)
print (‘First value:’ ,a)
print (‘Second value:’, b)
ILLUSTRATIVE PROGRAM
Exchange the values of a variables [Contd..]
2. Using arithmetic operator:
• Addition & Subtraction Multiplier & Division
a=a+b a=a*b
b=a-b b=a/b
a=a-b a=a/b
3. Using bitwise operator:
• If variables are integers , then swapping can be done with help of
bitwise XOR operator.
a=a^b
b=a^b
a=a^b
ILLUSTRATIVE PROGRAM
Circulate the value of N variables
• Circulating a python list by an arbitrary number of items to the right or
left can be performed by list slicing operator.
• Circulation of the list by n position can be achieved by slicing the array
into two and concatenating them.
• Slicing is done as nth element to end element + beginning element to n-
1th element.
• Example:
• 1, 2, 3, 4, 5, 6, 7
• If n=2, then the given list is rotated 2 positions towards left side.
• 3, 4, 5, 6, 7, 1, 2  Left circulated list
• If n=-2 then the given list is rotated 2 position towards right side.
• 6, 7, 1, 2, 3, 4, 5  Right circulated list
ILLUSTRATIVE PROGRAM
Circulate the value of N variables [Contd..]
• Function to perform this circulation:
def circulate ( list , n):
return list [n:] + list [:n]
>>> circulate ([1, 2, 3, 4, 5, 6, 7], 2)
[3, 4, 5, 6, 7, 1, 2]
>>>circulate ([1, 2, 3, 4, 5, 6, 7] , 2)
[ 6, 7, 1, 2, 3, 4, 5]
ILLUSTRATIVE PROGRAM
Test for Leap Year
• Python provides isleap() function in calendar module to check whether
a year is leap year or not .
>>> import calendar
>>> calendar
……..// provides info path
>>> calendar . isleap (2000)
True
>>> calendar . isleap (2003)
False
ILLUSTRATIVE PROGRAM
Distance between points
• To find the distance between 2 points , given by the coordinates
(X1,Y1) and (X2,Y2), the Pythagorean theorem is used
• By the Pythagorean theorem , the distance is :
distance = (x2-x1)2 + (y2-y1)2
• Example:
def distance (x1, y1, x2, y2):
dx = x2 – x1
dy = y2 – y1
dsquare = dx * dx + dy * dy
dist = dsquare **0.5
return result
>>> dist = distance (1, 2, 3, 5)
>>> print (dist)

Contenu connexe

Tendances

Tendances (20)

User defined functions in C
User defined functions in CUser defined functions in C
User defined functions in C
 
Presentation on Function in C Programming
Presentation on Function in C ProgrammingPresentation on Function in C Programming
Presentation on Function in C Programming
 
predefined and user defined functions
predefined and user defined functionspredefined and user defined functions
predefined and user defined functions
 
Lecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.pptLecture20 user definedfunctions.ppt
Lecture20 user definedfunctions.ppt
 
User defined functions in C programmig
User defined functions in C programmigUser defined functions in C programmig
User defined functions in C programmig
 
Prsentation on functions
Prsentation on functionsPrsentation on functions
Prsentation on functions
 
Functions in C
Functions in CFunctions in C
Functions in C
 
Pre defined Functions in C
Pre defined Functions in CPre defined Functions in C
Pre defined Functions in C
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Functions in C - Programming
Functions in C - Programming Functions in C - Programming
Functions in C - Programming
 
Function in C
Function in CFunction in C
Function in C
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Functions in c
Functions in cFunctions in c
Functions in c
 
C and C++ functions
C and C++ functionsC and C++ functions
C and C++ functions
 
Function in C Language
Function in C Language Function in C Language
Function in C Language
 
Function & Recursion
Function & RecursionFunction & Recursion
Function & Recursion
 
C functions
C functionsC functions
C functions
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Control Structures in C
Control Structures in CControl Structures in C
Control Structures in C
 

Similaire à 3. functions modules_programs (1)

Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and commentMalligaarjunanN
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptRajasekhar364622
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxsangeeta borde
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuplesMalligaarjunanN
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptxYagna15
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptxSulekhJangra
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceKrithikaTM
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptxRhishav Poudyal
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdfNehaSpillai1
 

Similaire à 3. functions modules_programs (1) (20)

Python programming variables and comment
Python programming variables and commentPython programming variables and comment
Python programming variables and comment
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
CH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptxCH.4FUNCTIONS IN C (1).pptx
CH.4FUNCTIONS IN C (1).pptx
 
Functions
FunctionsFunctions
Functions
 
Python programming - Functions and list and tuples
Python programming - Functions and list and tuplesPython programming - Functions and list and tuples
Python programming - Functions and list and tuples
 
Functions_new.pptx
Functions_new.pptxFunctions_new.pptx
Functions_new.pptx
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Chapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer ScienceChapter Functions for grade 12 computer Science
Chapter Functions for grade 12 computer Science
 
PSPC-UNIT-4.pdf
PSPC-UNIT-4.pdfPSPC-UNIT-4.pdf
PSPC-UNIT-4.pdf
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
Functions
FunctionsFunctions
Functions
 

Dernier

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 

Dernier (20)

MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptxYOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
YOUVE_GOT_EMAIL_PRELIMS_EL_DORADO_2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 

3. functions modules_programs (1)

  • 2. DATA, EXPRESSIONS, STATEMENTS • Python interpreter and interactive mode • Values and types • Variables, expressions, statements, tuple assignment • Precedence of operators • Comments • Functions • Modules • Illustrative programs: • exchange the values of two variables • circulate the values of n variables • distance between two points
  • 3. FUNCTIONS • A function is a set of instructions that are used to perform specified task • Functions provide better modularity and a high degree of code reusing. • complex tasks can be sub-divided into manageable tasks. • Routines, subroutines, procedures, methods, subprograms. • Python offers many built-in functions like print(), input() • It also supports to generate our own functions called as user-defined functions
  • 4. FUNCTIONS[Contd..] • Need-user-defined functions – Complex program – no. of problems, too large and complex – Debugging, testing and maintenance becomes difficult. – Program – Divided into parts – independently coded and later combined into single program. – Code is repeated in the program, designed as a function, called and used – required. – It save both time and memory
  • 5. FUNCTIONS[Contd..] • Advantages 1. The length can be reduced by dividing it into smaller functions. 2. It is easy to locate and debug an error. 3. User defined functions used whenever necessary. 4. Avoids coding of repeated instructions. 5. Build customised library of repeatedly used routines. 6. Top-down programming approach.
  • 6. FUNCTIONS[Contd..] • Function elements: – Function Definition – Function Invocation(call) • Function Definition: – The function definition contains the code that determines the function behaviour. • Component of function definition: – Starts with the keyword def followed by the function name – pair of parenthesis (). – Function name is used to identify it. – The values are passed as parameters (or) arguments which must be placed inside the parenthesis. – A colon (:) symbol is used to indicate end of function header. – The first statement – optional statement – docstring. – The function body consists of one or more valid python statements with similar indentation level – The last statement return [expression] exits a function • Syntax def funtionname(parameters): “functiondocstring ” Function body return [expression];
  • 7. FUNCTIONS[Contd..] • Function Invocation [function call]: • Once the structure of the function is defined, the function can be executed by calling it from other function or program or even from python prompt. • Program 1: def count_to_5(): “ this function prints the value between 1 to 5” for i in range(1,6): print(i) print (‘Function call to print numbers:’) count_to_5()// fn call print (‘Function call to print nos.again:’) count_to_5()// fn call • Output: Function call to print numbers: Function call to print no’s again: 1 1 2 2 3 3 4 4 5 5
  • 8. FUNCTIONS[Contd..] • Program 2: def cube(x=3): “ this function will return the cube of a number” y = x * x * x print(y) cube(3)// fn call • Output: 27 • Program 3: def odd_even(85): if(number%2==0): print (‘The number’,number,’is even’) else: print(‘The number’,number,’is odd’) return result = int(input(‘Enter a number:’)) odd_even(result)// fn call • Output: Enter a number: 85 The number 85 is odd
  • 9. FUNCTIONS[Contd..] • Function argument: – User-defined functions can take different types of arguments. – The arguments types and their meanings are predefined and can’t be changed. 1. Required Arguments: – Required arguments are the arguments passed to a function in correct positioned order • Example: def printing(str): ‘“The prints string passed to the function”’// doc string print(str) return; printing()
  • 10. FUNCTIONS[Contd..] 2. Keyword arguments: – Functions can be called using keyword arguments. – Caller identifies the arguments by the parameter name. – When the function is called in this method, the order(ie) the position of the arguments can be changed. • Example: def printinfo(name,phno): print(“Name:”,name) print(“phone no:”, phno) return; #A function with 2 keyword arguments printinfo (name=’xxx’, phno = 123456789) // fn call #A fn.call with out of order arguments printinfo(phno= 123456789, name=’xxx’) #A fn.call with 2 positional arguments printinfo(‘xxx’. 123456789) #A fn.call with | positional arguments & keyword argument printinfo(‘xxx’,phno=123456789)
  • 11. FUNCTIONS[Contd..] • Default Arguments: – A default value can be given to the parameter by means of the assignment operator. – Several no. of parameter in a function can have a default value. – But once the function has a default parameter, all the arguments to its right must also have default value • Example: def printfinfo (name,phno=’123456789’): print(‘name=’,name) print(phoneno=’,phone) return; printinfo(name=’xxx’) printinfo(name=’xxx’,phno=’567891234’) • In this function, the parameter name does not have a default value and is required during a call. The parameter phno has a default value of ‘12456789’. So it is optional during a call. If a value is provided, it will overwrite the default value. def printinfsso(name=’AAA’,phno) • Syntax Error: non-default argument follows default argument.
  • 12. FUNCTIONS[Contd..] • Variable-length arguments: – Not be familiar with the no. of arguments that will be passed to a function. – Function calls with subjective number of parameters. – asterisk(*) before the arguments name is used to indicate variable-length arguments. • Example: def greeting (*person-name):// fn definition for name in person-name: print(“Hai”,name) return; greeting(“XXX”, “YYY”, “ZZZ”)//fn call • Output: Hai XXX Hai YYY Hai ZZZ
  • 13. FUNCTIONS[Contd..] • An asterisk (*) is placed before the variable name that will hold the values of all non keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. For example: def printinfo( arg1, *vartuple ): "This is test" print "Output is: " print arg1 for var in vartuple: print var return; printinfo( 10 ); printinfo( 70, 60, 50 ); • This would produce following result: Output is: 10 Output is: 70 60 50
  • 14. The Anonymous Functions • The lambda keyword to create small anonymous functions. These functions are called anonymous because they are not declared in the standard manner by using the def keyword. • Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions. • An anonymous function cannot be a direct call to print because lambda requires an expression. • Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace. • Although it appears that lambda's are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is by passing function stack allocation during invocation for performance reasons. • Syntax: lambda [arg1 [,arg2,.....argn]]:expression
  • 15. Example • Following is the example to show how lambda form of function works: sum = lambda arg1, arg2: arg1 + arg2; print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40
  • 16. Scope of Variables • All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. • The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python: Global variables Local variables • Global vs. Local variables: • Variables that are defined inside a function body have a local scope, and those defined outside have a global scope. • This means that local variables can be accessed only inside the function in which they are declared whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope.
  • 17. Example total = 0; # This is global variable. def sum( arg1, arg2 ): "Add both the parameters" total = arg1 + arg2; print "Inside the function local total : ", total return total; # Now you can call sum function sum( 10, 20 ); print "Outside the function global total : ", total • This would produce following result: Inside the function local total : 30 Outside the function global total : 0
  • 18. FUNCTIONS[Contd..] • Function parameters: – Specified within pair of parentheses in the function definition. – The values of their variables are defined in function call. – The names given in the function definition are called parameters – The values supplied in function call are called arguments. def find_max (a,b): if a>b: print(a,’is max’ ) elif a==b: print (a, ‘is equal to’,b) else: print(b,’is max’) find_max(5,9) x=46 y=76 find_max(x,y)
  • 19. MODULES • A file that contains a collection of related functions. • A module allows user to logically organize python code grouping • Python has many built-in modules • e.g.) math module • >>>import math • This statement creates a module object named math. • < module ‘math’ (built-in)> • Contains the function and variables. • To access the function within module specify the name of the module and name of the function separated by a dot. • Example: >>> math.log10(200) 2.3010299956639813 3.1622776601683795
  • 20. MODULES[Contd..] • Writing Modules • Any file that contains python code can be imported as a module. Assume a file add Module.py with the following code def add (a,b): c= a+b print(c) add(10,20) • We can import this like >>>import add Module 30 • Now we have a module object add Module. • This module provides add() function. >>>add Module. add(100,200) 300
  • 21. MODULES[Contd..] • The drawback with this is that when module is imported it runs the test code at the bottom. • To avoid it, add the following idiom : if _name_==’_main_’; • _name_ is a built in variable that is set when the program starts. If the program is running as a script, _name_ has the value _main_, in the case, the test code runs. Otherwise, if the module is imported, the test code is skipped def add (a,b): c=a+b print(c) if _name_==_main_: add(10,20) • Now on importing addModule, the test case will not run • >>>import addModule.
  • 22. ILLUSTRATIVE PROGRAM Exchange the values of a variables 1. Exchange the values of a variables • Exchange values of 2 variables can be done in different ways. – Using temporary variable – Without using temporary variable. • Using temporary variable a= int (input(‘Enter first value :’)) b= int (input(‘Enter second value :’)) temp=a a=b b= temp print (‘After Swapping’) print (‘First value:’, a) print (‘second value:’, b)
  • 23. ILLUSTRATIVE PROGRAM Exchange the values of a variables [Contd..] OUTPUT: Enter first value : 10 Enter second value : 20 After Swapping First value : 20 Second value : 10
  • 24. ILLUSTRATIVE PROGRAM Exchange the values of a variables [Contd..] • Without using temporary variable 1. Using tuple assignment: a= int (input (‘ Enter first value:’)) b= int (input (‘Enter second value:’)) a,b=b,a print (‘After Swapping’) print (‘First value:’ ,a) print (‘Second value:’, b)
  • 25. ILLUSTRATIVE PROGRAM Exchange the values of a variables [Contd..] 2. Using arithmetic operator: • Addition & Subtraction Multiplier & Division a=a+b a=a*b b=a-b b=a/b a=a-b a=a/b 3. Using bitwise operator: • If variables are integers , then swapping can be done with help of bitwise XOR operator. a=a^b b=a^b a=a^b
  • 26. ILLUSTRATIVE PROGRAM Circulate the value of N variables • Circulating a python list by an arbitrary number of items to the right or left can be performed by list slicing operator. • Circulation of the list by n position can be achieved by slicing the array into two and concatenating them. • Slicing is done as nth element to end element + beginning element to n- 1th element. • Example: • 1, 2, 3, 4, 5, 6, 7 • If n=2, then the given list is rotated 2 positions towards left side. • 3, 4, 5, 6, 7, 1, 2  Left circulated list • If n=-2 then the given list is rotated 2 position towards right side. • 6, 7, 1, 2, 3, 4, 5  Right circulated list
  • 27. ILLUSTRATIVE PROGRAM Circulate the value of N variables [Contd..] • Function to perform this circulation: def circulate ( list , n): return list [n:] + list [:n] >>> circulate ([1, 2, 3, 4, 5, 6, 7], 2) [3, 4, 5, 6, 7, 1, 2] >>>circulate ([1, 2, 3, 4, 5, 6, 7] , 2) [ 6, 7, 1, 2, 3, 4, 5]
  • 28. ILLUSTRATIVE PROGRAM Test for Leap Year • Python provides isleap() function in calendar module to check whether a year is leap year or not . >>> import calendar >>> calendar ……..// provides info path >>> calendar . isleap (2000) True >>> calendar . isleap (2003) False
  • 29. ILLUSTRATIVE PROGRAM Distance between points • To find the distance between 2 points , given by the coordinates (X1,Y1) and (X2,Y2), the Pythagorean theorem is used • By the Pythagorean theorem , the distance is : distance = (x2-x1)2 + (y2-y1)2 • Example: def distance (x1, y1, x2, y2): dx = x2 – x1 dy = y2 – y1 dsquare = dx * dx + dy * dy dist = dsquare **0.5 return result >>> dist = distance (1, 2, 3, 5) >>> print (dist)