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()