Functions allow programmers to organize and reuse code. They take in parameters and return values. Parameters act as variables that represent the information passed into a function. Arguments are the actual values passed into the function call. Functions can have default parameter values. Functions can return values using the return statement. Python passes arguments by reference, so changes made to parameters inside functions will persist outside the function as well. Functions can also take in arbitrary or keyword arguments. Recursion is when a function calls itself within its own definition. It breaks problems down into sub-problems until a base case is reached. The main types of recursion are direct, indirect, and tail recursion. Recursion can make code more elegant but uses more memory than iteration.
Functions
Python Functions isa block of statements that return the Specific Task
Why is function needed?
The idea is to put some commonly or repeatedly done tasks together
and make a function so that instead of writing the same code again and
again for different inputs, we can do the function calls to reuse code
contained in it over and over again.
Creating Python Function
Wecan create a Python function using the def keyword.
# A simple Python function
def fun():
print("Welcome to Bharat")
5.
Calling a PythonFunction
After creating a function, we can call it by using the name of the
function followed by parenthesis containing parameters of that
particular function.
Program:
6.
Python Function withParameters
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside
the parentheses. You can add as many arguments as you
want, just separate them with a comma.
7.
Parameters or Arguments
Theterms parameter and argument can be used for the
same thing: information that are passed into a function.
From Function Perspective
A parameter is the variable listed inside the parentheses in the
function definition.
An argument is the value that is sent to the function when it is called.
8.
Types of Arguments
Pythonsupports various types of arguments that can be passed at the
time of the function call.
1. Default Arguments
2. Keyword Arguements
9.
Number of Arguments
Bydefault, a function must be called with the correct number of
arguments. Meaning that if your function expects 2 arguments, you
have to call the function with 2 arguments, not more, and not less.
10.
Arbitrary Arguments
If youdo not know how many arguments that will be passed into your
function, add a * before the parameter name in the function definition.
This way the function will receive a tuple of arguments, and can access
the items accordingly:
11.
Keyword Arguments
You canalso send arguments with the key = value syntax.
This way the order of the arguments does not matter.
12.
Arbitrary Keyword Arguments
Ifyou do not know how many keyword arguments that will be passed
into your function, add two asterisk: ** before the parameter name in
the function definition.
This way the function will receive a dictionary of arguments, and can
access the items accordingly:
13.
Default Parameter Value
Thefollowing example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
14.
Passing List asan Argument
You can send any data types of argument to a function (string, number,
list, dictionary etc.), and it will be treated as the same data type inside
the function.
Pass Statement
function definitionscannot be empty, but if you for some reason have a
function definition with no content, put in the pass statement to avoid
getting an error.
Pass By Valueand Pass By Reference
Call By Value -> A copy of the variable is passed to the function.
Call By Reference -> An address of the variable is passed to the
function.
19.
Call by Value
Itis a way of passing arguments to a function in which the arguments
get copied to the formal parameters of a function and are stored in
different memory locations. In short, Any changes made within the
function are not reflected in the actual parameters of the function
when called.
20.
Call By Reference
Itis a way of passing arguments to a function call in which both the
actual argument and formal parameters refer to the same memory
locations and any changes made within the function are reflected in
the actual parameters of the function when called.
If we consider call by value and call by reference in Python, then we
must keep in mind that,
Python variables are not storage containers rather Python’s variables
are like memory references. They refer to the memory address where
value is stored.
21.
Mutable Objects
An objectwhose internal state can be changed is called a mutable
object. Examples of Mutable objects are Lists, Sets, Dictionaries, byte
and array.
User- defined classes can be mutable or immutable, depending on
whether their internal state can be changed or not.
22.
Immutable Objects
An objectwhose internal state cannot be changed is called an
immutable object. Examples of immutable objects are Numbers(int,
float, bool , etc), Strings, Tuples, Frozen sets(mutable version of sets are
termed as Frozen sets)
Note : All operations using immutable objects make copies.
23.
Call By valuein Python
When Immutable objects such as whole numbers, strings, etc are
passed as arguments to the function call, it can be considered as Call by
Value.
This is because when the values are modified within the function, then
the changes do not get reflected outside the function.
Python Exercise
1. Writea Python Function to print a Fibonacci Number
2. Write a Python Function to Print a Lucas Number
3. Write a Python Function to convert Decimal into Binary
4. Write a Python Function to Convert Binary into Decimal
31.
Python Recursion
Recursion isa computational problem-solving technique used in
computer science where the solution is dependent on solutions to
smaller instances of the same problem. It uses functions that call
themselves from within their code to solve such recursive problems.
The strategy is adaptable to a wide range of problems.
32.
What is Recursion?
Aprocess in which a function calls itself is called recursion. This process
helps ease the method of solving problems by replacing iterative code
with recursive statements.
Recursion in python is used when problems can be broken into simpler
parts for easier computation and more readable code.
Although recursion is found to give results faster in some cases when
properly optimized, it can also add to memory usage.Thus, recursion
should be used only when needed.
33.
Recursive Python Function
BaseCase: This helps us to terminate the recursive function. It is a
simple case that can be answered directly and doesn't use recursion. If
satisfied, it returns the final computable answer. If this is omitted, the
function will run till infinity.
Python interpreter limits the number of recursive calls for a function to
1000 by giving a recursion error.
General (Recursive) Case - This case uses recursion and is called unless
the base condition is satisfied.
Types of Recursionin Python
1. Direct Recursion - In this type of recursion, the function calls itself.
1. Tail Recursion
2. Head Recursion
2. Indirect Recursion
Head Recursion
If ina recursive function, the last statement is not a recursive call, i.e.,
during the unwinding phase, there are still some steps to occur, and
then it is called head recursion.
Output:
1 2 3 4 5
39.
Indirect Recursion
In thistype of recursion, the function calls another function which calls
the original function. Here, when function A() is called, it first executes
the print statement and then calls function B() with an incremented
value of n. Its print statement is executed within function B, and then
the function A() with a value of n reduced by five is called. The process
continues as long as the terminating condition is not satisfied.
Output: 20 21 16 17 12 13 8 9 4 5
Advantages of Recursionin Python
Recursion in Python often reduces the length of the code.
It helps increase the elegance and conciseness of the code.
It helps in breaking a complex problem into simpler ones.
We can do sequence generation and tree traversal better and easily
with recursion.
46.
Disadvantages of Recursionin Python
It is difficult to frame and understand the logic behind recursive
functions. Thus, making them hard to debug.
Recursion in Python uses more memory as values need to be added
to the call stack with each recursive call.
Recursion in Python can be slow if not implemented correctly.
Python Recursive calls can be inefficient as, in some cases, they take
up a lot of memory and time.