Function and Recursion of Python
Function and Recursion of Python
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.
>>> 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,
•
For Example,
Composition
Composition
Mathematical functions
Def newLine():
Print
Calling user defined functions
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
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:
b “Class”
Part1 “Python”
>>> 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)