SlideShare a Scribd company logo
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

More Related Content

What's hot

Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python : Functions
Python : FunctionsPython : Functions
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Iteration
IterationIteration
Iteration
Pooja B S
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88
Mahmoud Samir Fayed
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Arrays
ArraysArrays
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
Intro C# Book
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 

What's hot (19)

Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
Python
PythonPython
Python
 
Iteration
IterationIteration
Iteration
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Python numbers
Python numbersPython numbers
Python numbers
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
Arrays
ArraysArrays
Arrays
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 

Similar to Python programming- Part IV(Functions)

Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
Koteswari Kasireddy
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
paijitk
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
paijitk
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
kailashGusain3
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
RiteshKumarPradhan1
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
AkhilTyagi42
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
simenehanmut
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
SaraswathiTAsstProfI
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
Daddy84
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
Francesco Bruni
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptx
georgejustymirobi1
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
Muhammad Fayyaz
 
Python functions
Python functionsPython functions
Python functions
ToniyaP1
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functionsankita44
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
tcsonline1222
 
Functions
FunctionsFunctions
Functions
PralhadKhanal1
 
Functions
FunctionsFunctions
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
reddyprasad reddyvari
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
Knoldus Inc.
 

Similar to Python programming- Part IV(Functions) (20)

Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
3. functions modules_programs (1)
3. functions modules_programs (1)3. functions modules_programs (1)
3. functions modules_programs (1)
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Introduction to Functional Programming
Introduction to Functional ProgrammingIntroduction to Functional Programming
Introduction to Functional Programming
 
PYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptxPYTHON-PROGRAMMING-UNIT-II (1).pptx
PYTHON-PROGRAMMING-UNIT-II (1).pptx
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Python functions
Python functionsPython functions
Python functions
 
Part 3-functions
Part 3-functionsPart 3-functions
Part 3-functions
 
cbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptxcbse class 12 Python Functions2 for class 12 .pptx
cbse class 12 Python Functions2 for class 12 .pptx
 
Functions
FunctionsFunctions
Functions
 
Functions
FunctionsFunctions
Functions
 
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulinkMATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
MATLAB/SIMULINK for Engineering Applications day 2:Introduction to simulink
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 

More from Megha V

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
Megha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
Megha V
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technology
Megha V
 
Digital initiatives in higher education
Digital initiatives in higher educationDigital initiatives in higher education
Digital initiatives in higher education
Megha V
 
Information and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationInformation and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviation
Megha V
 
Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,
Megha V
 
Information and communication technology(ict)
Information and communication technology(ict)Information and communication technology(ict)
Information and communication technology(ict)
Megha V
 

More from Megha V (19)

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
 
Python programming
Python programmingPython programming
Python programming
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technology
 
Digital initiatives in higher education
Digital initiatives in higher educationDigital initiatives in higher education
Digital initiatives in higher education
 
Information and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationInformation and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviation
 
Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,
 
Information and communication technology(ict)
Information and communication technology(ict)Information and communication technology(ict)
Information and communication technology(ict)
 

Recently uploaded

Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
Vivekanand Anglo Vedic Academy
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 

Recently uploaded (20)

Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
The French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free downloadThe French Revolution Class 9 Study Material pdf free download
The French Revolution Class 9 Study Material pdf free download
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 

Python programming- Part IV(Functions)

  • 1. Python Programming Functions Megha V Research Scholar 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 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
  • 4. 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
  • 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 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 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