SlideShare une entreprise Scribd logo
1  sur  47
PYTHON-FUNCTIONS
Functions
Python Functions is a 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.
Function Syntax
Creating Python Function
We can create a Python function using the def keyword.
# A simple Python function
def fun():
print("Welcome to Bharat")
Calling a Python Function
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:
Python Function with Parameters
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.
Parameters or Arguments
The terms 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.
Types of Arguments
Python supports various types of arguments that can be passed at the
time of the function call.
1. Default Arguments
2. Keyword Arguements
Number of Arguments
By default, 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.
Arbitrary Arguments
If you do 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:
Keyword Arguments
You can also send arguments with the key = value syntax.
This way the order of the arguments does not matter.
Arbitrary Keyword Arguments
If you 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:
Default Parameter Value
The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value:
Passing List as an 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.
Return Values
To let a function return a value, use the return statement
Pass Statement
function definitions cannot 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.
Exercise in Python Functions
1. Find the Given Number is Even or Odd
Pass By Value and 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.
Call by Value
It is 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.
Call By Reference
It is 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.
Mutable Objects
An object whose 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.
Immutable Objects
An object whose 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.
Call By value in 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.
Call by Reference
What is the Output of this Program?
What is the Output of this Program?
Guess the Output of the Code?
Mutable vs Immutable
Call By value vs Call By Reference
Python Exercise
1. Write a 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
Python Recursion
Recursion is a 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.
What is Recursion?
A process 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.
Recursive Python Function
Base Case: 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.
Example Recursive Function
Types of Recursion in Python
1. Direct Recursion - In this type of recursion, the function calls itself.
1. Tail Recursion
2. Head Recursion
2. Indirect Recursion
Tail Recursive Function
Output : 5 4 3 2 1
Not a Tail Recursive Function
Head Recursion
If in a 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
Indirect Recursion
In this type 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
Factorial of a Number
Output : 120
Ascending or Not
Output:
False
True
To Find the Nth number in Fibonacci Series
Output : 21
Integer Reversal
Output : 425
To check the Palindrome
Output:
True
False
Advantages of Recursion in 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.
Disadvantages of Recursion in 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.
Exercise 3:
1. Write a Program to Reverse Integer
2. Finding the Vowels

Contenu connexe

Tendances

Tendances (20)

Python Basics
Python BasicsPython Basics
Python Basics
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Programming with Python
Programming with PythonProgramming with Python
Programming with Python
 
Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...Django Tutorial | Django Web Development With Python | Django Training and Ce...
Django Tutorial | Django Web Development With Python | Django Training and Ce...
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
 
Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
 
Variables & Data Types In Python | Edureka
Variables & Data Types In Python | EdurekaVariables & Data Types In Python | Edureka
Variables & Data Types In Python | Edureka
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Java vs python
Java vs pythonJava vs python
Java vs python
 
Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...Python Programming Language | Python Classes | Python Tutorial | Python Train...
Python Programming Language | Python Classes | Python Tutorial | Python Train...
 
Python | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python TutorialPython | What is Python | History of Python | Python Tutorial
Python | What is Python | History of Python | Python Tutorial
 
Python introduction
Python introductionPython introduction
Python introduction
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python PPT
Python PPTPython PPT
Python PPT
 
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | EdurekaPython Tutorial | Python Tutorial for Beginners | Python Training | Edureka
Python Tutorial | Python Tutorial for Beginners | Python Training | Edureka
 
Python programming
Python programmingPython programming
Python programming
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 

Similaire à Python-Functions.pptx

Similaire à Python-Functions.pptx (20)

Userdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdfUserdefined functions brief explaination.pdf
Userdefined functions brief explaination.pdf
 
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONSINTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
INTRODUCTION TO PYTHON PROGRMMING AND FUNCTIONS
 
functions.pptx
functions.pptxfunctions.pptx
functions.pptx
 
Python_Unit_2.pdf
Python_Unit_2.pdfPython_Unit_2.pdf
Python_Unit_2.pdf
 
Python functions
Python   functionsPython   functions
Python functions
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx04. WORKING WITH FUNCTIONS-2 (1).pptx
04. WORKING WITH FUNCTIONS-2 (1).pptx
 
Dive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdfDive into Python Functions Fundamental Concepts.pdf
Dive into Python Functions Fundamental Concepts.pdf
 
Python Function.pdf
Python Function.pdfPython Function.pdf
Python Function.pdf
 
functions- best.pdf
functions- best.pdffunctions- best.pdf
functions- best.pdf
 
An Introduction on Functions in python 3.pdf
An Introduction on Functions in python 3.pdfAn Introduction on Functions in python 3.pdf
An Introduction on Functions in python 3.pdf
 
functions new.pptx
functions new.pptxfunctions new.pptx
functions new.pptx
 
Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
 
3 cs xii_python_functions _ parameter passing
3 cs xii_python_functions _ parameter passing3 cs xii_python_functions _ parameter passing
3 cs xii_python_functions _ parameter passing
 
Php, mysq lpart3
Php, mysq lpart3Php, mysq lpart3
Php, mysq lpart3
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Functions
FunctionsFunctions
Functions
 
Python functions
Python functionsPython functions
Python functions
 
VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1VIT351 Software Development VI Unit1
VIT351 Software Development VI Unit1
 
UNIT 3 python.pptx
UNIT 3 python.pptxUNIT 3 python.pptx
UNIT 3 python.pptx
 

Plus de Karudaiyar Ganapathy (8)

Python-FileHandling.pptx
Python-FileHandling.pptxPython-FileHandling.pptx
Python-FileHandling.pptx
 
Python-exceptionHandling.pptx
Python-exceptionHandling.pptxPython-exceptionHandling.pptx
Python-exceptionHandling.pptx
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
 
Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Overloading vs Overriding.pptx
Overloading vs Overriding.pptxOverloading vs Overriding.pptx
Overloading vs Overriding.pptx
 
Python-Polymorphism.pptx
Python-Polymorphism.pptxPython-Polymorphism.pptx
Python-Polymorphism.pptx
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
 
Python-Classes.pptx
Python-Classes.pptxPython-Classes.pptx
Python-Classes.pptx
 

Dernier

Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
dollysharma2066
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
amitlee9823
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
dharasingh5698
 

Dernier (20)

chapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineeringchapter 5.pptx: drainage and irrigation engineering
chapter 5.pptx: drainage and irrigation engineering
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night StandCall Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Bangalore ☎ 7737669865 🥵 Book Your One night Stand
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoorTop Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
Top Rated Call Girls In chittoor 📱 {7001035870} VIP Escorts chittoor
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Intro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdfIntro To Electric Vehicles PDF Notes.pdf
Intro To Electric Vehicles PDF Notes.pdf
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
(INDIRA) Call Girl Aurangabad Call Now 8617697112 Aurangabad Escorts 24x7
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Pargaon  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Pargaon 6297143586 Call Hot Indian Gi...
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...Bhosari ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready For ...
Bhosari ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For ...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Unit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdfUnit 2- Effective stress & Permeability.pdf
Unit 2- Effective stress & Permeability.pdf
 

Python-Functions.pptx

  • 2. Functions Python Functions is a 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.
  • 4. Creating Python Function We can create a Python function using the def keyword. # A simple Python function def fun(): print("Welcome to Bharat")
  • 5. Calling a Python Function 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 with Parameters 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 The terms 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 Python supports 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 By default, 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 you do 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 can also send arguments with the key = value syntax. This way the order of the arguments does not matter.
  • 12. Arbitrary Keyword Arguments If you 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 The following example shows how to use a default parameter value. If we call the function without argument, it uses the default value:
  • 14. Passing List as an 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.
  • 15. Return Values To let a function return a value, use the return statement
  • 16. Pass Statement function definitions cannot 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.
  • 17. Exercise in Python Functions 1. Find the Given Number is Even or Odd
  • 18. Pass By Value and 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 It is 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 It is 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 object whose 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 object whose 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 value in 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.
  • 25. What is the Output of this Program?
  • 26. What is the Output of this Program?
  • 27. Guess the Output of the Code?
  • 29. Call By value vs Call By Reference
  • 30. Python Exercise 1. Write a 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 is a 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? A process 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 Base Case: 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.
  • 35. Types of Recursion in Python 1. Direct Recursion - In this type of recursion, the function calls itself. 1. Tail Recursion 2. Head Recursion 2. Indirect Recursion
  • 37. Not a Tail Recursive Function
  • 38. Head Recursion If in a 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 this type 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
  • 40. Factorial of a Number Output : 120
  • 42. To Find the Nth number in Fibonacci Series Output : 21
  • 44. To check the Palindrome Output: True False
  • 45. Advantages of Recursion in 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 Recursion in 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.
  • 47. Exercise 3: 1. Write a Program to Reverse Integer 2. Finding the Vowels