UNIT-4
Functions
A function is a block of code identified with a name. A function has a definition and a call. The
function definition includes the process to be executed and that definition executes only when the
function is called. Function call is invocation of the definition.
A function is a collection of related assertions that performs a mathematical, analytical, or
evaluative operation. A collection of statements called Python Functions returns the particular
task. Python functions are simple to define and essential to intermediate-level programming. The
exact criteria hold to function names as they do to variable names. The goal is to group up
certain often performed actions and define a function. We may call the function and reuse the
code contained within it with different variables rather than repeatedly creating the same code
block for different input variables
Defining a Function:
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function:
To call a function, use the function name followed by parenthesis:
def my_function():
print("Hello from a function")
my_function() # calling a function
Types of Functions: the python functions are classified into 2 types.
1. Built in functions
2. User defined functions
The python has number of functions already defined and called built in functions, and we can
simply make a call to them to execute them.
The user may provide definition to his own functions and call them, are called user defined
functions. If the user defined function is not with in a class then it is called simply function and if
it is with in a class then it is called a method.
Function arguments:
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.
Ex:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
we may pass more than one argument as required.
Ex:
def my_function(fname, lname):
print(fname + " " + lname)
my_function("Emil", "Refsnes")
Arbitrary arguments:
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:
Ex:
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
keyword arguments :
one can also send arguments with the key = value syntax. In this way the order of the arguments
does not matter.
Ex:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
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")
The following example shows how to use a default parameter value. If we call the function
without argument, it uses the default value:
Ex:
def my_function(country = "India"):
print("I am from " + country)
my_function("Sweden")
my_function("Norway")
my_function()
my_function("Brazil")
Functions can also return values :
Ex:
def my_function(x):
return 5 * x
print(my_function(3))
print(my_function(5))
print(my_function(9))
---
Q. Write about types of functions in python
Q explain different types of arguments in python
---
Local and Global Variables:
The python variables are classified into 2 types. The local variables and the global
variables. The variables declared with in a function definition are called local variables to that
function and that are declared outside of all functions are called global variables. The local
variables are accessible only within that function in which they are declared and the global
variables are accessible both inside the function and outside the function.
Global variable can be declared and used as shown below:
1. A global variable can be declared outside of a function
x = "awesome"
def myfunc():
print("Python is " + x)
myfunc()
2. a global variable can be declared with global keyword global with in a function.
def aa():
global x
x=5
print('within function',x)
aa()
print('accessed from outside function',x)
Local variable is declared within a function definition as shown below:
def aa():
x=5
print(‘within function’,x)
aa()
print(‘accessed from outside function’,x) # this line raises error as x is not accessible
if a local variable and global variable have same names, then we can use the function globals() to
access the global variables with in a function as local variables have higher priority. The
globals() function returns the list of global variables as a list of Dictionaries.
X=10
def aa():
x=5
print(‘local variable :’,x)
print(‘global 4ariable :’, globals()[‘x’])
aa()
---
Q. Explain about local and global variables in python
---
Lambda functions:
A lambda function is a small anonymous function. A lambda function can take any
number of arguments, but can only have one expression. Instead of writing a function, for
simpler process, we can use the lambda functions.
Syntax:
lambda arguments : expression
The expression is executed and the result is returned
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
we can use the same function to do different processes as shown below:
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
Recursion :
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function calls
itself. This has the benefit of meaning that you can loop through data to reach a result.
The developer should be very careful with recursion as it can be quite easy to slip into writing a
function which never terminates, or one that uses excess amounts of memory or processor power.
However, when written correctly recursion can be a very efficient and mathematically-elegant
approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We
use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends
when the condition is not greater than 0 (i.e. when it is 0).
To a new developer it can take some time to work out how exactly this works, best way to find
out is by testing and modifying it.
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(6)
output:
Recursion Example Results
1
3
6
10
15
21
---
Q. Write about Lambda expression and recursion functions in python
Q. Explain about Lambda function and recursion in python
---
Modules- math and random:
A module is same as a library file in C and as a package in java. A Module is a file containing a
set of functions you want to include in your application.
To create a module just save the code you want in a file with the file extension .py:
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Python has also a built-in module called math, which extends the list of
mathematical functions.
math.ceil() Rounds a number up to the nearest integer
math.comb() Returns the number of ways to choose k items from n items
without repetition and order
math.copysign() Returns a float consisting of the value of the first parameter
and the sign of the second parameter
math.cos() Returns the cosine of a number
math.degrees() Converts an angle from radians to degrees
math.exp() Returns E raised to the power of x
math.fabs() Returns the absolute value of a number
math.factorial() Returns the factorial of a number
math.floor() Rounds a number down to the nearest integer
math.fmod() Returns the remainder of x/y
math.fsum() Returns the sum of all items in any iterable (tuples, arrays,
lists, etc.)
math.gcd() Returns the greatest common divisor of two integers
math.log() Returns the natural logarithm of a number, or the logarithm
of number to base
math.log10() Returns the base-10 logarithm of x
math.pow() Returns the value of x to the power of y
math.prod() Returns the product of all the elements in an iterable
math.remainder() Returns the closest value that can make numerator
completely divisible by the denominator
math.sin() Returns the sine of a number
math.sqrt() Returns the square root of a number
Python has a built-in module that you can use to make random numbers.
Method Description
seed() Initialize the random number generator
randrange() Returns a random number between the given range
randint() Returns a random number between the given range
choice() Returns a random element from the given sequence
random() Returns a random float number between 0 and 1
uniform() Returns a random float number between two given parameters
---
Q. Write about Math and random modules in python
---