Download Module 4

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Lambda calculus wikipedia , lookup

Renormalization group wikipedia , lookup

Simplex algorithm wikipedia , lookup

Mathematical optimization wikipedia , lookup

Recursion (computer science) wikipedia , lookup

Generalized linear model wikipedia , lookup

Dirac delta function wikipedia , lookup

Corecursion wikipedia , lookup

Transcript
FUNCTIONS
DEFINING FUNCTION
CALLING FUNCTION
PARAMETERS AND ARGUMENTS
TYPE CONVERSION AND COERCION
BUILT IN FUNCTIONS[MATHEMATICAL FUNCTIONS]
RECURSION
• Function is a group of related statements that
perform a specific task.
• It breaks a program into smaller and modular
parts.
• As the program grows larger, functions make it
more organized and manageable.
• It avoids repetition and makes code reusable.
• Functions are of two types :
– User Defined Function
– Built-in Functions
WHY FUNCTIONS?
• Creating a new function gives you an opportunity to
name a group of statements, which makes your program
easier to read and debug.
• Functions can make a program smaller by eliminating
repetitive code. Later, if you make a change, you only
have to make it in one place.
• Dividing a long program into functions allows you to
debug the parts one at a time and then assemble them
into a working whole.
• Well-designed functions are often useful for many
programs. Once you write and debug one, you can reuse
it.
User Defined function
Syntax
def function_name(parameters):
“””function_docstring“””
statement(s)
return expression
1. Keyword def marks the start of function header.
2. A function name is used to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) are the ones through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements make up the function body. Statements must have same
indentation level (usually 4 spaces).
7. An optional return statement is used to return a value from the function.
• Example of a function
def greet():
print "Hello Good Morning”
Calling Function
• Once we have defined a function, we can call it
from another function, program or even the
Python prompt.
• To call a function we simply type the function
name with appropriate parameters.
def greet(name):
print "Hello “,name,”. Good morning!"
• >>> greet('Paul')
• Output:
Hello Paul. Good morning!
Example1
print “hello”
def greet(msg):
print "Hello “,name,”. Good morning!"
print “hi”
greet(“May”)
Output:
hello
hi
Hello May. Good morning!
Example2
print “hello”
def greet(msg):
print msg*3
print “hi”
greet(“May”)
Output:
hello
hi
MayMayMay
Function Arguments
• You can call a function by using the following
types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required arguments
• Required arguments are the arguments passed to
a function in correct positional order. Here, the
number of arguments in the function call should
match exactly with the function definition.
• To call the function printme(), you definitely need
to pass one argument, otherwise it gives a syntax
error as follows −
Keyword arguments
• Keyword arguments are related to the function
calls. When you use keyword arguments in a
function call, the caller identifies the arguments
by the parameter name.
• This allows you to skip arguments or place them
out of order because the Python interpreter is
able to use the keywords provided to match the
values with parameters. You can also make
keyword calls to the printme() function in the
following ways −
default argument
• A default argument is an argument that
assumes a default value if a value is not
provided in the function call for that
argument. The following example gives an
idea on default arguments, it prints default
age if it is not passed −
variable-length arguments
• You may need to process a function for more
arguments than you specified while defining the
function. These arguments are called variablelength arguments and are not named in the function
definition, unlike required and default arguments.
• An asterisk (*) is placed before the variable name that
holds the values of all nonkeyword variable arguments.
This tuple remains empty if no additional arguments
are specified during the function call. Following is a
simple example −
• Syntax for a function with non-keyword variable
arguments is this
Return Statement
• The return statement is used to exit a function and go back to the
place from where it was called.
• Syntax of return
return [expression_list]
• This statement can contain expression which gets evaluated and the
value is returned to the calling function.
• If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return
the None object.
• For example:
def greet(msg):
print "Hello “,name,”. Good morning!“
Output:
>>> print(greet("May"))
Hello May. Good morning!
None
Here, None is the returned value.
Scope and Lifetime of variables
• Scope of a variable is the portion of a program where the variable is
recognized.
• Parameters and variables defined inside a function is not visible
from outside. Hence, they have a local scope.
• Lifetime of a variable is the period throughout which the variable
exists in the memory. The lifetime of variables inside a function is as
long as the function executes. They are destroyed once we return
from the function. Hence, a function does not remember the value
of a variable from its previous calls.
Scope of Variables
• All variables in a program may not be accessible
at all locations in that program. This depends on
where you have declared a variable.
• The scope of a variable determines the portion of
the program where you can access a particular
identifier. There are two basic scopes of variables
in Python −
• Global variables
• Local variables
• Global vs. Local variables
Variables that are defined inside a function body have a local
scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the
function in which they are declared, whereas global variables
can be accessed throughout the program body by all functions.
When you call a function, the variables declared inside it are
brought into scope. Following is a simple example −
• We can specify more than one global variables using the same
global statement.
• For example, global x, y, z .
Using Local Variables
# Demonstrating local variables
def func(x):
print 'Local x is', x
x=2
print 'Changed local x to', x
x = 50
func(x)
print 'x is still', x
Output:
Local x is 50
Changed local x to 2
x is still 50
24
Using global variables
# demonstrating global variables
def func():
global x
print ‘x is', x
x=2
print 'Changed x to', x
x = 50
func()
print 'Value of x is', x
Output:
x is 50
Changed x to 2
Value of x is 2
25
Built-in Functions
• Type Conversion Functions
– Implicit Conversion (Coercion)
– Explicit Conversion
• Mathematical Functions
Implicit conversion (Coercion)
•
we can arbitrarily combine integers and floatingpoint numbers in an arithmetic expression – and that
the result of any such expression will always be a
floating-point number.
• This is because Python will convert the integers to
floating-point numbers before evaluating the
expression.
• This is an implicit conversion –
• we don’t have to convert anything ourselves. There is
usually no loss of precision when an integer is
converted to a floating-point number.
• For example, the integer 2 will automatically be
converted to a floating-point number in the
following example:
• result = 8.5 * 2
• 8.5 is a float while 2 is an int.
• Python will automatically convert operands so
that they are of the same type.
• In this case this is achieved if the integer 2 is
converted to the floating-point equivalent 2.0.
• Then the two floating-point numbers can be
multiplied.
Explicit conversion
• Converting numbers from float to int will result in
a loss of precision.
• For example, try to convert5.834 to an int ,it is
not possible to do this without losing precision.
• In order for this to happen, we must explicitly tell
Python that we are aware that precision will be
lost.
• For example, we need to tell the compiler to
convert a float to an int like this:
• i = int(5.834)
• Python provides built-in functions that convert
values from one type to another.
• Eg: The int function takes any value and converts it
to an integer, if it can, or complains otherwise.
• int can convert floating-point values to integers, but
it doesn’t round off; it chops off the fraction part:
• float function converts integers and strings to
floating-point numbers:
• Finally, str function converts its argument to a
string:
MATH FUNCTIONS
• Python has a math module that provides most of
the familiar mathematical functions.
• A module is a file that contains a collection of
related functions. Before we can use the module,
we have to import it:
• The module object contains the functions and
variables defined in the module.
• To access one of the functions, you have to
specify the name of the module and the name
of the function, separated by a dot (also
known as a period). This format is called dot
notation.
Mathematical Constants:
• Module also defines two mathematical constants
pi – mathematical constant pi
e – mathematical constant e
Python Modules
• A module allows you to logically organize your
Python code. Grouping related code into a
module makes the code easier to understand
and use.
• Simply, a module is a file consisting of Python
code. A module can define functions, classes
and variables. A module can also include
runnable code.
• Example
Here's an example of a simple module,
support.py
The import Statement
• You can use any Python source file as a module by
executing an import statement in some other
Python source file. The import has the following
syntax:
import module1[, module2[,... moduleN]
• When the interpreter encounters an import
statement, it imports the module if the module is
present in the search path.
Example
calc.py
def sum(a,b):
c=a+b
return c
def sub(a,b):
c=a-b
return c
def mul(a,b):
c=a*b
return c
def div(a,b):
c=a/b
return c
sample.py
import calc
print “1. Addition”
print “2. Subtraction”
ch=input(“Enter choice : “)
if ch==1:
d=calc.sum(input(“num1 : “), input(“num 2 : “))
print “Sum is : “,d
else:
d=calc.sub(input(“num1 : “), input(“num 2 : “))
print “Difference is : “,d
The from...import Statement
• Python's from statement lets you import specific
attributes from a module into the current
namespace. The from...import has the following
syntax −
from modname import name1[, name2[, ...
namen]]
• For example, to import the function sum from the
module calc, use the following statement −
from calc import sum
sample1.py
from calc import sum
d=sum(input(“num1 : “), input(“num 2 : “))
print “Sum is : “,d
Recursion
• Sometimes, the best way to solve a problem is by
solving a smaller version of the exact same problem
first.
• Recursion is a technique that solves a problem by
solving a smaller problem of the same type.
• A function that calls itself again and again is called as
recursive function.
• Advantage is program size can be reduced and it also
provides good readability.
Example1 : Coding the factorial function
def Factorial(int n):
if (n==0): # base case
return 1
else:
return n * Factorial(n-1)
Print Factorial(5)
Output:
120
• Our recursion ends when the number reduces
to 1.
• This is called the base condition.
• Every recursive function must have a base
condition that stops the recursion or else the
function calls itself infinitely.
• We must avoid infinite recursion.
Example2: Compute an
def power(a,n):
if n==0:
return 1
else:
return a*power(a,n-1)
print “Ans is : “,power(2,3)
Output:
Ans is 8
Fibonacci series using Recursion
def recur_fibo(n):
"""Recursive function to print Fibonacci sequence"""
if n <= 1:
return n
else:
(N-2) th
return(recur_fibo(n-1) + recur_fibo(n-2))
term
# take input from the user
Nth
term
nterms = int(input("How many terms? "))
# check if the number of terms is valid
if nterms <= 0:
0 1 1 2 3 5 8 13 21 . . .
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
(N-1) th
term
for i in range(nterms):
print(recur_fibo(i))