Python Unit 4
Python Unit 4
Python 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.
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")
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")
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])
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)
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"])
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")
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
---
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:
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)
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
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
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
---
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.fsum() Returns the sum of all items in any iterable (tuples, arrays,
lists, etc.)
Method Description
---
Q. Write about Math and random modules in python
---