KEMBAR78
Python programming- Part IV(Functions) | PPTX
Python Programming
Functions
Megha V
Research Scholar
Kannur University
05-11-2021 meghav@kannuruniv.ac.in 1
Functions
• Built-in functions
• input()
• print()
• eval() function
The function eval() is used to evaluate the value of a string
Eg:
>>>eval(‘15’)
15
>>>eval(’15+10’)
25
05-11-2021 meghav@kannuruniv.ac.in 2
Functions
Composition
• The value returned by a function may be used as an argument for another
function in a nested manner .
eg:
>>>n=eval(input(‘Enter a number’))
Enter a number 56
>>>n
56
>>>e=eval(input(‘Enter an arithmetic expression:’))
Enter an arithmetic expression: 12.0+13.0*2
>>>e
38.0
05-11-2021 meghav@kannuruniv.ac.in 3
Functions
type() function
• Values or objects in Python are classified into types of classes
• type() function return the type of a value
• eg:
>>>print(type(12),type(12.5),type(‘hello’),type(int))
<class‘int‘><class 'float’><class‘str’><class 'type’>
round() function
• The round function
• n rounds a number up to specific number of decimal places,
eg:
>>>print(round(89.652,2),round(89.635),round(89.635,0))
89.65 90 90.0
>>>print(round(34.12,1)round(-34.63))
34.1 -35
05-11-2021 meghav@kannuruniv.ac.in 4
Functions
pow() function
• pow(a,b) computes ab
• Random number generation
random() function
• generates a random number in the range [0,1]
• Python module random contains this function
import random
if random.random()<0.5
print(‘Player A plays the first game’)
randint() function
• Chooses an integer in the specified range()
• randint(1,n) will randomly generate a number in the range 1 to n
05-11-2021 meghav@kannuruniv.ac.in 5
Functions
• Functions from math Module
Function Description
ceil(x) returns the smallest integer greater than or equal to x
floor(x) returns the largest integer less than or equal to x
fabs(x) returns the absolute value of x
exp(x) returns the value of expression e**x
log(x,b) returns the log(x) to the base b
log10(x) returns the log(x) to the base 10
pow(x,y) xy
sqrt(x) square root of x
05-11-2021 meghav@kannuruniv.ac.in 6
Functions
• Functions from math Module
Function Description
sin(x) sine of x in radians
tan(x) tangent of x in radians
cos(x) cosine of x in radians
acos(x) inverse cosine of x in radians
asin(x) inverse sine of x in radians
atan(x) inverse tangent of x in radians
degrees(x) returns a value in degree equivalent of input value x( in radians)
radians(x) returns a value in radian equivalent of input value x( in degrees)
05-11-2021 meghav@kannuruniv.ac.in 7
Functions from math Module
• examples:
>>> import math as m
>>>m.ceil(3.4)
4
>>>m.floor(3.7)
3
>>>m.fabs(-3)
3
>>>m.exp(2)
7.38905609893
>>>m.log(32,2)
5.0
>>>m.log10(100)
2.0
>>>m.pow(3,3)
27.0
>>>m.sqrt(65)
8.0622577
>>>m.cos(m.pi)
-1.0
>>>m.sin(m.pi/2)
1.0
>>>m.tan(m.pi/4)
0.999999
>>>m.acos(1)
0.0
>>>m.asin(1)
1.57079632
>>>m.atan(1)
0.7853981
05-11-2021 meghav@kannuruniv.ac.in 8
Function definition and calling the function
def function_name(comma_separated_list_of_parameters):
statements
• Just below def, begin with four spaces- indentation
• Every Python module has a built-in variable called _name_
-containing the name of the module
05-11-2021 meghav@kannuruniv.ac.in 9
Function definition and calling the function
• Eg:
def triangle():
print(‘ *’)
print(‘**’)
print(‘***’)
print(‘****’)
def square(): triangle(), square()-callee function
print(‘****’) main() – caller function
print(‘****’)
print(‘****’)
print(‘****’)
def main():
triangle()
print()
square()
if _name_==‘_main_’
main()
print(‘End of Program’)
05-11-2021 meghav@kannuruniv.ac.in 10
Fruitful function vs void function
• A function that returns a value if often called a fruitful function
• A function that does not return a value is called a void function
Default Parameter Values
• The function parameters may be assigned initial values, also called default
values
>>>areaRectangle(5)
• The default parameters must not be followed by non-default parameters
>>>def areaRectangle(length=10,breadth) #Syntax error
05-11-2021 meghav@kannuruniv.ac.in 11
return statement
• The return keyword is to exit a function and return a value.
Eg1:
def myfunction():
return 3+3
print(myfunction())
Eg2:
• Statements after the return line will not be executed:
def myfunction():
return 3+3
print("Hello, World!")
print(myfunction())
05-11-2021 meghav@kannuruniv.ac.in 12
Keyword Arguments
• You can also send arguments with the syntax
key = value
• This way the order of the arguments does not matter
Eg:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1="Emil",child2="Tobias",child3="Linus")
05-11-2021 meghav@kannuruniv.ac.in 13
Scope and lifetime of variable
• A variable is only available from inside the region it is created.
This is called scope.
Local Scope
• A variable created inside a function belongs to the local scope of
that function, and can only be used inside that function
def myfunc():
x = 300
print(x)
myfunc()
05-11-2021 meghav@kannuruniv.ac.in 14
Scope and lifetime of variable
Function Inside Function
• As explained in the example above, the variable x is not available
outside the function, but it is available for any function inside the
function
def myfunc():
x = 300
def myinnerfunc():
print(x)
myinnerfunc()
myfunc()
05-11-2021 meghav@kannuruniv.ac.in 15
Scope and lifetime of variable
Global Scope
• A variable created in the main body of the Python code is a
global variable and belongs to the global scope.
• Global variables are available from within any scope, global and
local.
x = 300
def myfunc():
print(x)
myfunc()
print(x)
05-11-2021 meghav@kannuruniv.ac.in 16
Scope and lifetime of variable
Naming Variables
• If you operate with the same variable name inside and outside of
a function
• Python will treat them as two separate variables, one available in
the global scope (outside the function) and one available in the
local scope (inside the function):
x = 300
def myfunc():
x = 200
print(x) #200
myfunc()
print(x) #300
05-11-2021 meghav@kannuruniv.ac.in 17
Scope and lifetime of variable
Global Keyword
• If you need to create a global variable, but are stuck in the local scope, you
can use the global keyword.
• The global keyword makes the variable global.
def myfunc():
global x
x = 300
myfunc()
print(x)
05-11-2021 meghav@kannuruniv.ac.in 18
Arbitrary Arguments, *args
• If you do not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
• This way the function will receive a tuple of arguments, and can access the
items accordingly:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
05-11-2021 meghav@kannuruniv.ac.in 19
Arbitrary Keyword Arguments, **kwargs
• If you do not know how many keyword arguments that will be passed into your
function, add two asterisk: ** before the parameter name in the function
definition.
• This way the function will receive a dictionary of arguments, and can access the
items accordingly:
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
05-11-2021 meghav@kannuruniv.ac.in 20
Command line arguments
• We may choose to run the Python script from the command line interface
1.Open the directory(F:PythonCodeCh2) containing the file area.py
2.Open command prompt window using an option in context menu
3. Execute the command: python area.py
F:PythonCodeCh2>python area.py
Enter the following values for rectangle
Length: integer value:20
Breadthe:integer value:10
Area of rectangle is 200
05-11-2021 meghav@kannuruniv.ac.in 21
Command line arguments
• We may also take the input as command line arguments while executing a script
from the command prompt
F:PythonCodeCh2> python areal.py 20 10
Area of rectangle is 200
• In above command 20 and 10 save as inputs for the script areal.py
• We execute the script from command line
• It takes the name of the script as first argument and followed by other input
arguments and store them in the list sys.argv
• We access the arguments stored in arg using indeces argv[0], argv[1], argv[2] etc
05-11-2021 meghav@kannuruniv.ac.in 22

Python programming- Part IV(Functions)

  • 1.
    Python Programming Functions Megha V ResearchScholar Kannur University 05-11-2021 meghav@kannuruniv.ac.in 1
  • 2.
    Functions • Built-in functions •input() • print() • eval() function The function eval() is used to evaluate the value of a string Eg: >>>eval(‘15’) 15 >>>eval(’15+10’) 25 05-11-2021 meghav@kannuruniv.ac.in 2
  • 3.
    Functions Composition • The valuereturned by a function may be used as an argument for another function in a nested manner . eg: >>>n=eval(input(‘Enter a number’)) Enter a number 56 >>>n 56 >>>e=eval(input(‘Enter an arithmetic expression:’)) Enter an arithmetic expression: 12.0+13.0*2 >>>e 38.0 05-11-2021 meghav@kannuruniv.ac.in 3
  • 4.
    Functions type() function • Valuesor objects in Python are classified into types of classes • type() function return the type of a value • eg: >>>print(type(12),type(12.5),type(‘hello’),type(int)) <class‘int‘><class 'float’><class‘str’><class 'type’> round() function • The round function • n rounds a number up to specific number of decimal places, eg: >>>print(round(89.652,2),round(89.635),round(89.635,0)) 89.65 90 90.0 >>>print(round(34.12,1)round(-34.63)) 34.1 -35 05-11-2021 meghav@kannuruniv.ac.in 4
  • 5.
    Functions pow() function • pow(a,b)computes ab • Random number generation random() function • generates a random number in the range [0,1] • Python module random contains this function import random if random.random()<0.5 print(‘Player A plays the first game’) randint() function • Chooses an integer in the specified range() • randint(1,n) will randomly generate a number in the range 1 to n 05-11-2021 meghav@kannuruniv.ac.in 5
  • 6.
    Functions • Functions frommath Module Function Description ceil(x) returns the smallest integer greater than or equal to x floor(x) returns the largest integer less than or equal to x fabs(x) returns the absolute value of x exp(x) returns the value of expression e**x log(x,b) returns the log(x) to the base b log10(x) returns the log(x) to the base 10 pow(x,y) xy sqrt(x) square root of x 05-11-2021 meghav@kannuruniv.ac.in 6
  • 7.
    Functions • Functions frommath Module Function Description sin(x) sine of x in radians tan(x) tangent of x in radians cos(x) cosine of x in radians acos(x) inverse cosine of x in radians asin(x) inverse sine of x in radians atan(x) inverse tangent of x in radians degrees(x) returns a value in degree equivalent of input value x( in radians) radians(x) returns a value in radian equivalent of input value x( in degrees) 05-11-2021 meghav@kannuruniv.ac.in 7
  • 8.
    Functions from mathModule • examples: >>> import math as m >>>m.ceil(3.4) 4 >>>m.floor(3.7) 3 >>>m.fabs(-3) 3 >>>m.exp(2) 7.38905609893 >>>m.log(32,2) 5.0 >>>m.log10(100) 2.0 >>>m.pow(3,3) 27.0 >>>m.sqrt(65) 8.0622577 >>>m.cos(m.pi) -1.0 >>>m.sin(m.pi/2) 1.0 >>>m.tan(m.pi/4) 0.999999 >>>m.acos(1) 0.0 >>>m.asin(1) 1.57079632 >>>m.atan(1) 0.7853981 05-11-2021 meghav@kannuruniv.ac.in 8
  • 9.
    Function definition andcalling the function def function_name(comma_separated_list_of_parameters): statements • Just below def, begin with four spaces- indentation • Every Python module has a built-in variable called _name_ -containing the name of the module 05-11-2021 meghav@kannuruniv.ac.in 9
  • 10.
    Function definition andcalling the function • Eg: def triangle(): print(‘ *’) print(‘**’) print(‘***’) print(‘****’) def square(): triangle(), square()-callee function print(‘****’) main() – caller function print(‘****’) print(‘****’) print(‘****’) def main(): triangle() print() square() if _name_==‘_main_’ main() print(‘End of Program’) 05-11-2021 meghav@kannuruniv.ac.in 10
  • 11.
    Fruitful function vsvoid function • A function that returns a value if often called a fruitful function • A function that does not return a value is called a void function Default Parameter Values • The function parameters may be assigned initial values, also called default values >>>areaRectangle(5) • The default parameters must not be followed by non-default parameters >>>def areaRectangle(length=10,breadth) #Syntax error 05-11-2021 meghav@kannuruniv.ac.in 11
  • 12.
    return statement • Thereturn keyword is to exit a function and return a value. Eg1: def myfunction(): return 3+3 print(myfunction()) Eg2: • Statements after the return line will not be executed: def myfunction(): return 3+3 print("Hello, World!") print(myfunction()) 05-11-2021 meghav@kannuruniv.ac.in 12
  • 13.
    Keyword Arguments • Youcan also send arguments with the syntax key = value • This way the order of the arguments does not matter Eg: def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1="Emil",child2="Tobias",child3="Linus") 05-11-2021 meghav@kannuruniv.ac.in 13
  • 14.
    Scope and lifetimeof variable • A variable is only available from inside the region it is created. This is called scope. Local Scope • A variable created inside a function belongs to the local scope of that function, and can only be used inside that function def myfunc(): x = 300 print(x) myfunc() 05-11-2021 meghav@kannuruniv.ac.in 14
  • 15.
    Scope and lifetimeof variable Function Inside Function • As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function def myfunc(): x = 300 def myinnerfunc(): print(x) myinnerfunc() myfunc() 05-11-2021 meghav@kannuruniv.ac.in 15
  • 16.
    Scope and lifetimeof variable Global Scope • A variable created in the main body of the Python code is a global variable and belongs to the global scope. • Global variables are available from within any scope, global and local. x = 300 def myfunc(): print(x) myfunc() print(x) 05-11-2021 meghav@kannuruniv.ac.in 16
  • 17.
    Scope and lifetimeof variable Naming Variables • If you operate with the same variable name inside and outside of a function • Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function): x = 300 def myfunc(): x = 200 print(x) #200 myfunc() print(x) #300 05-11-2021 meghav@kannuruniv.ac.in 17
  • 18.
    Scope and lifetimeof variable Global Keyword • If you need to create a global variable, but are stuck in the local scope, you can use the global keyword. • The global keyword makes the variable global. def myfunc(): global x x = 300 myfunc() print(x) 05-11-2021 meghav@kannuruniv.ac.in 18
  • 19.
    Arbitrary Arguments, *args •If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition. • This way the function will receive a tuple of arguments, and can access the items accordingly: def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") 05-11-2021 meghav@kannuruniv.ac.in 19
  • 20.
    Arbitrary Keyword Arguments,**kwargs • If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition. • This way the function will receive a dictionary of arguments, and can access the items accordingly: def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes") 05-11-2021 meghav@kannuruniv.ac.in 20
  • 21.
    Command line arguments •We may choose to run the Python script from the command line interface 1.Open the directory(F:PythonCodeCh2) containing the file area.py 2.Open command prompt window using an option in context menu 3. Execute the command: python area.py F:PythonCodeCh2>python area.py Enter the following values for rectangle Length: integer value:20 Breadthe:integer value:10 Area of rectangle is 200 05-11-2021 meghav@kannuruniv.ac.in 21
  • 22.
    Command line arguments •We may also take the input as command line arguments while executing a script from the command prompt F:PythonCodeCh2> python areal.py 20 10 Area of rectangle is 200 • In above command 20 and 10 save as inputs for the script areal.py • We execute the script from command line • It takes the name of the script as first argument and followed by other input arguments and store them in the list sys.argv • We access the arguments stored in arg using indeces argv[0], argv[1], argv[2] etc 05-11-2021 meghav@kannuruniv.ac.in 22