[go: up one dir, main page]

0% found this document useful (0 votes)
22 views43 pages

Functions and Recursion

Here are functions to solve the exercises: 1. To find the max of three numbers: def max_of_three(a, b, c): return max(a, b, c) 2. To sum all numbers in a list: def sum_list(list): total = 0 for num in list: total += num return total 3. To multiply all numbers in a list: def multiply_list(list): result = 1 for num in list: result *= num return result 4. To reverse a string: def reverse_string(string): return string[::-1] 5. To

Uploaded by

Akhil SK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views43 pages

Functions and Recursion

Here are functions to solve the exercises: 1. To find the max of three numbers: def max_of_three(a, b, c): return max(a, b, c) 2. To sum all numbers in a list: def sum_list(list): total = 0 for num in list: total += num return total 3. To multiply all numbers in a list: def multiply_list(list): result = 1 for num in list: result *= num return result 4. To reverse a string: def reverse_string(string): return string[::-1] 5. To

Uploaded by

Akhil SK
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 43

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

• A group of related statements that perform a specific task.


• Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions make it more
organized and manageable.
• Furthermore, it avoids repetition and makes code reusable.
Syntax for declaring function

1.Keyword def marks the start of function header.


2.A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3.Parameters (arguments) 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 that make up the function body. Statements must
have same indentation level (usually 4 spaces).
7.An optional return statement to return a value from the function.
Example
Function Calling
• Once the basic structure of a function is finalized, you can execute it
by calling it from another function or directly from the Python
prompt.
• Following is the example to call example() function:
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 a float, we force Python to do floating-


point division.
Math Functions
Calling a Math Function

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

We can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.


2. User-defined functions - Functions defined by the users themselves.
Python Built-in function
• A number of functions that are always available for use, called built-in functions.
• For example: print() function prints the given object to the standard output device (screen)
or to the text stream file.

Some of user-defined functions are:


Python User-defined Functions
• Functions that we define ourselves to do certain specific task are referred as User-defined
Functions.
• Functions that readily come with Python are called built-in functions.
• If we use functions written by others in the form of library, it can be termed as library
functions.
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
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 (=).

Parameter name does not have a


default value and is required
(mandatory) during a call.

On the other hand, the parameter msg


has a default value of "Good
morning!". So, it is optional during a
call. If a value is provided, it will
overwrite the default value.
Keyword Arguments
• When we call a function with some values, these values get assigned to the
arguments.
• For example, in the above function greet(), when we called it as greet("Bruce","How
do you do?"), the value "Bruce" gets assigned to the argument name and similarly
"How do you do?" to msg.
Python allows functions to be called using keyword arguments. When we call functions
in this way, the order (position) of the arguments can be changed.
Following calls to the above function are all valid and produce the same result.
Arbitrary Arguments
• We do not know in advance the number of arguments that will be passed into a
function. Python allows us to handle this kind of situation through function calls
with arbitrary number of arguments.
• In the function definition we use an asterisk (*) before the parameter name to
denote this kind of argument.
Function Definition
with arguments

Function Call
with arguments of
type String, Integer
and float respectively
Composition for user defined functions
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,
• 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

1. Recursive functions make the code look clean and elegant.


2. A complex task can be broken down into simpler sub-problems using
recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion

1. Sometimes the logic behind recursion is hard to follow through.


2. Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
3. Recursive functions are hard to debug.
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.

You might also like