0% found this document useful (0 votes)
269 views42 pages

Function and Recursion of Python

This document discusses functions and recursion in Python. It defines what functions are, how they are defined and called, and how to pass arguments to functions. It also covers user-defined functions, parameters vs arguments, and local vs global scope. Finally, it explains what recursion is and provides examples of recursive functions using stack diagrams. It includes an exercise asking the reader to write several Python functions.

Uploaded by

SaicharanSai
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
269 views42 pages

Function and Recursion of Python

This document discusses functions and recursion in Python. It defines what functions are, how they are defined and called, and how to pass arguments to functions. It also covers user-defined functions, parameters vs arguments, and local vs global scope. Finally, it explains what recursion is and provides examples of recursive functions using stack diagrams. It includes an exercise asking the reader to write several Python functions.

Uploaded by

SaicharanSai
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 42

Functions and

Recursion
• Function: A named sequence of statements that performs some
useful operation. Functions may or may not take arguments and may
or may not produce a result.

• Function definition: A statement that creates a new function,


specifying its name, parameters, and the statements it executes.

• Function call: A statement that call a function definition to perform a


specific task.
Function calls
Function Name Arguments

>>> type(“32”)
<type ‘str’> Return Value
Type conversion
Float to integer conversion
Integer and String Conversion to Float
Integer and Float Conversion to String
Type coercion
• Rules for automatic type conversion is know as Type coercion.
• For example,

• By making the denominator or numerator a float, we force Python


to do floating-point division.
Math Functions
Calling a Math Function

For Example,
Composition
Composition
Mathematical functions

• abs(x) : calculates the absolute value of x


• pow(x , y) : calculates x raise to the power of y.
• Max (x1,x2….xn) : Gives the maximum number out the all the
given numbers in parenthesis.
• Min (x1,x2…xn) : Gives the minimum number out the all the
given numbers in parenthesis.
Mathematical Functions stored in Math Package

• exp (x) : exponential


• ceil(x) : ceil value of x
• floor(x) : floor value of x
• log(x) : logarithm with natural base
• sqrt(x) : square root of x
Trigonometric Functions in Math Module
Adding new or user defined functions
• A function is a named sequence of statements that performs a
desired operation. This operation is specified in a function definition.

• The syntax for a function definition is:


• Example,

Def newLine():
Print
Calling user defined functions

• Output of the program is:


Why we need to create functions

• Creating a new function gives you an opportunity to name a group of


statements. Functions can simplify a program by hiding a complex
computation behind a single command and by using English words in
place of arcane code.

• Creating a new function can make a program smaller by eliminating


repetitive code.
Few points to remember
• Only the function definition generates no output.
• The statements inside the function do not get executed until the
function is called.
• You have to create a function before you can execute it. In other
words, the function definition has to be executed before the first time
it is called.
Flow of execution
• In order to ensure that a function is defined before its first use, you
have to know the order in which statements are executed, which is
called the flow of execution.
3
4
5
6

Execution Starts 1
2
7
Parameters and arguments
• Arguments are the values that control how the function does its job.
• For example, if you want to find the sine of a number, you have to
indicate what the number is. Thus, sin takes a numeric value as an
argument.

• Some functions take more than one argument. For example, pow
takes two arguments, the base and the exponent. In the function
definition, the values that are passed get assigned to variables called
as parameters.
EXAMPLE

def mammals( cat, dog):


animal = cat+dog
return animal
mice=10
rabbit = 12
mammals(mice , rabbit)
# Here mice and rabbit are arguments
# cat and dog are paramaters
Function Definition
with arguments

Function Call
with arguments of
type String, Integer
and float respectively
Composition for user defined functions
Variables and parameters are local
• When you create a local variable inside a function, it only exists inside
the function, and you cannot use it outside. For example:
def catTwice(part1, part2):
cat = part1 + part2
print cat

>>> a= “Python”
>>> b=“Class”
>>> catTwice(a,b)
When cat Twice terminates, the variable cat is destroyed. If we try to
print it,
we get an error:

>>> print cat


NameError: cat

• Parameters are also local. For example, outside the function


catTwice(part1, part2), there is no such thing as part1 and part2
Stack Diagram for functions
• To keep track of which variables can be used where, it is sometimes
useful to draw a stack diagram.
• Stack diagram is used to represent the state of a program during a
function call.
• Each function is represented by a frame. A frame is a box with the
name of a function beside it and the parameters and variables of the
function inside it.
_main_
a “Python”

b “Class”

Part1 “Python”

catTwice Part2 “Class”

Cat “Python Class”


Functions with results

def sum (x,y):


return x+y

>>> a=sum(8,9)
>>> print(a)
17
Recursion
• It is legal for one function to call another, and you have seen several
examples of that.
• But it is also legal for a function to call itself.
• For example,
>>> countdown(3)

OUTPUT of this function will be :


Stack diagrams for recursive functions
• Earlier we used a stack diagram to represent the state of a program
during a function call. The same kind of diagram can help interpret a
recursive function.

• Every time a function gets called, Python creates a new function


frame, which contains the function's local variables and parameters.
For a recursive function, there might be more than one frame on the
stack at the same time.
• Following figure shows a stack diagram for function countdown (n)
called with n = 3:
Infinite recursion
• If a recursion never reaches a base case, it goes on making recursive
calls forever, and the program never terminates. This is known as
infinite recursion, and it is generally not considered a good idea. Here
is a minimal program with an infinite recursion:

def recurse () : Function is calling


itself without any
recurse() condition to terminate
The recursive call
• In most programming environments, a program with infinite recursion
does not really run forever. Python reports an error message when
the maximum recursion depth is reached:
EXCERCISE
1. Write a Python function to find the Max of three numbers.
2. Write a Python function to sum all the numbers in a list.
3. Write a Python function to multiply all the numbers in a list.
4. Write a Python function to reverse a string.
5. Write a Python function to calculate the factorial of a number (non-
negative integer). The function accept the number as an argument.
6. Write a Python function to check whether a number is in a given
range.
7. Write a Python function that takes a number as a parameter and
check the number is prime or not.
8. Write a Python function that checks whether a passed string is
palindrome or not.
9. Write a Python function to check whether a number is perfect or not.
According to Wikipedia : In number theory, a perfect number is a
positive integer that is equal to the sum of its proper positive divisors,
that is, the sum of its positive divisors excluding the number itself
(also known as its aliquot sum). Equivalently, a perfect number is a
number that is half the sum of all of its positive divisors (including
itself).
Example : The first perfect number is 6, because 1, 2, and 3 are its
proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6
is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 =
6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed
by the perfect numbers 496 and 8128.

You might also like