SlideShare a Scribd company logo
1 of 14
Functions
• Function:
• Block of statements are grouped together and is given a name which can be used to invoke
(call) it from other parts of the program.
• Functions can be either Built-in functions or User-defined functions
• Built-In Functions:
Function name Syntax Explanation
abs() abs(x), where x is an integer or
floating point number
abs() function returns the
absolute value of a number
min() Min(arg_1,arg_2….arg_n)
Where arg_1, arg_2…arg_n are
arguments
Returns the smallest of 2 or
more arguments
max() Max(arg_1,arg_2….arg_n) Where
arg_1, arg_2…arg_n are arguments
Returns the maximum of 2 or
more arguments
Divmod() Divmod(a,b) where x and y are
numbers representing numerator
and denominator
Returns a pair of numbers
which are quotient and
remainder. (a//b, a%b)
Pow() Pow(x,y) where x and y are
numbers
Pow(x,y) is equivalent to x**y
Len() Len(s) where s may be string, byte,
list, tuple, range, dictionary or a set
Len() function returns the
length of the number of items
in an object
• Commonly Used Modules
• Modules are reusable libraries of code having .py extension. Python has many built in modules
as part of the standard library.
• Syntax: import module_name
• Math module contains mathematical functions which can be used by the programmer.
• Syntax: module_name.function_name()
• Eg:
• >>>import math
• >>>print(math.ceil(5.4))
• 6
• >>>print(math.sqrt(4))
• 2.0
• >>>print(math.pi)
• 3.141592653
• >>>print(math.cos(1))
• 0.54030
• >>>math.factorial(6)
• 720
• >>>math.pow(2,3)
• 8
• Built-in function dir() returns a sorted list of strings containing the names of functions, classes
and variables as defined in the module.
• >>>dir(math)
• Help: help() The argument to the help() is a string, which is looked up as the name of a module,
function, class, method, keyword or documentation topic.
• Eg:
• >>> help(math.gcd)
• Random module: This is used to generate random numbers.
• >>>import random
• >>>print(random.random())
• 0.2551914
• >>>print(random.randint(5,10))
• 9
• Random() function generates a random floating point number between 0 and 1.
• Syntax: random.randint(start,stop) # generates a integer number between start and stop arguments
• 3rd party modules or libraries can be installed and managed using python’s package manager pip.
Arrow is a popular library used to create, manipulate format and convert date, time and timestamp.
• The Syntax for pip is
• Pip install module_name
• >>>import arrow
• >>>a=arrow.utcnow()
• >>>a.now() # current date and time is displayed using now function.
• <Arrow[date and time]>
• Function definition and calling the function
• Def function_name(parameter_1, parameter_2, …………….parameter_n):
– Statement(s)
• Def – keyword
• Function_name = user defined
• Colon should be present at the end
• Indentation should be provided to the statement following the function_name.
• 1. The function Name: The rules are same as variables. We can use letters, numbers or an
underscore but it cannot start with a number.
• Keyword cannot be used as a function name.
• 2. List of parameters to the function are enclosed in parentheses and separated by commas.
Some functions do not have any parameters at all.
• 3. Colon is required at the end of function header.
• 4. Block of statements that define the body of function start at the next line of function header
and they must have the same indentation level.
• Syntax: function_name(argument_1, argument_2……argument_n)
• There must be one to one correspondence between the formal parameters in the function
definition and the actual arguments of the calling function.
• When a function is called, the control flows from the calling function to the called function.
Once the block of statements in the function definition is executed, the control flows back to
the calling function and proceeds to the next statement.
• Before executing the code in the source program, the python interpreter automatically
defines a few special variables.
• Python interpreter sets the special built-in _name_ variable to have a string value of “_main_”.
• After setting up these special variables, python interpreter reads the program to execute the
code found in it. All the code is at indentation level 0 gets executed.
• The special vaiable, _name_ with “_main”_ is the entry point of your program. All the functions
should be invoked within main() function.
• Eg:
• def function_definition_with_no_argument():
• print(“This is a function definition with no arguments”)
• def function_definition_with_one_argument(message):
• print(“This is a function definition with {message}”)
• def main():
• function_definition_with_no_argument()
• function_definition_with_one_argument(“one argument”)
• If_name_==“_main_”:
• main()
• OUTPUT:
• This is a function definition with no arguments
• This is a function definition with one argument
• The return Statement and void Function
• This is used to return value to the calling function so that it is stored in a variable.
• Syntax: return[expression_list]
• In Python, we can define functions without a return statement. Such functions are called void
functions.
• A function cal return only a single value but that value can be a list or tuple.
• Eg:
• god_name=input("enter the name of god")
• def greek_mythology(god_name):
• print(f"The God of seas according to greek mythology is {god_name}")
• def main():
• print("Story of our historians")
• greek_mythology(god_name)
• if __name__=="__main__":
• print("check this")
• main()
•
• #Program to return multiple values from return statement separated by comma
• def world_war():
• alliance_world_war = input("which alliance won world war 2?")
• world_war_end_year = input("when did world war 2 end?")
• return alliance_world_war, world_war_end_year
• def main():
• alliance, war_end_year = world_war()
• print(f"The war was won by {alliance} and the war ended in {war_end_year}")
• if __name__=="__main__":
• main()
• Examples of math programs returning values
• Scope and Lifetime of Variables
• There are two scopes: global and local.
• Global variables have global scope. A variable defined inside a function is called a local variable.
Local variable is created and destroyed every time the function is executed. It cannot be accessed
outside the function.
• Global variables can be accessed inside a function if there will be no local variables with the same
name.
• test_var = 10
• def outer_func():
• test_var = 60
• def inner_func():
• test_var = 100
• print("local var inner func is ", test_var)
• inner_func()
• print("local var outer func is", test_var)
• outer_func()
• print("global var value is", test_var)
• Output:
• local var inner func is 100
• local var outer func is 60
• global var value is 10
Nested Function:
A nested function (inner function) can inherit the arguments and variables of its outer function.
The inner function can use the arguments and variables of the outer function while the outer
function cannot use the arguments and variables of the inner function.
The inner function definition is invoked by calling it from within the outer function definition.
def add_cubes(a,b):
def cube_surface_area(x):
return 6* pow(x,2)
return cube_surface_area(a) + cube_surface_area(b)
def main():
result=add_cubes(2,3)
print(f"The surface area after adding two cubes is {result}")
if __name__=="__main__":
main()
The parameters of add_cubes(a,b) function are passed as arguments to the calling function
cube_surface_area(x). The inner function is called within the outer function.
Output:
The surface area after adding two cubes is 78
Default Parameters:
Any calling function must provide arguments for all required parameters in the function
definition but can omit the arguments for default parameters. If no argument is sent for that
parameter, the default values is used.
def work_area(prompt, domain=“Data Analytics”):
print(f”{prompt} {domain}”)
Def main():
work_area(“ Sam works here in ”)
work_area(“Alice has interest in”, “Internet of Things”)
If__name__==“__main__”:
main()
Output:
Sam works here in Data Analytics
Alice has interest in Internet of Things
Keyword Arguments:
Whenever you call a function with some values as its arguments, these values get assigned to the
parameters in the function definition according to their position.
In calling function, you can specify the argument name and their value in the form of
Kwarg = value. In calling function, keyword arguments must follow positional arguments.
No parameter in the function definition may receive a value more than once.
*args and **kwargs
They are used as parameters in function definitions.
*args and **kwargs allows you to pass a variable number of arguments to the calling function.
User might not know the the number of arguments in advance that will be passed to the calling
function.
*args : Allows you to pass a non-key worded variable length argument list to the calling function.
**kwargs as parameter in function allows you to pass key worded variable length dictionary
argument list to the calling function.
*args should come after all the positional paramters and **kwargs must come right at the end.
Command Line Arguments:
A python program can accept any number of arguments from the command line. Command line
arguments is a methodology in which user will give inputs to the program through the
console using commands.
You need to import sys module to access command line arguments. All the command line
arguments can be printed as a list of string by executing sys.argv.
Example:
import sys
def main():
print(f"sys.argv prints all the arguments at the command line including file name {sys.argv}")
print(f"len(sys.argv) prints the total number of command line arguments including file name
{len(sys.argv)}")
print("you can use for loop to traverse through sys.argv")
for arg in sys.argv:
print(arg)
if __name__=="__main__":
main()
Output
• C:UsersAdmin>python
C:/Users/Admin/AppData/Local/Programs/Python/Python311/cmdline1.py lion tiger mouse
• len(sys.argv) prints the total number of command line arguments including file name 4
• C:/Users/Admin/AppData/Local/Programs/Python/Python311/cmdline1.py
• lion
• tiger
• mouse

More Related Content

Similar to Python_Functions_Unit1.pptx

Similar to Python_Functions_Unit1.pptx (20)

Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
 
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
 
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
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
unit_2 (1).pptx
unit_2 (1).pptxunit_2 (1).pptx
unit_2 (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
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
unit_2.pptx
unit_2.pptxunit_2.pptx
unit_2.pptx
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Function
FunctionFunction
Function
 
Function in c
Function in cFunction in c
Function in c
 
functioninpython-1.pptx
functioninpython-1.pptxfunctioninpython-1.pptx
functioninpython-1.pptx
 
Chap 5 c++
Chap 5 c++Chap 5 c++
Chap 5 c++
 
Function in c
Function in cFunction in c
Function in c
 
Functions.pdf
Functions.pdfFunctions.pdf
Functions.pdf
 
Functionscs12 ppt.pdf
Functionscs12 ppt.pdfFunctionscs12 ppt.pdf
Functionscs12 ppt.pdf
 
Lecture6
Lecture6Lecture6
Lecture6
 

More from Koteswari Kasireddy

Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfKoteswari Kasireddy
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfKoteswari Kasireddy
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxKoteswari Kasireddy
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxKoteswari Kasireddy
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxKoteswari Kasireddy
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptxKoteswari Kasireddy
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxKoteswari Kasireddy
 

More from Koteswari Kasireddy (20)

DA Syllabus outline (2).pptx
DA Syllabus outline (2).pptxDA Syllabus outline (2).pptx
DA Syllabus outline (2).pptx
 
Chapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdfChapter-7-Sampling & sampling Distributions.pdf
Chapter-7-Sampling & sampling Distributions.pdf
 
Object_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdfObject_Oriented_Programming_Unit3.pdf
Object_Oriented_Programming_Unit3.pdf
 
unit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdfunit-3_Chapter1_RDRA.pdf
unit-3_Chapter1_RDRA.pdf
 
DBMS_UNIT_1.pdf
DBMS_UNIT_1.pdfDBMS_UNIT_1.pdf
DBMS_UNIT_1.pdf
 
business analytics
business analyticsbusiness analytics
business analytics
 
Relational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptxRelational Model and Relational Algebra.pptx
Relational Model and Relational Algebra.pptx
 
CHAPTER -12 it.pptx
CHAPTER -12 it.pptxCHAPTER -12 it.pptx
CHAPTER -12 it.pptx
 
WEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptxWEB_DATABASE_chapter_4.pptx
WEB_DATABASE_chapter_4.pptx
 
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptxUnit 4 chapter - 8 Transaction processing Concepts (1).pptx
Unit 4 chapter - 8 Transaction processing Concepts (1).pptx
 
Database System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptxDatabase System Concepts AND architecture [Autosaved].pptx
Database System Concepts AND architecture [Autosaved].pptx
 
Evolution Of WEB_students.pptx
Evolution Of WEB_students.pptxEvolution Of WEB_students.pptx
Evolution Of WEB_students.pptx
 
Presentation1.pptx
Presentation1.pptxPresentation1.pptx
Presentation1.pptx
 
Algorithm.pptx
Algorithm.pptxAlgorithm.pptx
Algorithm.pptx
 
Control_Statements_in_Python.pptx
Control_Statements_in_Python.pptxControl_Statements_in_Python.pptx
Control_Statements_in_Python.pptx
 
parts_of_python_programming_language.pptx
parts_of_python_programming_language.pptxparts_of_python_programming_language.pptx
parts_of_python_programming_language.pptx
 
linked_list.pptx
linked_list.pptxlinked_list.pptx
linked_list.pptx
 
matrices_and_loops.pptx
matrices_and_loops.pptxmatrices_and_loops.pptx
matrices_and_loops.pptx
 
algorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptxalgorithms_in_linkedlist.pptx
algorithms_in_linkedlist.pptx
 
Control_Statements.pptx
Control_Statements.pptxControl_Statements.pptx
Control_Statements.pptx
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
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
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
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
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
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
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
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
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
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
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
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
 
Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17Difference Between Search & Browse Methods in Odoo 17
Difference Between Search & Browse Methods in Odoo 17
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 

Python_Functions_Unit1.pptx

  • 2. • Function: • Block of statements are grouped together and is given a name which can be used to invoke (call) it from other parts of the program. • Functions can be either Built-in functions or User-defined functions • Built-In Functions: Function name Syntax Explanation abs() abs(x), where x is an integer or floating point number abs() function returns the absolute value of a number min() Min(arg_1,arg_2….arg_n) Where arg_1, arg_2…arg_n are arguments Returns the smallest of 2 or more arguments max() Max(arg_1,arg_2….arg_n) Where arg_1, arg_2…arg_n are arguments Returns the maximum of 2 or more arguments Divmod() Divmod(a,b) where x and y are numbers representing numerator and denominator Returns a pair of numbers which are quotient and remainder. (a//b, a%b) Pow() Pow(x,y) where x and y are numbers Pow(x,y) is equivalent to x**y Len() Len(s) where s may be string, byte, list, tuple, range, dictionary or a set Len() function returns the length of the number of items in an object
  • 3. • Commonly Used Modules • Modules are reusable libraries of code having .py extension. Python has many built in modules as part of the standard library. • Syntax: import module_name • Math module contains mathematical functions which can be used by the programmer. • Syntax: module_name.function_name() • Eg: • >>>import math • >>>print(math.ceil(5.4)) • 6 • >>>print(math.sqrt(4)) • 2.0 • >>>print(math.pi) • 3.141592653 • >>>print(math.cos(1)) • 0.54030 • >>>math.factorial(6) • 720 • >>>math.pow(2,3) • 8 • Built-in function dir() returns a sorted list of strings containing the names of functions, classes and variables as defined in the module. • >>>dir(math)
  • 4. • Help: help() The argument to the help() is a string, which is looked up as the name of a module, function, class, method, keyword or documentation topic. • Eg: • >>> help(math.gcd) • Random module: This is used to generate random numbers. • >>>import random • >>>print(random.random()) • 0.2551914 • >>>print(random.randint(5,10)) • 9 • Random() function generates a random floating point number between 0 and 1. • Syntax: random.randint(start,stop) # generates a integer number between start and stop arguments • 3rd party modules or libraries can be installed and managed using python’s package manager pip. Arrow is a popular library used to create, manipulate format and convert date, time and timestamp. • The Syntax for pip is • Pip install module_name • >>>import arrow • >>>a=arrow.utcnow() • >>>a.now() # current date and time is displayed using now function. • <Arrow[date and time]>
  • 5. • Function definition and calling the function • Def function_name(parameter_1, parameter_2, …………….parameter_n): – Statement(s) • Def – keyword • Function_name = user defined • Colon should be present at the end • Indentation should be provided to the statement following the function_name. • 1. The function Name: The rules are same as variables. We can use letters, numbers or an underscore but it cannot start with a number. • Keyword cannot be used as a function name. • 2. List of parameters to the function are enclosed in parentheses and separated by commas. Some functions do not have any parameters at all. • 3. Colon is required at the end of function header. • 4. Block of statements that define the body of function start at the next line of function header and they must have the same indentation level. • Syntax: function_name(argument_1, argument_2……argument_n) • There must be one to one correspondence between the formal parameters in the function definition and the actual arguments of the calling function. • When a function is called, the control flows from the calling function to the called function. Once the block of statements in the function definition is executed, the control flows back to the calling function and proceeds to the next statement.
  • 6. • Before executing the code in the source program, the python interpreter automatically defines a few special variables. • Python interpreter sets the special built-in _name_ variable to have a string value of “_main_”. • After setting up these special variables, python interpreter reads the program to execute the code found in it. All the code is at indentation level 0 gets executed. • The special vaiable, _name_ with “_main”_ is the entry point of your program. All the functions should be invoked within main() function. • Eg: • def function_definition_with_no_argument(): • print(“This is a function definition with no arguments”) • def function_definition_with_one_argument(message): • print(“This is a function definition with {message}”) • def main(): • function_definition_with_no_argument() • function_definition_with_one_argument(“one argument”) • If_name_==“_main_”: • main() • OUTPUT: • This is a function definition with no arguments • This is a function definition with one argument
  • 7. • The return Statement and void Function • This is used to return value to the calling function so that it is stored in a variable. • Syntax: return[expression_list] • In Python, we can define functions without a return statement. Such functions are called void functions. • A function cal return only a single value but that value can be a list or tuple. • Eg: • god_name=input("enter the name of god") • def greek_mythology(god_name): • print(f"The God of seas according to greek mythology is {god_name}") • def main(): • print("Story of our historians") • greek_mythology(god_name) • if __name__=="__main__": • print("check this") • main() •
  • 8. • #Program to return multiple values from return statement separated by comma • def world_war(): • alliance_world_war = input("which alliance won world war 2?") • world_war_end_year = input("when did world war 2 end?") • return alliance_world_war, world_war_end_year • def main(): • alliance, war_end_year = world_war() • print(f"The war was won by {alliance} and the war ended in {war_end_year}") • if __name__=="__main__": • main() • Examples of math programs returning values
  • 9. • Scope and Lifetime of Variables • There are two scopes: global and local. • Global variables have global scope. A variable defined inside a function is called a local variable. Local variable is created and destroyed every time the function is executed. It cannot be accessed outside the function. • Global variables can be accessed inside a function if there will be no local variables with the same name. • test_var = 10 • def outer_func(): • test_var = 60 • def inner_func(): • test_var = 100 • print("local var inner func is ", test_var) • inner_func() • print("local var outer func is", test_var) • outer_func() • print("global var value is", test_var) • Output: • local var inner func is 100 • local var outer func is 60 • global var value is 10
  • 10. Nested Function: A nested function (inner function) can inherit the arguments and variables of its outer function. The inner function can use the arguments and variables of the outer function while the outer function cannot use the arguments and variables of the inner function. The inner function definition is invoked by calling it from within the outer function definition. def add_cubes(a,b): def cube_surface_area(x): return 6* pow(x,2) return cube_surface_area(a) + cube_surface_area(b) def main(): result=add_cubes(2,3) print(f"The surface area after adding two cubes is {result}") if __name__=="__main__": main() The parameters of add_cubes(a,b) function are passed as arguments to the calling function cube_surface_area(x). The inner function is called within the outer function. Output: The surface area after adding two cubes is 78
  • 11. Default Parameters: Any calling function must provide arguments for all required parameters in the function definition but can omit the arguments for default parameters. If no argument is sent for that parameter, the default values is used. def work_area(prompt, domain=“Data Analytics”): print(f”{prompt} {domain}”) Def main(): work_area(“ Sam works here in ”) work_area(“Alice has interest in”, “Internet of Things”) If__name__==“__main__”: main() Output: Sam works here in Data Analytics Alice has interest in Internet of Things
  • 12. Keyword Arguments: Whenever you call a function with some values as its arguments, these values get assigned to the parameters in the function definition according to their position. In calling function, you can specify the argument name and their value in the form of Kwarg = value. In calling function, keyword arguments must follow positional arguments. No parameter in the function definition may receive a value more than once. *args and **kwargs They are used as parameters in function definitions. *args and **kwargs allows you to pass a variable number of arguments to the calling function. User might not know the the number of arguments in advance that will be passed to the calling function. *args : Allows you to pass a non-key worded variable length argument list to the calling function. **kwargs as parameter in function allows you to pass key worded variable length dictionary argument list to the calling function. *args should come after all the positional paramters and **kwargs must come right at the end.
  • 13. Command Line Arguments: A python program can accept any number of arguments from the command line. Command line arguments is a methodology in which user will give inputs to the program through the console using commands. You need to import sys module to access command line arguments. All the command line arguments can be printed as a list of string by executing sys.argv. Example: import sys def main(): print(f"sys.argv prints all the arguments at the command line including file name {sys.argv}") print(f"len(sys.argv) prints the total number of command line arguments including file name {len(sys.argv)}") print("you can use for loop to traverse through sys.argv") for arg in sys.argv: print(arg) if __name__=="__main__": main()
  • 14. Output • C:UsersAdmin>python C:/Users/Admin/AppData/Local/Programs/Python/Python311/cmdline1.py lion tiger mouse • len(sys.argv) prints the total number of command line arguments including file name 4 • C:/Users/Admin/AppData/Local/Programs/Python/Python311/cmdline1.py • lion • tiger • mouse