0% found this document useful (0 votes)
8 views83 pages

Module 2

Modular programming in Python involves breaking large programs into smaller, manageable modules, enhancing simplicity, maintainability, and reusability. It also covers local and global variable scopes, error handling, and the use of built-in modules and regular expressions for various operations. The document further explains string operations, including concatenation, repetition, membership, and slicing, along with methods for traversing strings.

Uploaded by

bhasinanju5
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)
8 views83 pages

Module 2

Modular programming in Python involves breaking large programs into smaller, manageable modules, enhancing simplicity, maintainability, and reusability. It also covers local and global variable scopes, error handling, and the use of built-in modules and regular expressions for various operations. The document further explains string operations, including concatenation, repetition, membership, and slicing, along with methods for traversing strings.

Uploaded by

bhasinanju5
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

Modular Programming

• It is a process of breaking large programs into


smaller and manageable programs.
• Modularity in python can be implemented
through using functions, modules and
packages.
• These modules can be clubbed together to
created a larger application.
Advantage of Modular Programming
1. Simplicity – Instead of taking the entire problem, we take a small
portion of the problem. It can make the code much easier to develop
and maintain. eg. Function or Module.

2. Maintainability – Function or Module applies the logical boundaries


between portions of problem. It reduces the coupling or interdependency
among the modules. This helps the team of programmer to work
simultaneously on the large projects
.
3. Reusability – It allows reusing the same code in different part of the large
application, without duplicating them. Import utilities used in the python to
reuse the functionality.

4. Scoping – Modules or Packages creates a namespace which helps to


remove the ambiguity for names defined in the programs.
The local and global Scoping
1. Variables and parameters that are initialized
within a function including parameters, are said
to exist in that function’s local scope. Variables
that exist in local scope are called local variables.
2. Variables that are assigned outside functions are
said to exist in global scope. Therefore, variables
that exist in global scope are called global
variables.
Local Variables Cannot be Used in Global Scope
Practice:
Reading Global Variables from a Local Scope
Local and Global Variables with the Same Name
The Global Statement
Errors and Exceptions
Errors:
• Syntax Errors
example of syntax errors:
>>> prin t ( He l l o World )
Fi l e "<ipython input 1 10cb182148e3>" , l i n e 1
prin t ( He l l o World )

SyntaxEr ror : i n v a l i d syntax


• In the example we have written print(Hello World) instead
of print("Hello World") and then the Python Interpreter
gives us an error message.
Exceptions
Even if a statement or expression is syntactically correct, it may cause
an error when an attempt is made to execute it. Errors detected
during execution are called exceptions.
Most exceptions are not handled by programs, however, and result in
error messages as shown here:
>>> 10 * (1/0)

Traceback (most recent call last ) :

Fi l e "<ipython input 20b280f36835c>" , l i n e 1 , in <module>


10 * (1/0)

Zero Division Error : division by zero


Exceptions Handling
It is possible to write programs that handle selected
exceptions.
In Python we can use the following built-in Exceptions
Handling features:
• The try block lets you test a block of code for errors.
• The except block lets you handle the error.
• The finally block lets you execute code, regardless of
the result of the try and except blocks.

When an error occurs, or exception as we call it, Python


will normally stop and generate an error message.
These exceptions can be handled using the try - except
statements.
Examples
The finally block, if specified, will be executed
regardless if the try block raises an error or not.
Modules
• A module helps to break the large program to
manageable and organized code. It allows the
reusability of code.
• Module is a Python file containing a set of Python
Statements and Functions.
• Module files has the “.py” extension. e.g. my_abc.py
• Create Module
To create a module , save a file with extension “.py”
File my_abc.py
def show(name, age) :
print("Name : " , name)
print("Age : ", age)
Employee= { "name":"Ajay", "age":30, "Salary":20000 }
Import Module
• Import Statement help to provide the Module
contents to the caller program code.
• Import module created a separate namespace,
which contains all the objects define in the
module.
• Module content like identifiers , functions , class
or objects defined in the module can be accessed
using the dot notation like
<ModuleName>.<FunctionName>.
eg. my_abc.show( )
Syntax
import Module_Name
Example
To import the module “my_abc.py” for using in the “[Link]” program file.
import my_abc
print("\n Accessing function from Module\n")
my_abc.show("vikas",27)
print("\n Accessing Variable from Module\n")
print(my_abc.Employee["name"])
print(my_abc.Employee["age"])
print(my_abc.Employee["salary"])
Output
Accessing function from Module
Name : vikas
Age : 27
Accessing Variable from Module
Ajay
30
20000
Renaming Module
To import the module “my_abc.py” and rename it “m” for using in
the “[Link]” program file.
import my_abc as m
print("\n Accessing function from Module\n")
[Link]("vikas",27)
print("\n Accessing Variable from Module\n")
print([Link]["name"]) print([Link]["age"])
print([Link]["salary"])
Output
Accessing function from Module
Name : vikas
Age : 27
Accessing Variable from Module
Ajay 30
20000
DIY
• Using the dir( ) function
• Using the from …import
• Importing all the Modules using from…import
Standard modules
• The Python Standard Library is a collection of script
modules that may be used by a Python program,
making it unnecessary to rewrite frequently used
commands and streamlining the development process.
By "calling/importing" them at the start of a script,
they can be used.
• A module is a file that contains Python code; an
‘[Link]’ file would be a module with the name
‘coding’. We utilise modules to divide complicated
programmes into smaller, more manageable pieces.
Modules also allow for the reuse of code.
Some standard modules
• The datetime module
• The math module
• The random module
• The re module
• The os module
• The io module
• The json module
• The copy module
*study and practice
Regular Expressions
A regular expression is a compact notation for
representing a collection of strings. What makes
regular expressions so powerful is that a single
regular expression can represent an unlimited
number of strings—providing they meet the regular
expression’s requirements. Regular expressions are
defined using a mini-language that is completely
different from Python—but Python includes the re
module through which we can seamlessly create
and use regular expressions.
Regular expressions(Regex) are used
for
Parsing: identifying and extracting pieces of text that
match certain criteria—regular expressions are used for
creating ad hoc parsers and also by traditional parsing
tools.

Searching: locating substrings that can have more than


one form, for example, finding any of “[Link]”,
“[Link]”, “[Link]”, or “[Link]” while avoiding
“[Link]” and similar.
Searching and replacing: replacing everywhere
the regular expressions matches with a string,
for example, finding “bicycle” or “human
powered vehicle” and replacing either with
“bike”.
Splitting strings: splitting a string at each place
the regex matches, for example, splitting
everywhere colon-space or equals (“: ” or “=”)
occurs.
Validation: checking whether a piece of text
meets some criteria, for example, contains a
currency symbol followed by digits.
The Regular Expression Module
The re module provides two ways of working with regexes. One
is to use the functions listed in Table
where each function is given a regular
expression as its first argument. Each function
converts the regex into an internal format—a
process called compiling—and then does its
work. This is very convenient for one-off uses,
but if we need to use the same regex repeatedly
we can avoid the cost of compiling it at each use
by compiling it once using the [Link]()
function. We can then call methods on the
compiled regex object as many times as we like.
The compiled regex methods are listed in Table
Quantifiers
A quantifier has the form {m,n} where m and n
are the minimum and maximum times the
expression the quantifier applies to must match.
Quantifiers
In regular expressions, quantifiers match the preceding characters or character sets
a number of times. The following table shows all the quantifiers and their meanings:

Quantifier Name Meaning


* Asterisk Match its preceding element
zero or more times.

+ Plus Match its preceding element one


or more times.

? Question Mark Match its preceding element


zero or one time.

{n} Curly Braces Match its preceding element


exactly n times.
{ n ,} Curly Braces Match its preceding element at
least n times.
{n,m} Curly Braces Match its preceding element
from n to m times.
STRINGS
String is a sequence which is made up of one or
more UNICODE characters. Here the character can
be a letter, digit, whitespace or any other symbol. A
string can be created by enclosing one or more
characters in single, double or triple quote.
Example
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!''
Accessing Characters in a String
Each individual character in a string can be accessed
using a technique called indexing. The index
specifies the character to be accessed in the string
and is written in square brackets ([ ]). The index of
the first character (from left) in the string is 0 and
the last character is n-1 where n is the length of the
string.
If we give index value out of this range then we get
an IndexError.
The index must be an integer (positive, zero or
negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> str1[0]
'H'
#gives seventh character of str1
>>> str1[6]
'W'
#gives last character of str1
>>> str1[11]
'!'
#gives error as index is out of range
>>> str1[15]
IndexError: string index out of range
The index can also be an expression including
variables and operators but the expression must
evaluate to an integer.
#an expression resulting in an integer index
#so gives 6th character of str1
>>> str1[2+4]
'W'
#gives error as index must be an integer
>>> str1[1.5]
TypeError: string indices must be integers
Python allows an index value to be negative
also. Negative indices are used when we want to
access the characters of the string from right to
left. Starting from right hand side, the first
character has the index as -1 and the last
character has the index –n where n is the length
of the string.
>>> str1[-1] #gives first character from right '!'
>>> str1[-12]#gives last character from right 'H'
Positive Indices 0 1 2 3 4 5 6 7 8 9 10 11
String H e l l o W o r l d !
Negative Indices -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2
-1
An inbuilt function len() in Python returns the length of the
string that is passed as parameter. For example,
the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> len(str1)
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
'H'
String is Immutable
A string is an immutable data type. It means that the
contents of the string cannot be changed after it
has been created. An attempt to do this would lead to
an error.
>>> str1 = "Hello World!"
#if we try to replace character 'e' with 'a'
>>> str1[1] = 'a'
TypeError: 'str' object does not support item
assignment
STRING OPERATIONS
Python allows certain operations on string data type, such as
concatenation, repetition, membership and slicing.
Concatenation
To concatenate means to join. Python allows us to join two strings
using concatenation operator plus which is denoted by symbol +.

>>> str1 = 'Hello' #First string


>>> str2 = 'World!' #Second string
>>> str1 + str2 #Concatenated strings
'HelloWorld!'
#str1 and str2 remain same
>>> str1 #after this operation.
'Hello'
>>> str2
'World!'
Repetition
Python allows us to repeat the given string using
repetition operator which is denoted by symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> str1 * 2
'HelloHello'
#repeat the value of str1 5 times
>>> str1 * 5
'HelloHelloHelloHelloHello'
Note: str1 still remains the same after the use of
repetition operator.
Membership
Python has two membership operators 'in' and 'not in'. The 'in'
operator takes two strings and returns True if the first string appears
as a substring in the
second string, otherwise it returns False.
>>> str1 = 'Hello World!'
>>> 'W' in str1
True
>>> 'Wor' in str1
True
>>> 'My' in str1
False
The 'not in' operator also takes two strings and returns True if the
first string does not appear as a substring in the second string,
otherwise returns False.
>>> str1 = 'Hello World!'
>>> 'My' not in str1
True
>>> 'Hello' not in str1
False
Slicing
In Python, to access some part of a string or
substring, we use a method called slicing. This
can be done by specifying an index range.
Given a string str1, the slice operation str1[n:m]
returns the part of the string str1 starting from
index n (inclusive) and ending at m (exclusive).
In other words, we can say that str1[n:m]
returns all the characters starting from str1[n]
till str1[m-1]. The numbers of characters in the
substring will always be equal to difference of
two indices m and n, i.e., (m-n).
>>> str1 = 'Hello World!'
#gives substring starting from index 1 to 4
>>> str1[1:5]
'ello'
#gives substring starting from 7 to 9
>>> str1[7:10]
'orl'
#index that is too big is truncated down to
#the end of the string
>>> str1[3:20]
'lo World!'
#first index > second index results in an
#empty '' string
>>> str1[7:2]
If the first index is not mentioned, the slice starts
from index.
#gives substring from index 0 to 4
>>> str1[:5]
'Hello'
If the second index is not mentioned, the slicing is done till the
length of the string.
#gives substring from index 6 to end
>>> str1[6:]
'World!'
The slice operation can also take a third index that specifies
the ‘step size’. For example, str1[n:m:k], means every kth
character has to be extracted from the string str1 starting
from n and ending at m-1. By default, the step size is one.
>>> str1[0:10:2]
'HloWr'
>>> str1[0:10:3]
'HlWl'
Negative indexes can also be used for slicing.
#characters at index -6,-5,-4,-3 and -2 are
#sliced
>>> str1[-6:-1]
'World'
If we ignore both the indexes and give step size
as -1
#str1 string is obtained in the reverse order
>>> str1[::-1]
'!dlroW olleH'
TRAVERSING A STRING
We can access each character of a string or traverse
a string using for loop and while loop.
(A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')
Hello World! #output of for loop
In the above code, the loop starts from the first
character of the string str1 and automatically ends
when the last character is accessed.
(B) String Traversal Using while Loop:
>>> str1 = 'Hello World!'
>>> index = 0
#len(): a function to get length of string
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World! #output of while loop
Here while loop runs till the condition index
< len(str) is True, where index varies from 0 to
len(str1) -1.
STRING METHODS AND BUILT-IN FUNCTIONS
HANDLING STRINGS
1. Write a program with a user defined function to count the
number of times a character (passed as argument) occurs in the
given string.
2. Write a program with a user defined function with string as a
parameter which replaces all vowels in the string with '*'.
3. Write a program to input a string from the user and print it in the
reverse order without creating a new string.
4. Write a program which reverses a string passed as parameter
and stores the reversed string in a new string. Use a user defined
function for reversing the string.
5. Write a program using a user defined function to check if a string
is a palindrome or not. (A string is called palindrome if it reads
same backwards as forward. For example, Kanak is a
palindrome.)
Library in Python
What is a Library?
Each of Python's open-source libraries has its own source
code. A collection of code scripts that can be used iteratively
to save time is known as a library. It is like a physical library in
that it has resources that can be used again, as the name
suggests.
A collection of modules that are linked together is also known
as a Python library. It has code bundles that can be used again
and again in different programs. For programmers, it makes
Python programming easier and simpler. Since then, we will
not need to compose the same code for various projects.
Python libraries are heavily used in a variety of fields, including
data visualization, machine learning, and computer science.
How Python Libraries work?
Python library is nothing more than a collection of
code scripts or modules of code that can be used in
a program for specific operations.
We use libraries to avoid having to rewrite existing
program code. However, the process is as follows: In
the MS Windows environment, the library files have
a DLL (Dynamic Load Libraries) extension. The linker
automatically looks for a library when we run our
program and import it. It interprets the program in
accordance with the functions extracted from the
library. This is how we use library strategies in our
program.
Standard Libraries of Python
1. Matplotlib
This library is responsible for the plotting of numerical data. It is utilized in
data analysis for this reason. An open-source library plots superior quality
figures, for example, pie outlines, scatterplots, boxplots, and diagrams, in
addition to other things.

2. NumPy
One of the most popular open-source Python packages, NumPy focuses on
scientific and mathematical computation. It makes it easy to work with large
matrices and multidimensional data thanks to built-in mathematical functions
that make it easy to compute. It can be used as an N-dimensional container
for all kinds of data, including linear algebra. An N-dimensional array with
rows and columns is defined by the NumPy Array Python object. It can also be
used as a random number generator because of this.
NumPy is preferred over lists in Python because it uses less memory, is faster,
and is easier to use. Pictures, sound waves, and other parallel crude streams
can be addressed as a multi-faceted exhibit of genuine qualities involving the
NumPy interface for perception. NumPy is required for full-stack developers
to use this machine learning library.
3. Pandas
Pandas is an open-source library authorized under the Berkeley Programming
Conveyance (BSD). This well-known library is frequently utilized in the field of data
science. They're generally utilized for examination, control, and cleaning of information,
in addition to other things. Without having to switch to another programming language
like R, Pandas enables us to carry out straightforward data modelling and analysis.
4. SciPy
Scipy is a Python library. Scientific computing, information processing, and high-level
computing are the primary uses for this open-source library. The library contains a large
number of easy-to-use methods and functions for quick and easy computation. Scipy
can be utilized for numerical calculations close by NumPy.
Some of SciPy's subpackages include cluster, fftpack, constants, integrate, io, linalg,
interpolate, ndimage, odr, optimize, signal, spatial, special, sparse, and stats.
5. Scikit- learn
Additionally, Scikit-learn is a Python-based open-source machine learning library. This
library supports both supervised and unsupervised learning methods. This library
already comes pre-installed with a number of well-known algorithms as well as the
SciPy, NumPy, and Matplotlib packages. Spotify music recommendations are the
Scikit-most-learn application that is most widely used.

You might also like