0% found this document useful (0 votes)
17 views47 pages

Python Inner Function

The document discusses inner functions in Python. It provides an example of defining an inner function within an outer function. It also discusses how inner functions can access variables and parameters of the outer function. The document further explains recursive functions, lambda functions, decorators and namespaces in Python.

Uploaded by

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

Python Inner Function

The document discusses inner functions in Python. It provides an example of defining an inner function within an outer function. It also discusses how inner functions can access variables and parameters of the outer function. The document further explains recursive functions, lambda functions, decorators and namespaces in Python.

Uploaded by

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

PYTHON INNER

FUNCTION

FUNCTION IN FUNCTION
DEFINING A FUNCTION IN A FUNCTION
Inner Function
DEFINING A FUNCTION IN A FUNCTION
• In Python, an inner function is a function defined inside
another function. The inner function can access variables
and parameters of the outer function and can also be used
to implement closures.
• Here is an example of defining an inner function:
In the above example, we have defined an outer function
called outer_function() and an inner function called inner_function().
The inner_function() is defined within the body of outer_function(). Note
that the inner function is only called within the outer function.
This code defines a function called create_list that allows the user to add,
delete, and display a list of names. Here is a step-by-step breakdown of the code:

1.The function create_list is defined. Inside the function, an empty list called names_list is
defined to store the names.
1.The function add_name is defined inside the create_list function. This function asks the user to
enter a name and appends it to the names_list using the append method. A message is displayed to
confirm that the name has been added to the list.
1.The function delete_name is defined inside the create_list function. This function asks the
user to enter a name and checks if it is in the names_list. If the name is in the list, it is removed using
the remove method. A message is displayed to confirm that the name has been deleted from the list. If
the name is not in the list, a message is displayed to inform the user.
1.The function display_list is defined inside the create_list function. This function simply prints all the names in
the names_list using a for loop.
2.Inside the while loop, the user is presented with a menu of options to choose from. They can choose to add a name to the
list, delete a name from the list, display the recorded list, or quit the program.
3.Depending on the user's choice, the corresponding function is called. If the user chooses to quit, the loop is broken and the
function exits.
4.If the user enters an invalid choice, a message is displayed to inform the user, and the loop continues.
1.Finally, the function create_list is called to run the program.
Overall, this code provides a simple way for the user to interact with a list of names
and add, delete, or display them as desired.
Anonymous Functions: lambda
WHAT IS LAMBDA FUNCTION IN PYTHON?
• A Lambda Function in Python programming is an anonymous
function or a function having no name. It is a small and restricted
function having no more than one line. Just like a normal function,
a Lambda function can have multiple arguments with one
expression.
Every anonymous function you define in Python will have 3
essential parts:

•The lambda keyword.


•The parameters (or bound variables), and
•The function body.
4/23/2024 Sample Footer Text 13
EXAMPLE 1

• Now that you know about lambdas let’s try it with an example. So,
open your IDLE and type in the following:
Code Explanation
Here, we define a variable that will hold the result returned by the lambda
function.
1. The lambda keyword used to define an anonymous function.
2. x and y are the parameters that we pass to the lambda function.
3. This is the body of the function, which adds the 2 parameters we passed.
Notice that it is a single expression. You cannot write multiple statements in the
body of a lambda function.
4. We call the function and print the returned value.
In Python, an anonymous function is a function that is defined
without a name. While normal functions are defined using
the def keyword

in Python, anonymous functions are defined using


the lambda keyword. Hence, anonymous functions are also
called lambda functions.
4/23/2024 Sample Footer Text 17
Example of Lambda Function in Python
An example of a lambda function that adds 4 to the input number is
shown below.
Code
Using Lambda Function with filter()
The filter() method accepts two arguments in Python: a function and an iterable
such as a list.
The function is called for every item of the list, and a new iterable or list is returned
that holds just those elements that returned True when supplied to the function.
Here's a simple illustration of using the filter() method to return only odd numbers
from a list.
Using Lambda Function with map()
A method and a list are passed to Python's map() function.
The function is executed for all of the elements within the list, and a new list is
produced with elements generated by the given function for every item.
The map() method is used to square all the entries in a list in this example.
Using Lambda Function with List Comprehension
We'll apply the lambda function combined with list comprehension
and lambda keyword with a for loop in this instance. We'll attempt to
print the square of numbers in the range 0 to 11.
Using Lambda Function with if-else
We will use the lambda function with the if-else block.
Code
Decorators
A decorator is a function that takes one function as input and
returns another function. Let's dig into our bag of Python tricks
and use the following:*args and **kwargs Inner functions
Functions as arguments
Here's an example of a simple decorator that adds a greeting before
the execution of the decorated function:
EXAMPLE OF HOW YOU COULD USE DECORATORS
IN PYTHON TO REVERSE A NAME:

4/23/2024 Sample Footer Text 27


In this code, we have defined a decorator delete_item_decorator which takes a
delete_func as input. The decorator returns an inner function wrapper which takes a
name_list as input, asks the user to enter the item to delete, calls the delete_func
with the name_list and item as inputs, and finally prints the remaining items in the list.
We have decorated the delete_item function with this decorator using the
@delete_item_decorator syntax. The delete_item function takes a
name_list and an item as input, and deletes the item from the list if it exists. If the item
is not in the list, it prints a message saying so.
After calling the delete_item function with the names_list as input, the remaining
items in the list are printed as well.
NAMESPACES AND
SCOPE

4/23/2024 Sample Footer Text 30


Namespaces
In Python, a namespace is a system that provides a way to
organize variables, functions, and other objects in a program. It
defines a scope for the objects and determines where they can
be accessed within the program.

Python has several types of namespaces,


including built-in namespaces, global
namespaces, and local namespaces.
•Built-in namespaces: This is a namespace that contains names for all the built-in
functions, exceptions, and attributes in Python. It is automatically loaded when the
Python interpreter starts up.
•Examples of built-in namespaces in Python include names such as 'print', 'input',
'len', 'type', 'int', 'float', 'str', 'list', 'dict', and many others. These names are
available globally throughout the Python program and can be used without any
need for explicit declaration or import.
•Global namespaces: This namespace contains all the names defined at the top-
level of a module or in the global scope of a function. It is created when the
module or function is defined and is available throughout the module or function.
•Local namespaces: This namespace contains all the names defined within a
function. It is created when the function is called and is destroyed when the
function returns.
4/23/2024 Sample Footer Text 33
FUNCTIONS IN PYTHON

2 0 2 0 C T U Tr a i n i n g S o l u t i o n s | A l l R i g h t s R e s e r v e d | c t u t r a i n i n g . a c . z a
Scope
In programming, a namespace is a container for a set of identifiers (such as
variables, functions, and classes) that are used to organize code and prevent
naming conflicts. A namespace can be thought of as a dictionary that maps names
to objects, where each namespace has its own dictionary.

Scope, on the other hand, refers to the region of the code where a
particular name can be accessed. In Python, there are four levels of
scope:

There are four types of scopes in Python


1.Local scope: This is the scope of variables defined inside a function. These variables can only
be accessed within the function.
2.Enclosing scope: This is the scope of variables defined in an enclosing function (i.e., a function
that contains the current function). These variables can be accessed by the current function as
well as any nested functions.
3.Global scope: This is the scope of variables defined at the top level of a module. These
variables can be accessed by any function or code within the same module.
4.Built-in scope: This is the scope of built-in functions and modules (such as print, len, and
math). These variables can be accessed from anywhere in the code.
Recursive function
A recursive function is a function that calls itself. When a function calls itself, it's
like a loop that repeats until a certain condition is met. The condition that
determines whether the function should stop calling itself is called the base
case. Recursive functions are often used when the problem being solved can be
broken down into smaller sub-problems that can be solved using the same
algorithm
Example of a recursive function in Python:
Async Functions
Async functions, also known as asynchronous functions, are a type of function
in Python that allows for non-blocking I/O operations. They are used in
situations where a program needs to wait for some I/O operation to complete,
such as network or disk I/O, without blocking other code from running.
Async functions in Python are defined using the async def keyword instead
of def. They typically use the await keyword to indicate when an I/O
operation is being performed and the function should wait for it to complete
before continuing.

Overall, async functions are a powerful tool for building responsive,


scalable, and efficient applications in Python.
4/23/2024 Sample Footer Text 41
Exceptions
In programming, exceptions are errors or unexpected events that occur during the
execution of a program. When an exception occurs, the program stops running
and displays an error message, which helps the developer to identify and fix the
issue.
Python has built-in exception handling mechanisms that allow you to handle
exceptions gracefully, instead of abruptly terminating the program. You can use
the try-except statement to catch and handle exceptions.

The try block contains the code that you want to run, while
The except block contains the code that will be executed if an exception
occurs in the try block. If no exception occurs in the try block, the except block
will be skipped.
Exception Types in PYTHON
4/23/2024 Sample Footer Text 46
Main Heading | Subheading

The End
2 0 2 02 0C2T0U CTrT aUi nTri nagi nSi nogl uSt iool nu st i o|n sA l |l RAi gl l hRt si gRhet s eRr ev seedr v |e dc t u
| t rcat u
i nt irnagi n. ai nc g
. z. a c . z a

You might also like