KEMBAR78
Python-Functions.pptx
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

Python-Functions.pptx

  • 1.
  • 2.
    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.
  • 3.
  • 4.
    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.
  • 15.
    Return Values To leta function return a value, use the return statement
  • 16.
    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.
  • 17.
    Exercise in PythonFunctions 1. Find the Given Number is Even or Odd
  • 18.
    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.
  • 24.
  • 25.
    What is theOutput of this Program?
  • 26.
    What is theOutput of this Program?
  • 27.
    Guess the Outputof the Code?
  • 28.
  • 29.
    Call By valuevs Call By Reference
  • 30.
    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.
  • 34.
  • 35.
    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
  • 36.
  • 37.
    Not a TailRecursive Function
  • 38.
    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
  • 40.
    Factorial of aNumber Output : 120
  • 41.
  • 42.
    To Find theNth number in Fibonacci Series Output : 21
  • 43.
  • 44.
    To check thePalindrome Output: True False
  • 45.
    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.
  • 47.
    Exercise 3: 1. Writea Program to Reverse Integer 2. Finding the Vowels