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)