Python Programming
PIET CSE Dept.
CHAPTER-4
User Defined Function
What is Function?
➢ Group of statements to perform particular task
➢ Takes arguments as input
➢ Returns the result after manipulation
➢ Two kinds of function
➢ Built – in functions : print(), input()
➢ User defined functions
Image source : Google
Function in Python
➢ Python uses ‘def’ keyword to create user defined function
➢ Define function once and call it many times to reuse
➢ Syntax
❑ Function Definition
def <function_name> (<arguments>) :
# function statement
❑ Function Calling
<function_name>()
Arguments
➢ Input values given to function
➢ Arguments are specified by parameters in function definition
Parameters
Arguments
Return Values
➢ Whatever function gives as outcome is defined as return values
➢ Uses ‘return’ keyword
Return Values
Multiple Parameters
➢ Positional Parameter : Arguments values are identified based on their
position
Argument at pos = 0
Argument at pos = 1
Multiple Parameters
➢ Keyword Parameter : Arguments values are identified based on their
names
Multiple Parameters
➢ Default Parameter : Arguments values can be default
❑ Try calling ‘printinfo(30 , ‘Nita’)’
No need to worry about number of arguments
Accepts
multiple
arguments
You get
tuple of
arguments
Lambda Function
➢ Anonymous functions at runtime
➢ Can take any number of arguments
➢ Can only have one expression
➢ Uses ‘lambda’ keyword to define Arguments
Image source : Google
Recursion : When function call itself
Recursion : When function call itself
Factorial = fact (3)
return (3 * fact(2) ) = 6
return (2 * fact(1) ) = 2
1
Modules
➢ Logically organize your python code in module
➢ Module is just a python file
➢ Module can define functions, classes, variables
daily.py weekly.py
Packages
➢ Hierarchical organization of modules
➢ Package is a directory consists of modules and file named as : __init__.py
weatherman
weatherman is a package
consists of daily and weekly
modules
➢ Use ‘weatherman’ package in another python file using ‘from’ and ‘import’ statement
www.paruluniversity.ac.in