Functions and Recursion
Functions and Recursion
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
• abs(x) • Log(x)
• Ceil(x) • pow (x,y)
• cmp (x, y) • sqrt(x,y )
• exp (x) • Max (x1,x2….xn)
• Floor(x) • Min (x1,x2…xn)
Trigonometric Functions
Example
Types of Functions
Execution Starts 1
2
7
Function Arguments
You can call a function by using the following types of formal arguments −
Default Arguments
• Arguments can have default values in Python.
• We can provide a default value to an argument by using the assignment
operator (=).
Function Call
with arguments of
type String, Integer
and float respectively
Composition for user defined functions
Functions with results
>>> 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,
• When we call this function with a positive integer, it will recursively call
itself by decreasing the number. Each function call multiples the number
with the factorial of number 1 until the number is equal to one.
Advantages of Recursion