M.C.
E Society
Allana Institute Management
Sciences
M.C.A
Class: FY MCA
Python Programming
Jabir Zakir Basri
Roll no: 14
Question_1: Python installation and configuration with
windows and Linux.
Program:
Description:
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 make process can require up to a minute — it
depends on the processing speed of your system.
13. Type sudo make altinstall 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.
Question_2: Program for understanding the data types, control
flow statements, blocks and loops.
Program: understanding the data types, control flow
statements, blocks and loops
Description:
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']]
3) Tuple
Just like list, tuple is also an ordered collection of Python
objects. The only difference between tuple and list is that
tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by tuple class.
Code:
# Python program to demonstrate
# creation of Set
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with
# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
OUTPUT
Initial empty Tuple:
()
Tuple with the use of String:
('Geeks', 'For')
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'))
2. Dictionaries
A dictionary is an unordered, changeable, and indexed
collection of elements. In Python, dictionaries are written with
curly brackets and contain keys and values. See the code below:
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Code', 2: 'With', 3: 'Harry'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Code', 2: 'With', 3:'Harry'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Code'), (2, 'With')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output: Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Code', 2: 'With', 3: 'Harry'}
Dictionary with the use of Mixed Keys:
{'Name': 'Geeks', 1: [1, 2, 3, 4]}
Dictionary with the use of dict():
{1: 'Code', 2: 'With', 3: 'Harry'}
Dictionary with each item as a pair:
{1: 'Code', 2: 'With'}
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.
Control Description
Statement
break Terminates the loop statement and transfers
execution
statement to the statement immediately following the
loop.
Causes the loop to skip the remainder of its
continue body and
Immediately retest its condition prior to
statement reiterating.
The pass statement in Python is used when a
pass
statement
statement
is required syntactically but you do not want
any
Command or code to execute.
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),
Loop Type Description
Repeats a statement or group of statements
while loop while a given
condition is TRUE. It tests the condition before
executing the
loop body.
Executes a sequence of statements multiple
for loop times and
abbreviates the code that manages the loop
variable.
You can use one or more loop inside any
nested loops 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)
Question_3: Programs for understanding functions, use of built
in functions, user defined function.
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]
Question_4: Program to use existing modules, Packages and
creating modules, Packages
Python 3 – Modules
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.
Question_5: Programs for implementations of all object-
oriented concepts like class, method, inheritance,
polymorphism etc. (Real life example must be covered for the
implementation of object oriented 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
Question_6: Programs for parsing of data, validations like
password, Email, URL, ect.
# 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 = "[email protected]"
check(email)
email = "[email protected]"
check(email)
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']
Question_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:
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):
print('*', end=' ')
c=c+1
print(c, end=' ')
print('\n')
output:
1*2*3*4
1*2*3
1*2
1
Question_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 NameError: #This exception gets exceuted
print('Variable x is not defind ')
except :
print('Kuch to gadhbad hai daya!!!')
Output:
Variable x is not defind
Question_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 ha
ndling 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())
Question_10: Programs to perform searching, adding,
updating the content 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 file
Question_11: Programs for performing CRUD operation with
MongoDB and Python.
Question_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
Question_13: Program 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]
Question_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')
Tips
# 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]
is_dinner = Tips['time'] =='Dinner'
is_dinner.value_counts()
Tips[is_dinner]
#tips at dinner time more than 5
Tips[(Tips['time']=='Dinner') & (Tips['tip']>5.00)]
Question_15: Programs 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:
# 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: