0% found this document useful (0 votes)
6 views32 pages

PY Module II

This document provides an introduction to functions in Python, explaining their importance in debugging and code organization. It covers various types of functions, including built-in, user-defined, and lambda functions, along with their syntax and examples. Additionally, it discusses function parameters, arguments, and the scope of variables within functions.

Uploaded by

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

PY Module II

This document provides an introduction to functions in Python, explaining their importance in debugging and code organization. It covers various types of functions, including built-in, user-defined, and lambda functions, along with their syntax and examples. Additionally, it discusses function parameters, arguments, and the scope of variables within functions.

Uploaded by

SINGH
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Introduction to Function in Python

Fixing bugs in a program can be challenging, especially as the length of the code increases, which
is very often in the case of Machine Learning and Data Science projects. Multiple teams work on
the same project and sequentially develop different modules. Hence cleanliness and under stand
ability matter a lot.

To make debugging easier, developers working on different modules often divide their code into
smaller, manageable chunks called functions. This enables developers to identify the Function
where the bug is located easily. In Python, functions can be either user-defined or built in
functions

What is Function?

The function is a block of code defined with a name. We use functions whenever we need to
perform the same task multiple times without writing the same code again. It can take arguments
and returns the value.

Functions in Python provide organized, reusable and modular code to perform a set of specific
actions. Functions simplify the coding process, prevent redundant logic, and make the code easier
to follow. This topic describes the declaration and utilization of functions in Python.

Syntax:

def function_name(parameters):

"""docstring"""

statement1

statement2

...

...

return

 To define the function, we use the def keyword, along with the function name.
 The identifier rule must follow the function name.

 A function accepts the parameter (argument), and it can be optional.

 The function block is started with the help of colon (:), and block statements must be at
the same indentation.

 To return the value from the function, we use the return statement. A function can have
only one return statement involved in it.

Example:

def calculate(a,b):

print('The Sum : ', a + b)

print('The Difference : ', a - b) # Function 'calculate()' executes 3 times

print('The Product : ', a * b)

calculate(20,10) # Function call

calculate(200,100)

Explain Calling aFunction?

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of [Link] 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 printme() function −

calculate(2000,1000)

Calling a function of a module

The built-in module and use the functions defined in it.

For example, Python has a random module that is used for generating random numbers

and data. It has various functions to create different types of random data.

from random import randint


# call randint function to get random number

print(randint(10, 20))

# Output 14

Function Parameters And Arguments

A function to receive one or more parameters (also called arguments) and use them for
processing inside the function block. Parameters/arguments may be given suitable formal
names.

The names of the arguments used in the definition of the function are called formal
arguments/parameters. Objects actually used while calling the function are called actual
arguments/parameters.

Example:

def multiply(x, y):

print("Multiply {} and {}".format(x, y))

result = x * y

return result

if __name__ == “__main__”:

answer = multiply(3,4)

print(“Answer: “, ans/wer)

Explain types of functions

There are three types of functions in Python:

 Built-in functions, such as help() to ask for help, min() to get the minimum value, print()
to print an object to the terminal,… You can find an overview with more of these functions
here.
 User-Defined Functions (UDFs), which are functions that users create to help them out
 Anonymous functions, which are also called lambda functions because they are not
declared with the standard def keyword.

Built-in Functions:

Built-in functions are the functions that are already written or defined in python. We only need to
remember the names of built-in functions and the parameters used in the functions. As these
functions are already defined so we do not need to define these functions. Below are some built-
in functions of Python.

Function name Description


len() It returns the length of an object/value.
list() It returns a list.
max() It is used to return maximum value from a sequence (list,sets) etc.
min() It is used to return minimum value from a sequence (list,sets) etc.
open() It is used to open a file.
print() It is used to print statement.
str() It is used to return string object/value.
sum() It is used to sum the values inside sequence.
type() It is used to return the type of object.
tuple() It is used to return a tuple.

Program:

def get_length(word):

return len(word)

words = ['apple', 'banana', 'cherry', 'date', 'elderberry']

sorted_words = sorted(words, key=get_length)

print(sorted_words)

User-Defined Functions:

The functions defined by a programmer to reduce the complexity of big problems and to use that
function according to their need. This type of functions is called user-defined functions.
User define functions are two types

1. Non recursive function


2. Recursive function

Non recursive function

A procedure or subroutine, implemented in a programming language, whose implementation


references itself

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

num1= int(input("Enter First number :"))

num2 = int(input("Enter Second number :"))

print(num1,"+" ,num2,"=", add(num1,num2))

print(num1,"-" ,num2,"=", sub(num1, num2))

print(num1,"*" ,num2,"=",mul(num1, num2))

print(num1,"/", num2,"=",div(num1, num2))

Recursive Functions in Python


Recursive functions in Python call themselves to perform a task repeatedly until a certain
condition is met. Recursive functions can be used to solve problems that can be broken down into
smaller sub-problems that can be solved using the same approach.

def factorial(n):

if n == 1:

return 1

else:

return n * factorial(n-1)

Lambda Function in Python(Anonymous functions)

In Python, a lambda function is a small, anonymous function that can take any number of
arguments but only have one expression. Lambda functions are also known as “anonymous
functions” because they don’t require a named function to be created.

syntax

lambda arguments: expression

add = lambda x, y: x + y

result = add(3, 5)

print(result)

numbers = [1, 2, 3, 4, 5]

squares = list(map(lambda x: x**2, numbers))

print(squares)

Function Parameters Vs Arguments

When we define and call a Python function, the term parameter and argument is used to pass
information to the function.

parameter: It is the variable listed inside the parentheses in the function definition.
argument: It is a value sent to the function when it is called. It is data on which function performs
some action and returns the result.

def my_sum(a, b, c):

s=a+b+c

return s

print('Total is:', my_sum(30, 40, 50))

Explain Types of arguments in functions?

Types of function arguments

There are various ways to use arguments in a function. In Python, we have the following 4 types
of function arguments.

 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs)

Default Arguments
We assign default values to the argument using the ‘=’ (assignment) operator at the time of
function definition. You can define a function with any number of default arguments.

The default value of an argument will be used inside a function if we do not pass a value to that
argument at the time of the function call. Due to this, the default arguments become optional
during the function call.

Example:

def phone(Mobilename, price, Model="14 pro", availability="Amazon & Aptronix"):

print('Student Details:', Mobilename, price, Model, availability)

student('iphone', 12)

Keyword Arguments

Keyword arguments are those arguments where values get assigned to the arguments by their
keyword (name) when the function is called. It is preceded by the variable name and an (=)
assignment operator. The Keyword Argument is also called a named argument.

def student(name, age):

print('Student Details:', name, age)

# default function call

student("Suri", 14)

# both keyword arguments

student(name='dasara', age=12)

Positional Arguments(functional)

Positional arguments are those arguments where values get assigned to the arguments by their
position when the function is called. For example, the 1st positional argument must be 1st when
the function is called. The 2nd positional argument needs to be 2nd when the function is called,
etc.

By default, Python functions are called using the positional arguments.


def add(a, b):

print(a - b)

add(50, 10)

add(10, 50 , 5)

Variable-length arguments

There is a situation where we need to pass multiple arguments to the function. Such types of
arguments are called arbitrary arguments or variable-length arguments.

We use variable-length arguments if we don’t know the number of arguments needed for the
function in advance.

Types of Arbitrary Arguments:

 arbitrary positional arguments (*args)


 arbitrary keyword arguments (**kwargs)

arbitrary positional arguments (*args)

We can declare a variable-length argument with the * (asterisk) symbol. Place an asterisk (*)
before a parameter in the function definition to define an arbitrary positional argument.

we can pass multiple arguments to the function. Internally all these values are represented in the
form of a tuple.

def percentage(sub1, sub2, sub3):

avg = (sub1 + sub2 + sub3) / 3

print('Average', avg)

percentage(56, 61, 73)

This function works, but it’s limited to only three arguments. What if you need to calculate the
average marks of more than three subjects or the number of subjects is determined only at
runtime? In such cases, it is advisable to use the variable-length of positional arguments to write a
function that could calculate the average of all subjects no matter how many there are.
Arbitrary keyword arguments (**kwargs)

The **kwargs allow you to pass multiple keyword arguments to a function. Use the **kwargs if
you want to handle named arguments in a function.

Use the unpacking operator(**) to define variable-length keyword arguments. Keyword


arguments passed to a kwargs are accessed using key-value pair (same as accessing a dictionary in
Python).

def percentage(**kwargs):

sum = 0

for sub in kwargs:

# get argument name

sub_name = sub

# get argument value

sub_marks = kwargs[sub]

print(sub_name, "=", sub_marks)

# pass multiple keyword arguments

percentage(math=56, english=61, science=73)

Important points to remember about function argument

 Default arguments should follow non-default arguments

 keyword arguments should follow positional arguments only.

 The order of keyword arguments is not important, but All the keyword arguments passed
must match one of the arguments accepted by the function.

 No argument should receive a value more than once

What is fruitful function?

Fruitful Functions
 A function that returns a value is called fruitful function.

 The functions that return a value are called “Fruitful Functions”. Every function after
performing its task it return the program control to the caller. This can be done implicitly.
This implicit return statemnet return nothing to the caller, except the program control. A
function can return a value to the caller explicitly using the “return” statement.

Syntax:

return (expression)

The expression is written in parenthesis that computes a single value. This return statement is

used for two things: First, it returns a value to the caller. Second, To end and exit a function andgo
back to the caller.

Defining a fruitful function

If we want a function to return a result to the caller of the function, we use the return statement.

For example, here we define two fruitful functions. The second one, circle area, calls the first

one, square, to square the radius.

import math

def square(x):

return x ∗ x

def circle area (diameter ):

radius = diameter / 2.0

return [Link] ∗ square(radius)

In general, a return statement consists of the return keyword followed by an expression, which is
evaluated and returned to the function caller

For example:
Example:

Root=sqrt(25)

Abs(420)

abs(-420)

#finding the area of a circle

Example:

def area(r):

a=3.14*r*r

return(a) #function returning a value tothe caller

#begining of main function

x=int(input("Enter the radius :"))

#calling the function

r=area(x)

print("The area of the circle is:",r)

How python evaluates a return statement (Flow of execution)

The rules for executing a function call:

1. Evaluate the arguments to produce memory addresses.

2. Store those memory addresses in the corresponding parameters.

3. Execute the body of the function.

4. When complete, return to the location in the program where the function was called.

Python Anonymous(Lambda) Functions


A function without a name is called 'anonymous function' . So far, the functions we wrote
were defined using the keyword 'def'.But anonymous functions are not defined using 'def'. They
are defined using the keyword lambda and hence they are also called 'Lambda functions'

lambda functions are another name for anonymous functions.

Syntax:

lambda argument_list: expression

def square(x):

return x*x

The same function can be written as anonymous function as:

lambda x: x*x

f = lambda x: x*x

value = f(5)

print('Square of 5 =', value)

Here, 'f' is the variable name to which the lambda expression is assigned.

Lambda functions contain only one expression and they return the result implicitly. Hence we
should not write any 'return' statement in the lambda functions.

Properties of Lambda or Anonymous functions:

 Lambda functions have no name

 Lambda functions can take any number of arguments

 Lambda functions can just return a single value

 Lambda functions cannot access variables other than in their parameter list.

 Lambda functions cannot even access global variables.

Using lambdas with Python built-ins


Lambda functions provide an elegant and powerful way to perform operations using built-in
methods in Python. It is possible because lambdas can be invoked immediately and passed as an
argument to these functions.

 filter()

 map()

 reduce().

Using the filter() function

Using the filter function, specific elements can be chosen from a list of elements. Any iterator,
such as lists, sets, tuples, etc., can be used as the sequence. The elements that will be chosen will
depend on a pre-defined constraint. There are two parameters -

 A function that specifies the filtering constraint

 A series of any iterator like lists, tuples, etc.

Syntax:

filter(function, sequence)

Example:

Series = [23,45,57,39,1,3,95,3,8,85]

result = filter (lambda m: m > 29, series)

print('All the numbers greater than 29 in the series are :',list(result))

Use in map() function

Function The map() function is similar to filter() function but it acts on each element of the
sequence and perhaps changes the elements.

Syntax:

map(function, sequence)

The 'function' performs a specified operation on all the elements of the sequence and the modified
elements are returned which can be stored in another sequence.

Example:
series = [23,5,1,7,45,9,38,65,3]

result = map (lambda m: m*m*m, series)

print('The cube of each element in the list are :',list(result))

Use in reduce() function

This function reduces the sequence of elements into a single element by applying a specific
condition or logic. To use the reduce function we need to import the functools module.

Syntax:

reduce(function, sequence)

Example:

def add(x, y):

return x + y

def multiply(x, y):

return x * y

data = [1, 2, 3, 4]

reduce(add, data)

10

reduce(multiply, data)

24

Scope of the Variables in a Function

All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable. The part of the program in which a variable can be accessed
is called its scope. The duration for which a variable exists is called its “Lifetime”. If a variable is
declared and defined inside a function its scope is limited to that function only. Itcannot be
accessed to outside that function. If an attempt is made to access it outside that
function an error is raised.

The scope of a variable determines the portion of the program where you can access aparticular
identifier. There are two basic scopes of variables in Python:

 Global Scope -variables defined outside the function and part of main program

 Local Scope - variables defined inside functions have local scope

Local variable

A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function.

A variable created inside a function is available inside that function:

def myfunc():

x = 300

print(x)

myfunc()

Output

300

Global variable

Global variables are available from within any scope, global and local. A variable created outside
of a function is global and can be used by anyone:

x = 300

def myfunc():

print(x)

myfunc()

print(x)

Output
300

300

The global keyword makes the variable global.

def myfunc():

global x

x = 300

myfunc()

print(x)

Recursive Functions

A recursive function is defined as a function that calls itself to solve a smaller version of its task
until a final call is made which does not require a call to itself. Every recursive solution has two
major cases, which are as follows:

 base case, in which the problem is simple enough to be solved directly without making any
further calls to the same function.
 recursive case, in which first the problem at hand is divided into simpler sub parts.
 Recursion utilized divide and conquer technique of problem solving.

Recursion vs Iteration:

Recursion is more of a top-down approach to problem solving in while the original problem is
divided into smaller sub-problems.

Iteration follows a bottom-up approach that begins with what is known and then constructing the
solution step-by-step.

Pros The benefits of using a recursive program are:

 Recursive solutions often tend to be shorter and simpler than non-recursive ones.
 Code is clearer and easier to use.
 Recursion uses the original formula to solve a problem.
 It follows a divide and conquer technique to solve problems.
 In some instances, recursion may be more efficient.

Cons The limitations of using a recursive program are:

For some programmers and readers, recursion is difficult concept.


Recursion is implemented using system stack. If the stack space on the system is limited,
recursion to a deeper level will be difficult to implement.
Aborting a recursive process in midstream is slow and sometimes nasty.
Using a recursive function takes more memory and time to execute as compared to its non-
recursive counterpart.
It is difficult to find bugs, particularly when using global variables.
Conclusion: The advantages of recursion pays off for the extra overhead involved in terms of time
and space required.

Modules_II
Till now, we were taking the input from the console and writing it back to the console to interact
with the user. Instead of that we can able use files as input or output.

Introduction to Modules, files and Exceptions


What is Pyhton Module?
 Modular programming refers to the process of breaking a large, unwieldy programming
task into separate, smaller, more manageable subtasks or modules.
 Individual modules can then be cobbled together like building blocks to create a larger
application.
 A Python module is a file containing Python definitions and statements. A module can
define functions, classes, and variables. A module can also include runnable code.
Grouping related code into a module makes the code easier to understand and use. It also
makes the code logically organized.

Example:
def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
import csm_a
print(csm_a.add(10, 2))
What is File?
 When a program is being executed, its data is stored in RAM. Though RAM can be
accessed faster by the CPU, it is also volatile, which means when the program ends, or the
computer shuts down, all the data is lost. If you want to use the data in future, then you
need to store this data on a permanent or nonvolatile storage media such as hard disk, USB
drive and DVD e.t.c.,
 A file is a collection of data stored on a secondary storage device like hard disk

Modular programming refers to the process of breaking a large, unwieldy programming task into
separate, smaller, more manageable subtasks or modules.
Individual modules can then be cobbled together like building blocks to create a larger
application.
There are several advantages to modularizing code in a large application:
 Simplicity: Rather than focusing on the entire problem at hand, a module typically focuses
on one relatively small portion of the problem.
 Maintainability: Modules are written in a way that minimizes interdependency. This
makes it more viable for a team of many programmers to work collaboratively on a large
application.
 Reusability: Functionality defined in a single module can be easily reused. This
eliminates the need to duplicate code.
 Scope: Modules often declare a distinct namespace to prevent identifier clashes in various
parts of a program.

What is namespace? Explain different types of name space and their Scope?
Every entity in python is considered an object. We give some names to every object like variable,
class, and function for identification. Often these names are known as identifiers in python. So,
the name is nothing but the identifier. All these names and where we use value are stored in the
main memory at a unique location. This location is known as space. So the location allocated to an
object name and its value is known as python namespaces.

Python also maintains its namespace that is known as a python dictionary. All namespaces in
python are like dictionaries in which names are considered as keys, and dictionary values are the
actual values associated with those names.

Example:

The telephone directory is a good real-time example for the namespace. If we try to search a
phone number of a person named SAHASRA, there are multiple entries, and it will be difficult to
find the right one. But if we know the surname of SAHASRA, we can see the correct number. In
this case, a person's name is a name or identifier in python, and space depends on the person’s
location.

Types of Namespaces in Python

1. Built-in Namespace
2. Global Namespace
3. Local Namespace
4. Create namespace

Built-in Namespace

When we run the Python interpreter without creating any user-defined function, class, or
module, some functions like input(), print(), type() are always present. These are built-in python
namespaces.

Example:

name=input("Enter your name:")

print(name)

we are using input() and print() without creating any function or without accessing any module

Global Namespace

When we create a module, it creates its namespaces, and these are called global
namespaces. The global namespace can access built-in namespaces.

Example:

x=10

def f1():

print(x)

f1()

The variable x is declared in a global namespace and has a global scope of variable in python.

Local Namespace

When we create a function, it creates its namespaces, and these are called local
namespaces. A local namespace can access global as well as built-in namespaces.

def f1(): #function definition

print("function start ")

def f2():

var = 10 # local scope of variable in python

print("local function, value of var:",var)

f2()
print("Try printing var from outer function: ",var)

f1()

The variable var is declared in a local namespace and has a local scope of variable in python.

Create namespace

x='I am Global' #global namespace and global scope of variable in python

def f1(): #function definition

y='I am Local' # local namespace and local scope of variable in python

print(x) #accessing global namespace from local namespace

print(y) #accessing local namespace, we use

f1() #function calling

print('I am Built-in') # print() is a built-in namespace

we have used a built-in namespace i.e. print() which is accessed by global and local namespace.
Also, we have created global namespace x and local namespace y.

Scopes in Python

The lifetime of the object depends on the scope of the object. Once the lifetime of the object
comes to the end scope of variables in python also ends. Scopes in python are nothing but the part
or portion of the program where namespace can be accessed directly.

Types of Scope

1. Local Scope

If we create a variable inside the function, then the scope of the variable in python is local.

[Link] Scope

If we create a variable inside the module, then that variable has a global scope in python.

3. Built-in Scope

When we don’t create any module or user-defined function and still can access the methods
like print(), type(), input(), then it is a built-in scope. When a script is run that created or loaded
built-in scope.

4. Function Inside Function

The variable is defined under the function, which is available only inside that function and
nested function.
create a module
In Python programming, to create a module simply define the functions, classes, and variables that
you want to place in the module and save the file with .py extension. For example, let's create a
module which performs all arithmetic operations.

Example:

def add(a, b):

return a + b

def sub(a, b):

return a - b

defmul(a, b):

return a * b

def div(a, b):

return a / b

Module types
In Python, there are two types of modules.

 Built-in Modules

 User-defined Modules

Built-in Modules:

Built-in modules come with default Python installation. One of Python’s most significant
advantages is its rich library support that contains lots of built-in modules. Hence, it provides
a lot of reusable code. Some commonly used Python built-in modules are os, math, sys, random,
datetime, etc.

import datetime

now = [Link]()

print(now)

print([Link])

print([Link])

print([Link])

User-defined modules
The modules which the user defines or create are called a user-defined module. We can create
our own module, which contains classes, functions, variables, etc., as per our requirements.

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

import file name

print("Addition of x and y4 is:", [Link](x, y))

What is the Python import module?

A file is considered as a module in python. To use the module, you have to import it using the
import keyword. The function or variables present inside the file can be used in another file by
importing the module. This functionality is available in other languages, like typescript,
JavaScript, java, ruby, etc.

Loading the module in our python code

We need to load the module in our python code to use its functionality. Python provides three
types of statements as defined below.

1. import <-module name->

2. from <-module name-> import <-method name->

3. form <-module name-> import*

The import statement


The import statement is used to import all the functionality of one module into another. Here, we
must notice that we can use the functionality of any python source file by importing that file as the
module into another python source file.

We can import multiple modules with a single import statement, but a module is loaded once
regardless of the number of times, it has been imported into our file.

The syntax to use the import statement is given below.


import module1,module2,........ module n

Bulti-in Module using import

import math

print([Link](4))

import math

print([Link](0))

User Define Module using import

program.

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

import calculator

print(“Addition of 5 and 4 is:”;, [Link](5, 4))

print(“Subtraction of 7 and 2 is”;, [Link](7, 2))

print(“Multiplication of 3 and 4 is:”, [Link](3, 4))

print(“Division of 12 and 3 is:”, [Link](12, 3))

from .. import statement


The from….import statement allows you to import specific functions/variables from a module
instead of importing everything. In the previous example, when you imported calculation into
module_test.py, both the add() and sub() functions were imported.

Syntax:

from < module-name> import <name 1>, <name 2>..,<name n>

Bulit in Module using from import


from random import choice

fruits = ["Apple", "Pear", "Banana"]

print(choice(fruits))

user define Module using from import

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

from calculator import add,sub,mul,div

print(“Addition of 5 and 4 is:”;, [Link](5, 4))

print(“Subtraction of 7 and 2 is”;, [Link](7, 2))

print(“Multiplication of 3 and 4 is:”, [Link](3, 4))

print(“Division of 12 and 3 is:”, [Link](12, 3))

We use the from keyword, followed by random, to tell our program that we want to import a
specific function from the “random” module. Then, we usethe import keyword to tell our code
what function we want to import.

When using the from keyword to import a function, you do not need to write the function using
dot notation. As you can see above, instead of using [Link]() to access
the [Link]() function from the random module, we just use choice().

Import all Names - From import * Statement


To import all the objects from a module within the present namespace, use the * symbol and the
from and import keyword.

Syntax:

from name_of_module import *


here are benefits and drawbacks to using the symbol *. It is not advised to use * unless we are
certain of our particular requirements from the module; otherwise, do so.

Bulit in Module using import*

from math import *

print(sqrt(25) )

print(tan(pi/6) )

print(pi)

print(tan(34))

print(factorial(5))

user define in Module using import*

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

from calculator import*

print(“Addition of 5 and 4 is:”;, [Link](5, 4))

print(“Subtraction of 7 and 2 is”;, [Link](7, 2))

print(“Multiplication of 3 and 4 is:”, [Link](3, 4))

print(“Division of 12 and 3 is:”, [Link](12, 3))

Importing Module Attributes

Python Module Attributes: name, doc, file, dict


Attributes perform some tasks or contain some information about the module.
Some of the important attributes are explained below:

__name__ Attribute

The __name__ attribute returns the name of the module. By default, the name of the file
(excluding the extension .py) is the value of __name__attribute.

Example:

import math

print(math.__name__) #'math'

_doc__ Attribute

The __doc__ attribute denotes the documentation string (docstring) line written in a module code.

Example:

import math

print(math.__doc__)

Output:

This module provides access to the mathematical functions

defined by the C standard.

_file__ Attribute

__file__ is an optional attribute which holds the name and path of the module file from which it is
loaded.

Example:

import io

print(io.__file__)

output: 'C:\\python37\\lib\\[Link]'

__dict__ Attribute

The __dict__ attribute will return a dictionary object of module attributes, functions and other
definitions and their respective values.

Example:

import math

print(math.__dict__)
Module Built-in Functions

Renaming a module
print("Addition is : ",Add(num1,num2))

Python provides us the flexibility to import some module with a specific name so that we can use
this name to use that module in our python source file.

Syntax:

import <module-name> as <specific-name>

import calculation as cal;

a = int(input("Enter a?"));

b = int(input("Enter b?"));

print("Sum = ",[Link](a,b))

Using dir() function


The dir() function returns a sorted list of names defined in the passed module. This list contains all
the sub-modules, variables and functions defined in this module.

Import json

List = dir(json)

print(List)

The reload() function


As we have already stated that, a module is loaded once regardless of the number of times it is
imported into the python source file. However, if you want to reload the already imported module
to re-execute the top-level code, python provides us the reload() function.

The syntax to use the reload()

reload(<module-name>)

The globals() and locals() Functions:


The globals() and locals() functions can be used to return the names in the global and local
namespaces depending on the location from where they are called. If locals() is called from with
in a function, it will return all the names that can be accessed locally from that function. If
globals() is called from with in a function, it will return all the names that can be accessed
globally from that function. The return type of both these functions is dictionary. Therefore,
names canbe extracted using the keys() function.

What is a Package in Python?

A package is a hierarchical file directory structure that defines a single Python application
environment that consists of modules and sub packages and sub-sub packages, and so on.

Creating Package

Let’s create a package named mypckg that will contain two modules mod1 and mod2.

To create this module follow the below steps –

 Create a folder named mypckg.

 Inside this folder create an empty Python file i.e. __init__.py

 Then create two modules mod1 and mod2 in this folder.

Filename [Link]

def SayHello(name):

print("Hello ", name)

[Link]

def sum(x,y):

return x+y

def average(x,y):

return (x+y)/2

def power(x,y):
return x**y

Package Initialization __init__.py :

The package folder contains a special file called __init__.py, which stores the package's content. It
serves two purposes:

 The Python interpreter recognizes a folder as the package if it contains __init__.py file.
 __init__.py exposes specified resources from its modules to be imported.

An empty __init__.py file makes all functions from the above modules available when this
package is imported. Note that __init__.py is essential for the folder to be recognized by Python
as a package.

Steps:

 First create folder game.


 Inside it again create folder sound.
 Inside sound folder create [Link] file.
 Inside sound folder create [Link] file.
 Inside sound folder create [Link] file.
 Import package game and subpackage sound(files:load,pause,play)

Example:

Def baz():

print('[mod3] baz()')

class Baz:

pass

from.. import sub_pkg1

print(sub_pkg1)

from..sub_pkg1.mod1import foo

foo()

from pkg.sub_pkg2 import mod3 <module 'pkg.sub_pkg1' (namespace)>[mod1] foo()

You might also like