You are on page 1of 33

PRACTICALS

IT21L

Practical Assignment
Book
MCA I Semester II
2021-2023
Name : Shehbaz Hasware
Roll No : 112
Subject Faculty:
Python Programming: Prof. Tabassum Shaikh
Advance Internet Technology: Prof. Pankaj Kulkarni
1
[PART I] PYTHON PROGRAMMING

PART I
PYTHON
PROGRAMMING
[PART I] PYTHON PROGRAMMING

INDEX
Sr. No Assignment Page No.
1 Python installation and configuration with windows
and Linux
2 Programs for understanding the data types, control flow
statements, blocks and loops
3 Programs for understanding functions, use of built in
functions, user defined functions
4 Programs to use existing modules, packages and
creating modules, packages
5 Programs for implementations of all object-oriented
concepts like class, method, inheritance, polymorphism
etc. (Real life examples must be covered for the
implementation of object oriented concepts)
6 Programs for parsing of data, validations like
Password, email, URL, etc.
7 Programs for Pattern finding should be covered.
8 Programs covering all the aspects of Exception
handling, user defined exception, Multithreading
should be covered.
9 Programs demonstrating the IO operations like reading
from file, writing into file from different file types like
data file, binary file, etc
10 Programs to perform searching, adding, updating the
content from the file.
Program for performing CRUD operation with
11
MongoDB and Python
[PART I] PYTHON PROGRAMMING

Basic programs with NumPy as Array, Searching and


12
Sorting, date & time and String handling
Programs for series and data frames should be covered.
13
Programs to demonstrate data pre-processing and data
14
handling with data frame
Program for data visualization should be covered.
15

Prof. Tabassum Shaikh


Python Programming

Student Name: Shehbaz Hasware


Signature:
[PART I] PYTHON PROGRAMMING

1. Python installation and configuration with windows and Linux

Step 1: Select Version of Python to download Full Installer and


install
The most stable Windows downloads are available from
the Python for Windows page. On Windows, you have a choice
between 32-bit (labeled x86) and 64-bit (labeled x86–64)
versions, and several flavors of the installer for each. Underneath the Python Releases
for Windows find the Latest
Python 3 Release — Python 3.9.4
Step 2: Download Python Executable Installer and install it
Double-click the executable file, which is downloaded; the
following window will open. Select Customize installation and
proceed. Click on the Add Path check box, it will set the Python
path automatically. 1. Run the Python Installer once downloaded. (In this example,
we have downloaded Python 3.9.4)
2. Make sure you select the “Install launcher for all users” and
“Add Python 3.9 to PATH” checkboxes. 3. Select Install Now — the recommended installation options.
Step 3: Wait for it to complete the installation process
The next dialog will prompt you to select whether to Disable the
path length limit. Choosing this option will allow Python to
bypass the 260-character MAX_PATH limit. Effectively, it will
enable Python to use long path names.
The Disable path length limit option will not affect any other
system settings. Turning it on will resolve potential name length
issues that may arise with Python projects developed in Linux
Step 4: Verification of installation of python in Windows
To check if Python 3.9.4 has been successfully installed in our
system,
Open Cmd prompt in your system
Run “ Python -V”
Step 5: Run python
Kudos! python has been installed in your system, Now go to
1. Windows search
2. Type IDLE
3. Open it. Run your First Python code
Step 6: Verify Pip Was Installed
Installation and configuration with Linux. Using the standard Linux installation
The standard Linux installation works on any system. However,
it requires you to work at the Terminal and type commands to
complete it. Some of the actual commands may vary by version
of Linux. The information on Python installations provides
some helpful tips that you can use in addition to the procedure
that follows. 1. Navigate to the Python download site with your browser.
You see information regarding the latest version of
Python. 2. Click the appropriate link for your version of Linux:
1. Python 3.3.4 compressed source tarball (any version of
Linux)
2. Python 3.3.4 xzipped source tarball (better compression
and faster download)
3. When asked whether you want to open or save the file, choose Save.
The Python source files begin downloading. Be patient: The
source files require a minute or two to download.
4. Double-click the downloaded file.
The Archive Manager window opens. After the files are
extracted, you see the Python 3.3.4 folder in the Archive
Manager window.
5. Double-click the Python 3.3.4 folder.
The Archive Manager extracts the files to the Python 3.3.4
subfolder of your home folder.
6. Open a copy of Terminal. The Terminal window appears. If you have never built any
software on your system before, you must install the build-essentials,
SQLite, and bzip2, or the Python installation will fail.
Otherwise, you can skip to Step 10 to begin working with Python immediately.
7. Type sudo apt-get install build-essential and press Enter.
Linux installs the Build Essential support required to build packages.
8. Type sudo apt-get installs libsqlite3-dev and press Enter.
Linux installs the SQLite support required by Python for database manipulation.
9. Type sudo apt-get installs libbz2-dev and press Enter.
Linux installs the bzip2 support required by Python for archive manipulation.
10. Type CD Python 3.3.4 in the Terminal window and press Enter.
Terminal changes directories to the Python 3.3.4 folder on your system.
11. Type. /configure and press Enter. The script begins by checking the system
build type and then performs a series of tasks based on the system you’re using. This process
can require a minute or two because there is a large list of items to check.
12. Type makes and press Enter. Linux executes the make script to create the Python application
software. The making process can require up to a minute — it
depends on the processing speed of your system.
13. Type sudo make alt install and press Enter.The system may ask you for your administrator password.
Type
your password and press Enter. At this point, a number of tasks
take place as the system installs Python on your system. Using the graphical Linux installation
A few versions of Debian-based Linux distributions, such as Ubuntu 12.x and later,
provide a graphical installation technique as well. You need the administrator group (sudo) password to
use this procedure, so having it handy will save you time. The following steps outline the graphical
installation technique for Ubuntu, but the technique is similar for other Linux installations:
1. Open the Ubuntu Software Centre folder. (The folder may be named Synaptic on other platforms.)
You see a listing of the most popular software available for download and installation.
2. Select Developer Tools (or Development) from the All Software drop-down list box.
You see a listing of developer tools, including Python.
3. Double-click the Python 3.3.4 entry. The Ubuntu Software Centre provides details about the Python
3.3.4 entry and offers to install it for you. 4. Click Install. Ubuntu begins the process of installing Python.
A progress bar
shows the download and installation status. When the
installation is complete, the Install button changes to a Remove
button. 5. 5.Close the Ubuntu Software Centre folder. You see a Python icon added to the desktop.
Python is ready
for use.
[PART I] PYTHON PROGRAMMING

2. Programs for understanding the data types, control


flow statements, blocks and loops
Standard Data Types
Python has five standard data types- • Numbers
• String
• List • Tuple
• Dictionary
Python Numbers
Numeric
In Python, numeric data type represents the data which has
numeric value. Numeric value can be integer, floating number
or even complex numbers. These values are defined
as int, float and complex class in Python. Integers – This value is represented by int class. It
contains positive or negative whole numbers (without
fraction or decimal). In Python there is no limit to how
long an integer value can be. Float – This value is represented by float class. It is a real
number with floating point representation. It is specified
by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be
appended to specify scientific notation. Complex Numbers – Complex number is represented by
complex class. It is specified as (real part) + (imaginary
part)j. For example – 2+3j. Code:
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Note – type() function is used to determine the type of data
type. Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class 'complex'>
2. String
Strings are used to store data that involves characters (e.g., names or addresses).
Strings can be created in Python by
enclosing a sequence of characters within a pair of single or
double-quotes.
Code:
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World' print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek" print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
For
Life''' print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World
String with the use of Double Quotes:
I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>
Creating a multiline String:
Geeks
For
Life
2) List
Lists are just like the arrays, declared in other languages which
is a ordered collection of data. It is very flexible as the items in
a list do not need to be of the same type. Code:
# Python program to demonstrate
# Creation of List
# Creating a List
List = []
print("Intial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = ['CodeWithHarry']
print("\nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Code", "With", "Harry"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
List = [['Code', 'With'], ['Harry']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Intial blank List:
[]
List with the use of String:
['CodeWithHarry']
List containing multiple values:
Code
Harry
Multi-Dimensional List:
[['Code', 'With'], ['Harry']] 2. Dictionaries
3) Tuple A dictionary is an unordered, changeable, and indexed
Just like list, tuple is also an ordered collection of Python collection of elements. In Python, dictionaries are written with
objects. The only difference between tuple and list is that curly brackets and contain keys and values. See the code
tuples are immutable i.e. tuples cannot be modified after it is below:
created. It is represented by tuple class. Code: # Creating an empty Dictionary
# Python program to demonstrate Dict = {}
# creation of Set print("Empty Dictionary: ")
# Creating an empty tuple print(Dict)
Tuple1 = () # Creating a Dictionary
print("Initial empty Tuple: ") # with Integer Keys
print (Tuple1) Dict = {1: 'Code', 2: 'With', 3: 'Harry'}
# Creating a Tuple with print("\nDictionary with the use of Integer Keys: ")
# the use of Strings print(Dict)
Tuple1 = ('Geeks', 'For') # Creating a Dictionary
print("\nTuple with the use of String: ") # with Mixed keys
print(Tuple1) Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
# Creating a Tuple with print("\nDictionary with the use of Mixed Keys: ")
# the use of list print(Dict)
list1 = [1, 2, 4, 5, 6] # Creating a Dictionary
print("\nTuple using List: ") # with dict() method
print(tuple(list1)) Dict = dict({1: 'Code', 2: 'With', 3:'Harry'})
# Creating a Tuple with the print("\nDictionary with the use of dict(): ")
# use of built-in function print(Dict)
Tuple1 = tuple('Geeks') # Creating a Dictionary
print("\nTuple with the use of function: ") # with each item as a Pair
print(Tuple1) Dict = dict([(1, 'Code'), (2, 'With')])
# Creating a Tuple print("\nDictionary with each item as a pair: ")
# with nested tuples print(Dict)
Tuple1 = (0, 1, 2, 3) Output: Empty Dictionary:
Tuple2 = ('python', 'geek') {}
Tuple3 = (Tuple1, Tuple2) Dictionary with the use of Integer Keys:
print("\nTuple with nested tuples: ") {1: 'Code', 2: 'With', 3: 'Harry'}
print(Tuple3) Dictionary with the use of Mixed Keys:
OUTPUT {'Name': 'Geeks', 1: [1, 2, 3, 4]}
Initial empty Tuple: Dictionary with the use of dict():
() {1: 'Code', 2: 'With', 3: 'Harry'}
Tuple with the use of String: Dictionary with each item as a pair:
('Geeks', 'For') {1: 'Code', 2: 'With'}
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
('G', 'e', 'e', 'k', 's')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', 'geek'))

control flow statements


Loop Control Statements The Loop control statements change
the execution from its normal sequence. When the execution
leaves a scope, all automatic objects that were created in that
scope are destroyed. Python supports the following control
statements.
break statement
The break statement is used for premature termination of the
current loop. After
abandoning the loop, execution at the next statement is
resumed, just like the
traditional break statement in C. The most common use of
break is when some
external condition is triggered requiring a hasty exit from a loop. The break
statement can be used in both while and for loops. If you are
using nested loops, the break statement stops the execution of the innermost loop
and starts executing
the next line of the code after the block
Syntax
break
Example
for letter in 'Python': # First Example
if letter == 'h':
break
print ('Current Letter:', letter)
var = 10 # Second Example
while var > 0:
print ('Current variable value:', var)
var = var -1
if var == 5:
break
Print ("Good bye!")
When the above code is executed, it produces the following
result- Current Letter: P
Current Letter: y
Current Letter: t
Current variable value: 10
Current variable value: 9
Current variable value: 8
Current variable value: 7
Current variable value: 6
Good bye!
Blocks and loops
Loops
Looping Statements (while loop, infinite while loop, while … else, for loop, for loop... else, nested loops),
while loop
Repeats a statement or group of statements while a given
condition is TRUE. It tests the condition before executing the loop body.
for loop
Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable

nested loops
You can use one or more loop inside any another while, or for loop

A while loop statement repeatedly executes a target


statement as long as a given
condition is true. syntax is :
while expression:
statements
else:
statements
Example
count = 0
while (count < 9):
print ('The count is:', count)
count = count + 1
print ("Good bye!")
for Loop Statements
The for loop iterates over all the values in a sequence (string, List, tuple files objects
and dictionaries), performing the same task on each of the
elements. Syntax is :
for var in sequence:
statements
else:
statements
Nested loops
Python programming language allows the use of one loop
inside another loop. The
following section shows a few examples to illustrate the
concept. Syntax
for iterating_var in sequence:
for iterating_var in sequence:
statements(s)
statements(s
[PART I] PYTHON PROGRAMMING

3. Programs for understanding functions, use of built


in functions, user defined functions
Functions
A function is a block of organized, reusable code that is used to
perform a single, related action. Functions provide better
modularity for your application and a high degree of code
reusing. We can also create your own functions. These
functions are called user-defined functions. Defining a Function
Rules to define a function in Python. 1. Function blocks begin with the keyword def followed by the
function name and parentheses ( ). 2. Any input parameters or arguments should be placed
within these parentheses. You can also define parameters
inside these parentheses. 3. The first statement of a
function can be an optional statement - the documentation
string of the function or docstring. 4. The code block within every function starts with a colon (:)
and is indented. 5. The statement return [expression] exits a
function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return
None. Syntax
def functionname( parameters ): "function_docstring" function_suite
return [expression]
Example : The following function takes a string as input
parameter and prints it on the standard screen.
def printme( str ): "This prints a passed string into this function" print (str)
return
Docstring
The first string after the function header is called the docstring
and is short for documentation string. It is used to explain in
brief, what a function does. Although optional, documentation is a good programming
practice. Unless you can remember what you had for dinner
last week, always document your code. we have a docstring immediately below the function header.
We generally use triple quotes so that docstring can extend up
to multiple lines. This string is available to us as __doc__ attribute of the function.
For example:
Try running the following into the Python shell to see the
output. >>> print(printme.__doc__)
This prints a passed string into this function
Calling a Function
Defining a function gives it a name, specifies the parameters
that are to be included in the function and structures the
blocks of code. Once 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 an example to
call the printme() function
def printme( str ):
"This prints a passed string into this function" print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following
result- This is first call to the user defined function.
Function Arguments
A function can be called by using the following types of
formal arguments 1. Required arguments
#Requried Arguments - are those arguments which are
passed to function
# in a pearticular positional order
#The number of arguments in the function call should
exacly match
#with the function definations
def print_me(str): """This prints a passed String""" print(str)
return
print_me("ejaz")
x ="ejaz" print_me(x)
print_me() #Error as an arguments is reuried
Output:
ejaz
ejaz
--------------------------------------------------------------------------- TypeError Traceback (most recent call last)
<ipython-input-23-bc93814b0ea6> in <module>
12 x ="ejaz" 13 print_me(x)
---> 14 print_me() #Error as an arguments is reuried
TypeError: print_me() missing 1 required positional argument: ' str' 2. Keyword arguments
#2 . Keyword Arguments - Related to the function calls
#the keyword arguments identifies the caller arguments by
parameters name
# it allows us to skip arguments or their position order
becuse the interpreter
#uses KW to match the values with the arguments
Code:
def print_me(str): """This prints a passed String""" print(str)
return
print_me(str="Ejaz")
output:
Ejaz
3. Default arguments
# Defult Arguments: It is an arguments that aassumes a
dr=efult
#values if a value is not provided in the function call
Code:
def stud(name, age=20):
print(f'Name is :{name}')
print(f'Age is :{age}')
return
stud('rahil',18)
output:
Name is :rahil
Age is :18
4. Variable-length arguments
#Pass By Refrence
#All argument in python are pass by refernce only. #if we change anytime in the function, it is also reflected
outside
#in the calling function
def change(list1):
print (f"Before change in function {list1}")
list1[3] = 87
print (f"After change in function {list1}")
return
list2=[10,20,30,40,50,60]
print (f"Before change Outside function {list2}")
change(list2)
print (f"After change Outside function {list2}")
OUTPUT:
Before change Outside function [10, 20, 30, 40, 50, 60]
Before change in function [10, 20, 30, 40, 50, 60]
After change in function [10, 20, 30, 87, 50, 60]
After change Outside function [10, 20, 30, 87, 50, 60]
[PART I] PYTHON PROGRAMMING

4. Programs to use existing modules, packages and creating modules, packages


Modules enable you to split parts of program in different files
for easier maintenance and better performance. As a program
grows more in the size, it may be split it into several files for
easier maintenance as well as reusability of the code. The
solution to this is Modules. The most used functions can be defined in a module and then import it,
instead of copying their definitions into different programs. A module can be imported
by another program to make use of its functionality. This is how the Python standard library also works.
Simply put, a module is a file consisting of Python code. It can define functions, classes, and variables, and can also include
runnable code. Any Python file can be referenced as a module. A file containing Python code, for example: test.py, is called a
module, and its name would be test. The import statement
To use the functionality present in any module, you have to
import it into your current program. You need to use the import keyword along with the desired module name. When
interpreter comes across an import statement, it imports the
module to your current program. You can use the functions
inside a module by using a dot(.) operator along with the
module name. First, let's see how to use the standard library modules. In the example below, math module is imported into
the program so that you can use sqrt() function defined in it.
import math #You need to put this command,`import` keyword
along with the name of the module you want to import
Writing Modules
def add(x,y):
return (x+y) def sub(x,y):
return (x-y)
Here is an example to illustrate the use of from..import
from calculation import add
print(add(1,2))
from calculation import add,sub
from .. import * statement
You can import all attributes of a module using this statement. This will make all attributes of imported module visible in your
code. Here is an example to illustrate the use of from .. import *:
from calculation import *
print(add(1,2))
print(sub(3,2))
Renaming the imported module
import calculation as cal
print(cal.add(1,2))
Module Search Path
You may need your modules to be used in different
programs/projects and their physical location in the directory can be different. If you want to use a module residing in some
other directory, you have some options provided by Python. When you import a module named calculation, the interpreter
first searches for a built-in module with that name. If not found, it then searches for a file named calculation.py in a list of
directories given by the variable sys.path. sys.path contains these locations: • the directory containing the input script
(or the current directory). • PYTHONPATH (a list of directory names, with
the same syntax as the shell variable PATH). • the installation-dependent default. sys.path.append('/home/test/')
import calculation
print(calculation.add(1,2))
The dir() function
The dir() function is used to find out all the names defined in a
module. It returns a sorted list of strings containing the names defined in a module. import calculation
print(test.add(1,2))
print(dir(calculation))
Output: ['__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'add', 'sub']
In the output, you can see the names of the functions you defined in the module, add & sub. Attribute __name__ contains
the name of the module. All attributes beginning with an
underscore are default python attributes associated with a
module.
Packages in Python
A package is a hierarchical file directory structure that defines
a single Python application environment that consists of
modules and subpackages and sub subpackages, and so on. Consider a file Pots.py available in Phone directory.
This file has following line of source code-
#!/usr/bin/python
def Pots():
print "I'm Pots Phone" Similar way, we have another two files having different functions with the same name as above –
• Phone/Isdn.py file having function Isdn()
• Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory −
• Phone/__init__.py
To make all of your functions available when you've imported
Phone, you need to put explicit import statements in __init__.py as follows −
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these
classes available when you import the Phone package. #!/usr/bin/python
# Now import your Phone Package.
import Phone
Phone.Pots() Phone.Isdn() Phone.G3() When the above code is executed, it produces the
following result − I'm Pots Phone
I'm 3G Phone
I'm ISDN Phone
A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended.
Within a module, the module’s name (as a string) is available
as the value of the global variable __name__. For instance, use
your favorite text editor to create a file called fibo.py in the
current directory with the following contents:
# Fibonacci numbers module
def fib(n): # write Fibonacci series up to n
a, b = 0, 1
while a < n:
print(a, end=' ')
a, b = b, a+b
print()
def fib2(n): # return Fibonacci series up to n
result = []
a, b = 0, 1
while a < n:
result.append(a)
a, b = b, a+b
return result
A module can contain executable statements as well as
function definitions. These statements are intended to
initialize the module. They are executed only the first time the
module name is encountered in an import statement. (They are
also run if the file is executed as a script.)
Modules can import other modules. It is customary but not
required to place all import statements at the beginning of a
module (or script, for that matter). The imported module
names are placed in the importing module’s global symbol
table. There is a variant of the import statement that imports
names from a module directly into the importing module’s
symbol table. For example:
>>> from fibo import fib, fib2
>>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
This does not introduce the module name from which the
imports are taken in the local symbol table (so in the example, fibo is not defined).
There is even a variant to import all names that a
module defines: >>> from fibo import *
>>> fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
>>> import fibo as fib
>>> fib.fib(500) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
The Module Search Path
When a module named spam is imported, the interpreter first
searches for a built in module with that name. If not found, it
then searches for a file named spam.py in a list of directories
given by the variable sys.path. sys.path is initialized from these
locations:
• The directory containing the input script (or the current directory when no file is specified). •
PYTHONPATH (a list of directory names, with the same
syntax as the shell variable PATH).
• The installation-dependent default.
“Compiled” Python files
The variable sys.path is a list of strings that determines the
interpreter’s search path for modules. It is initialized to a default path taken from the environment variable
PYTHONPATH, or from a built-in default if PYTHONPATH is not
set. You can modify it using standard list operations:
>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')
The dir() Function
The built-in function dir() is used to find out which names a
module defines. It returns a sorted list of strings:
>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__',
'__excepthook__', '__interactivehook__', '__loader__',
'__name__', '__package__', '__spec__', '__stderr__', '__stdin__',
'__stdout__', '__unraisablehook__',
'_clear_type_cache', '_current_frames',
'_debugmallocstats', '_framework', '_getframe', '_git',
'_home', '_xoptions', 'abiflags', 'addaudithook',
'api_version', 'argv', 'audit', 'base_exec_prefix',
'base_prefix',
'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth',
'setdlopenflags', 'setprofile', 'setrecursionlimit',
'setswitchinterval', 'settrace', 'stderr', 'stdin', 'stdout',
'thread_info', 'unraisablehook', 'version', 'version_info',
'warnoptions']
Without arguments, dir() lists the names you have defined currently: >>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys'] Note that it lists all types of names: variables, modules, functions, etc.
dir() does not list the names of built-in functions
and variables. If you want a list of those, they are defined in the
standard module builtins:
>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError',
'BaseException',
'BlockingIOError', 'BrokenPipeError', 'BufferError',
'BytesWarning', 'ChildProcessError',
'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError',
'DeprecationWarning', 'EOFError', 'Ellipsis',
'EnvironmentError', 'Exception', 'False',
'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple',
'type', 'vars', 'zip']
Packages
Packages are a way of structuring Python’s module
namespace by using “dotted module names”. For example, the
module name A.B designates a submodule named B in a
package named A. Just like the use of modules saves the
authors of different modules from having to worry about each
other’s global variable names, the use of dotted module names
saves the authors of multi-module packages like NumPy or
Pillow from having to worry about each other’s module names. Suppose you want to design a collection of modules (a
“package”) for the uniform handling of sound files and sound
data. There are many different sound file formats (usually
recognized by their extension, for example: .wav, .aiff, .au), so
you may need to create and maintain a growing collection of
modules for the conversion between the various file formats. There are also many different operations you might want to
perform on sound data (such as mixing, adding echo, applying
an equalizer function, creating an artificial stereo effect), so in
addition you will be writing a never-ending stream of modules
to perform these operations. Here’s a possible structure for
your package (expressed in terms of a hierarchical
filesystem):
sound/ Top-level package
__init__.py Initialize the sound package
formats/ Subpackage for file format conversions
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
... effects/ Subpackage for sound effects
__init__.py
echo.py
surround.py
reverse.py
... filters/ Subpackage for filters
__init__.py
equalizer.py
vocoder.py
karaoke.py
Importing * From a Package
Now what happens when the user writes from sound.effects
import *? Ideally, one would hope that this somehow goes out
to the filesystem, finds which submodules are present in the
package, and imports them all. This could take a long time and
importing sub-modules might have unwanted side-effects that
should only happen when the sub-module is explicitly
imported. Packages in Multiple Directories
Packages support one more special attribute, __path__. This is
initialized to be a list containing the name of the directory
holding the package’s __init__.py before
the code in that file is executed. This variable can be modified;
doing so affects future searches for modules and
subpackages contained in the package.
[PART I] PYTHON PROGRAMMING

5. Programs for implementations of all object-oriented


concepts like class, method, inheritance,
polymorphism etc. (Real life examples must be
covered for the implementation of objectoriented concepts)
# Object and Class:
class employee():
def _init_(self,name,age,id,salary):
self.name = name
self.salary = salary
self.id = id
emp1 = employee("ejaz",22,1000,123400)
emp2 = employee("shaikh",23,2000,22340)
print(emp1._dict_)
Output:
{'name': ejaz, shaikh: 123400, 'id': 1000}
Code:
# Method:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Output:
Value inside function: 10
Value outside function: 20
Code:
# Multilevel Inheritance:
class employee():
def _init_(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
class childemployee1(employee):
def _init_(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
class childemployee2(childemployee1):
def _init_(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
emp1 = employee(ejaz,22,1000)
emp2 = childemployee1(sabir,23,2000)
print(emp1.age)
print(emp2.age)
Output:
22
23
Code:
# Compile-time Polymorphism:
class employee1():
def name(self):
print("ejaz is her name")
def salary(self):
print("3000 is her salary")
def age(self):
print("22 is her age")
class employee2():
def name(self):
print("Alvina is her name")
def salary(self):
print("4000 is her salary")
def age(self):
print("23 is her age")
def func(obj):
obj.name()
obj.salary()
obj.age()
obj_emp1 = employee1()
obj_emp2 = employee2()
func(obj_emp1)
func(obj_emp2)
Output:
ejaz is her name
3000 is her salary
22 is her age
sabir is her name
4000 is her salary
23 is her age
Code:
# Encapsulation:
class employee():
def _init_(self):
self.__maxearn = 1000000
def earn(self):
print("earning is:{}".format(self.__maxearn))
def setmaxearn(self,earn):
self.__maxearn = earn
emp1 = employee()
emp1.earn()
emp1.__maxearn = 10000
emp1.earn()
emp1.setmaxearn(10000)
emp1.earn()
Output:
earning is:1000000
earning is:1000000
earning is:10000
[PART I] PYTHON PROGRAMMING

6. Programs for parsing of data, validations like Password, email, URL, etc.
# To validate the password
def password_check(passwd):
SpecialSym =['$', '@', '#', '%']
val = True
if len(passwd) < 6:
print('length should be at least 6')
val = False
if len(passwd) > 20:
print('length should be not be greater than 8')
val = False
if not any(char.isdigit() for char in passwd):
print('Password should have at least one numeral')
val = False
if not any(char.isupper() for char in passwd):
print('Password should have at least one uppercase letter')
val = False
if not any(char.islower() for char in passwd):
print('Password should have at least one lowercase letter')
val = False
if not any(char in SpecialSym for char in passwd):
print('Password should have at least one of the symbols
$@#')
val = False
if val:
return val
def main():
passwd = 'Juvi@321' if (password_check(passwd)):
print("Password is valid")
else:
print("Invalid Password !!")
if _name_ == '_main_':
main()
Output:
Password is valid
Code:
# Email validation:
import re
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b' def check(email):
if(re.fullmatch(regex, email)):
print("Valid Email")
else:
print("Invalid Email")
if _name_ == '_main_':
email = "ejaz8837@gmail.com" check(email)
email = "my.ownsite@our-earth.org" check(email)
email = " ejaz8837@.com" check(email)
Output:
Valid Email
Valid Email
Invalid Email
Code:
#Validating URL
import re
s = 'https://www.aims.org/' obj1 = re.findall('(\w+)://', s)
print(obj1)
obj2 = re.findall('://www.([\w\-\.]+)', s)
print(obj2)
Output:
['https']
['aims.org']
[PART I] PYTHON PROGRAMMING

7. Programs for Pattern finding should be covered.


Programs to print number pattern
rows = 6
# if you want user to enter a number, uncomment the below
line
# rows = int(input('Enter the number of rows'))
# outer loop
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')
Output:
1
22
333
4444
55555
Equilateral triangle pattern of star
print("Print equilateral triangle Pyramid using asterisk symbol ")
# printing full Triangle pyramid using stars
size = 7
m = (2 * size) - 2
for i in range(0, size):
for j in range(0, m):
print(end=" ")
# decrementing m after each loop
m=m-1
for j in range(0, i + 1):
print("* ", end=' ')
print(" ")
output:
*
**
***
****
*****
******
*******
print alphabets and letters patterns in Python. # ASCII number of 'A' ascii_number = 65
rows = 7
for i in range(0, rows):
for j in range(0, i + 1):
character = chr(ascii_number)
print(character, end=' ')
ascii_number += 1
print(" ")
output:
A
BC
DEF
GHIJ
KLMNO
PQRSTU
VWXYZ[\
Pattern with a combination of numbers and stars
row = 4
for i in range(0, row):
c=1
print(c, end=' ')
for j in range(row - i - 1, 0, -1): output:
print('*', end=' ') 1*2*3*4
c=c+1 1*2*3
print(c, end=' ') 1*2
print('\n') 1
[PART I] PYTHON PROGRAMMING

8.Programs covering all the aspects of Exception


handling, user defined exception, Multithreading should be covered.
# Exception Handling
if there is an error, it raises an exception,This block of code
which rasises
an exception can be written in a "try:" block. After the try block, including an "exception :" block fllowed by a
code to
handle the problem
sytnax:
try:
namrmal operations
.................... except Exception1:
if there is eception1 then execute this code
except Exception2:
if there is exception2 then exceute this code
.... else:
if there is no exception then execute this code
finally :
always execute this code, irrespective of exception or not
A single try statements can have multiple statements .This ids
used when
a single try block may throw diffrent types of exceptions . we can have generic except clause to handle any type of
exception
The else clause can be execute a code when execption does
not occur
Example
#This statement will raise an exception
print(x)
Output:
NameError Traceback (most recent call last)
<ipython-input-11-159e3ab570bd> in <module>
1 #This statement will raise an exception
----> 2 print(x)
NameError: name 'x' is not defined
# Handling of this Exception
try:
print(x)
except NameError:
print('Please initilaize some data in x printing it')
Outrput:
Please initilaize some data in x printing it
# we can handle any error by using just except:
try:
print(x)
except :
print('Please initilaize some data in x printing it')
while True:
try:
x = int(input("enter a number"))
print(f'You enterd => {x}')
break
except ValueError :
print('Number re Pagal...Try Again!!!')
Output:
enter a numberw
Number re Pagal...Try Again!!!
enter a number#
Number re Pagal...Try Again!!!
enter a number'2' Number re Pagal...Try Again!!!
enter a number5
You enterd => 5
#Multipla Exception
try:
print(s) except :
except NameError: #This exception gets exceuted print('Kuch to gadhbad hai daya!!!')
print('Variable x is not defind ') Output:
Variable x is not defined.
[PART I] PYTHON PROGRAMMING

9.Programs demonstrating the IO operations like


reading from file, writing into file from different file
types like data file, binary file, etc.
python makes use of several functions for creating ,reading, updating and
deleting files
A file can be opend for operations using the open() method
The open() method takes two arguments : filename and mode
of file to be pend
There are 4 basic modes for opening a file
1. "r" - Read mode, defult value. it opens a files for reading and
giving an error
if the file is not present
2. "a" - Append : opens a file for writing. creates a new files if
the file does
not exits
3. "w" - create : creates a file. returns an error if the file not
present
A file can be handeled in binary or text mode. opening a file using "with " sttement :
it is the best way to open a file, we dont need to explicitly call the
close() method. it is internally when the block inside with is
excied
ir is also designed to prived much cleaner syntax and
eception handling. with open('abc.txt') as f:
f.read
import os
os.getcwd()
os.chdir('C:\\Users\\admin\\Desktop\\mod')
os.listdir()
Output:
['ang',
'MeraModule.py',
'MyCalculations',
'MyCalculations.py',
'mydir',
'test1',
'test101.txt',
'__pycache__']
with open('MyCalculations.py') as f:
print(f.read())
OutPut:
def add(a,b) :
return a+b
def sub(a,b) :
return a-b
def mod(a,b) :
return a%b
def mul(a,b) :
return a*b
def div(a,b) :
return a/b
we are learning file handling using pythonwe are learning file handling using pythonwe are learning file handling using python.
Program
with open('MyCalculations.py','a') as x:
x.write ("we are learning file handling using python")
with open('test101.txt') as f:
print ((f.read))
#tell
with open('test101.txt','r') as f:
print((f.tell))
with open('MyCalculations','w') as x:
print (f.tell())
f.seek(0)
print(f.tell())
print(f.read(10))
print(f.tell())
print(f.read(1))
print(f.tell())
[PART I] PYTHON PROGRAMMING

10.Programs to perform searching, adding, updating the content from the file.
Python program to create/adding binary file:
import pickle
list =[]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
file = open("student.dat","wb")
pickle.dump(list,file)
file.close()
output:
Enter student Roll No:51
Enter student Name :ejaz shaikh mushtaque
Want to add more record(y/n) :y
Enter student Roll No:52
Enter student Name :hussain shabbier pathrawala
Want to add more record(y/n) :y
Enter student Roll No:40
Enter student Name :Shaikh farhan
Want to add more record(y/n) :y
Want to add more record(y/n) :y
Enter student Roll No:56
Enter student Name :shaikh musaddique
Want to add more record(y/n) :n
Python program to update binary file:
import pickle
name = input('Enter name that you want to update in binary
file :')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
for x in list:
if name in x['name']:
found = 1
x['name'] = input('Enter new name ')
lst.append(x)
if(found == 1):
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('Name does not exist')
file.close()
output:
Enter name that you want to update in binary file :
Shaikh ejaz mushtaque
Enter new name farhan shaikh
Record Updated
Python program to Search binary file:
import pickle
name = input('Enter name that you want to search in binary file
:')
file = open("student.dat", "rb")
list = pickle.load(file)
file.close()
found = 0
for x in list:
if name in x['name']:
found = 1
print("Found in binary file" if found == 1 else "Not found")
Output:
Enter name that you want to search in binary file :
Shaikh ejaz mushtaque
Found in binary fil
[PART I] PYTHON PROGRAMMING

11.Program for performing CRUD operation with MongoDB and Python


Connecting to with Database with PyMongo:
1. To perform CRUD operations first need to establish the connection using Mongo client
>>> from pymongo import MongoClient
>>> client = MongoClient('localhost',27017) # 27017 is the default port number for mongodb
2. Next step is to connect to the database (test).
db = client.test
3. Now retrieve the collection (person) from the database
col = db.person
Now we are ready to perform the actual CRUD operations.
CRUD Operations:
C-Create:
Mongo store the data in the form of JSON objects. So every record for a collection in mongo is called a document. If the collection does not
insert_one()
insert_many()
insert()
1. insert_one(): insert_one() inserts a single document into a collection.
col.insert_one(
{
name: "John",
salary: 100 ,
}
)
The above snippet returns the pymongo.results.InsertOneResult object:
<pymongo.results.InsertOneResult object at 0x7f8fbe7fb960>
2. insert_many(): insert_many() inserts multiple documents into a collection.
The following example inserts three new documents into the users collection.
Each document has two fields name and salary. Since the documents do not specify an _id field, MongoDB adds the _id field with an Object
col.insert_many(
[
{ name: "Jeorge", salary: 100},
{ name: "Steve", salary: 100},
{ name: "David", salary: 100}
]
)
The method returns a pymongo.results.InsertManyResult object
<pymongo.results.InsertManyResult object at 0x7f8fbe7fb7d0>
3. insert(): insert() can be used to insert single or array or documents.
# single document
col.insert({ name: "Jeorge", salary: 100})
# array of documents
col.insert([{ name: "Jeorge", salary: 100}, { name: "Steve", salary: 100}])
insert() method returns all the Object ids of the documents that are inserted.
# return type of single document
ObjectId('57611d4b1aa303032ad5ba9e')
# return type of multiple documents
[ObjectId('57611d4b1aa303032ad5ba9e'), ObjectId('57611d4b1aa30303sdd5ba9e')]
R-Read:
We can retrieve the documents from a collection using 2 methods.
find()
find_one()
1. find(): find() function will return with all the documents in that collection. By default it returns a cursor object.
col.find()
<pymongo.cursor.Cursor object at 0x7f8fc1853890>
2. find_one(): find_one() returns the first document in the collection.
col.find_one()
{u'salary': 100, u'_id': ObjectId('57611a711aa303032ad5ba9b'), u'name': u'John'}
We can filter the results by applying conditions on these methods as following
col.find_one({"name": "John"}) # returns object.
col.find({"name": "John"}) # returns cursor
U- Update:
We can update the documents from the collection with the following methods.
update()
update_one()
update_many()
replace_one()
The general syntax for all the above methods is
<method_name>(condition, update_or_replace_document, upsert=False, bypass_document_validation=False)
Here
condition: A query that matches the document to replace.
update_or_replace_document: The new document.
upsert (optional): If True, perform an insert if no documents match the filter.
bypass_document_validation: (optional) If True, allows the right to opt-out of document-level validation.
Default is False.
Following are the snippets for update(), update_one(), update_many() and replace_one().
All the methods will return UpdateResult object except update().
# update_one
>>> col.update_one({"name":"John"}, {"$set":{"name":"Joseph"}})
<pymongo.results.UpdateResult object at 0x7f8fbe7fb910>
# update_many
>>> col.update_many({"name":"John"}, {"$set":{"name":"Joseph"}})
<pymongo.results.UpdateResult object at 0x7f8fbe7fb7d0>
# update
>>> col.update({"name":"John"}, {"$set":{"name":"Jeorge"}})
{'updatedExisting': False, u'nModified': 0, u'ok': 1, u'n': 0}
#replace_one
>>> col.replace_one({"name":"John"}, {"name":"Jeorge"})
<pymongo.results.UpdateResult object at 0x7f8fbe7fb910>
D- Delete:
We can delete the documents in the collection using the following methods.
delete_one()
delete_many()
Both these methods will return a DeleteResult object. The general syntax for the above methods is as follows.
<method_name>(condition)
Following are the examples how we use the delete_one() and delete_many() methods, both returns the DeleteResult object.
>>> col.delete_one({"name":"John"})
<pymongo.results.DeleteResult object at 0x7f8fbe7fba00>
>>> col.delete_many({"name":"John"})
<pymongo.results.DeleteResult object at 0x7f8fbe7fb960>
[PART I] PYTHON PROGRAMMING

12.Basic programs with NumPy as Array, Searching


and Sorting, date & time and String handling
# Searching & Sorting
import numpy as np
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = 0)
print ("Along first axis : \n", arr1)
a = np.array([[10, 15], [12, 1]])
arr2 = np.sort(a, axis = -1)
print ("\nAlong first axis : \n", arr2)
a = np.array([[12, 15], [10, 1]])
arr1 = np.sort(a, axis = None)
print ("\nAlong none axis : \n", arr1)
print("\n")
# Searching
b = np.array([12, 90, 380, 12, 211])
print(np.where(b>12))
print("\n")
c = np.array([[20, 24],[21, 23]])
print(np.where(c>20))
Output:
Along first axis :
[[10 1]
[12 15]]
Along first axis :
[[10 15]
[ 1 12]]
Along none axis :
[ 1 10 12 15]
(array([1, 2, 4]),)
(array([0, 1, 1]), array([1, 0, 1]))
Code:
# Date & time
import numpy as np
import time
import sys
# To display all the dates for the month of March, 2021. print("March, 2021")
print(np.arange('2021-03', '2021-04', dtype='datetime64[D]'))
print("\n")
# The time taken in order to find the sum of lists and sum of
numpy arrays both. SIZE = 1000000
L1= range(SIZE)
L2= range(SIZE)
A1= np.arange(SIZE)
A2=np.arange(SIZE)
start= time.time()
result=[(x,y) for x,y in zip(L1,L2)]
print((time.time()-start)*1000)
start=time.time()
result= A1+A2
print((time.time()-start)*1000)
Output:
March, 2021
['2021-03-01' '2021-03-02' '2021-03-03' '2021-03-04' '2021-03-05'
'2021-03-06' '2021-03-07' '2021-03-08' '2021-03-09' '2021-03-10'
'2021-03-11' '2021-03-12' '2021-03-13' '2021-03-14' '2021-03-15'
'2021-03-16' '2021-03-17' '2021-03-18' '2021-03-19' '2021-03-20'
'2021-03-21' '2021-03-22' '2021-03-23' '2021-03-24' '2021-03-25'
'2021-03-26' '2021-03-27' '2021-03-28' '2021-03-29' '2021-03-30'
'2021-03-31']
204.03599739074707
50.83727836608887
Code:
# String Handling
import numpy as np
# converting to lowercase
print(np.char.lower('EJAZ'))
# splitting a string
print(np.char.split('ejaz , mushtaque , shaikh ', sep = ','))
# joining a string
print(np.char.join(['-', ':'], ['ejaz', 'shaikh']))
# using greater() to check str1 is greater than str2
a=np.char.greater('ejaz','shaikh')
print(a)
# counting a substring
a=np.array(['ejaz', 'mushtaque', 'shaikh'])
print(np.char.count(a,'iy'))
# counting a substring
print(np.char.rfind(a,'mushtaque'))
# using equal() method
a=np.char.equal('ejaz','mushtaque')
print(a)
Output:
ejaz
['ejaz ', ' mushtaque ', ' shaikh ']
['e-j-a-z' 's:h:a:i:k:h']
False
[0 0 0]
[-1 0 -1]
False
[PART I] PYTHON PROGRAMMING

13. Programs for series and data frames should be covered.


Description:
The datastructure of pandas, series (1-D) AND dATAfRAME (2- D) handle vast amount of typical
use cases in finace, statistics, social science and other fields. Code :
import pandas as pd
#create a series
ages = pd.Series([22, 35, 58], name='Ages')
#A pandas series has no column lables, as it is usd a single
column of a DataFrame
#A series have row lable (index)
ages
Output:
0 22
1 35
2 58
Name: Ages, dtype: int64
df["Age"].max()
output:
58
#Series
ages.max()
58
#describe series
df.describe()
output:

The describe() provides a quick overview of all numerical data


in dataframe as name and sex column are textual columns, they were not considered by default. #Working with Titanic Dataset
Titanic =
pd.read_csv(r"C:\Users\admin\Desktop\DATA\titanic.csv")
#pandas provide the read_csv() method to read stored data in
csv format a pandas
#dataframe . pandas support diffrent files format or data
sources
Titanic
Output:

#Starting rows
Titanic.head()
# last rows()
Titanic.tail()

# How has pandas interpreted column datatypes


#we can chk
Titanic.dtypes
Output:
PassengerId int64
Survived int64
Pclass int64
Name object
Sex object
Age float64
SibSp int64
Parch int64
Ticket object
Fare float64
Cabin object
Embarked object
dtype: object
type(ages)
Output:
pandas.core.series.Series
#cheaking shape (daimentions) of dataframe
#chk diamentionss by using attributes
Titanic.shape
Output:
(891, 12)
#filter dataframe records
#eg : passenger having age greater than 35
Titanic[Titanic['Age']>35]
[PART I] PYTHON PROGRAMMING

14.Programs to demonstrate data pre-processing and data handling with data frame
Tips = pd.read_csv(r'C:\Users\admin\Desktop\DATA\tips.csv')
Tip

# select total bill, tips, smoker, time


Tips[['total_bill','tip','smoker','time']]
#Add a calculated colunm
Tips.assign(tip_rate=Tips["tip"]/Tips['total_bill']) #Filter data same as sql
Tips[Tips["total_bill"]>10]

#tips at dinner time more than 5


Tips[(Tips['time']=='Dinner') & (Tips['tip']>5.00)
[PART I] PYTHON PROGRAMMING

15.Program for data visualization should be covered.


MatplotLib for Data Visualization
MatplotLib is a graph plotting library for visualization. It is
written in python, C and javascript
# how to check matplotlib
import matplotlib
#how to check version of matplotlib
print(matplotlib.__version__)
Output:
3.3.4
import matplotlib.pyplot as plt
x = [0, 6]
y = [0, 260]
plt.plot(x,y)
plt.show()
Output:

#Marker size or ms
y =[2, 10, 7, 8, 6, 9]
plt.plot(y, marker='o', ms=20)
plt.show()
output:

# multiples lines in a ploat by using the ploat() function


multiple times
x1 = [0,1,2,3]
y1 =[2, 10, 7, 8]
x2 =[0,1,2,3]
y2 =[9,4,6,7]
plt.plot(x1,y1,x2,y2)
plt.show()
output:
[PART I] PYTHON PROGRAMMING

# Bar Charts
x = ['A', 'B', 'C', 'D']
y = [3, 8, 4, 10]
plt.bar(x,y, color='red')
plt.show()
output:

#pie chart
x =[35, 25, 25, 15]
l =['Sunday','Monday','Tuesday','Thursday']
e =[0.1,0,0,0]
plt.pie(x, labels =l, startangle=90, explode=e, shadow =True)
plt.show()
Output

You might also like