Final Lab Manual Python Dipesh
Final Lab Manual Python Dipesh
DSC-100
LAB MANUAL
Name : Dipesh Jha
System ID: 2023340540
Roll no. : 2302040076
Program : MBA
Semester : 3rd
Specialization : Finance & Business Analytics
INDEX OF EXPERIMENTS
Prerequisites
You should have a basic understanding of Computer Programming terminologies. A basic
understanding of any of the programming languages is a plus.
• Python is Interpreted − Python is processed at runtime by the interpreter. You do not need to
compile your program before executing it. This is similar to PERL and PHP.
• Python is Interactive − You can actually sit at a Python prompt and interact with the interpreter
directly to write your programs.
• Python is a Beginner's Language − Python is a great language for the beginner-level programmers
and supports the development of a wide range of applications from simple text processing to WWW
browsers to games.
History of Python
Python was developed by Guido van Rossum in the late eighties and early nineties at the National
Research Institute for Mathematics and Computer Science in the Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68,
SmallTalk, and Unix shell and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU General
Public License (GPL).
Python is now maintained by a core development team at the institute, although Guido van
Rossum still holds a vital role in directing its progress.
Page | 1
Python Features
Python's features include −
• Easy-to-learn − Python has few keywords, simple structure, and a clearly defined syntax. This allows
the student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and visible to the eyes.
• A broad standard library − Python's bulk of the library is very portable and cross-platform compatible
on UNIX, Windows, and Macintosh.
• Interactive Mode − Python has support for an interactive mode which allows interactive testing and
debugging of snippets of code.
• Portable − Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
• Extendable − You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more efficient.
• Databases − Python provides interfaces to all major commercial databases.
• GUI Programming − Python supports GUI applications that can be created and ported to many system
calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X Window system of
Unix.
• Scalable − Python provides a better structure and support for large programs than shell scripting.
Apart from the above-mentioned features, Python has a big list of good features, few are listedbelow −
• It supports functional and structured programming methods as well as OOP.
• It can be used as a scripting language or can be compiled to byte-code for building large applications.
• It provides very high-level dynamic data types and supports dynamic type checking.
• It supports automatic garbage collection.
• It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.
Page | 2
First Python Program:
Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.
A Python variable is a reserved memory location to store values. In other words, a variable in a python
program gives data to the computer for processing.
Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings,
Dictionary, etc. Variables can be declared by any name or even alphabets like a, aa, abc, etc.
Let see an example. We will declare variable "a" and print it.
a=100
print a
Python 1 Example
Page | 3
Python 2 Example
x = 123 # integer
x = "hello" # string
x = [0,1,2] # list
x = (0,1,2) # tuple
Constants
Non technically, you can think of constant as a bag to store some books and
those books cannotbe replaced once place inside the bag.
Page | 4
Assigning value to a constant in Python
In Python, constants are usually declared and assigned on a module. Here, the module means anew file
containing variables, functions etc which is imported to main file. Inside the module, constants are
written in all capital letters and underscores separating the words.
Create a constant.py
1. PI = 3.14
2. GRAVITY =
9.8
Create a main.py
1. import constant
2.
3. print(constant.PI)
4. print(constant.GRAVIT
Y)
When you run the program, the output will be:
3.14
9.8
Types of Operator
Python language supports the following types of operators.
• Arithmetic Operators
• Comparison (Relational) Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Let us have a look on all operators one by one.
Page | 5
Python Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then −
- Subtraction Subtracts right hand operand from left hand operand. a–b=
10
% Modulus Divides left hand operand by right hand operand and returns b%a=0
remainder
Page | 6
removed. But if one of the operands is negative, the result is 9.0//2.0
floored, i.e., rounded away from zero (towards negative = 4.0,
infinity) − 11//3 =
-4, -
11.0//3
= -4.0
<> If values of two operands are not equal, then condition becomes (a <> b) is
true. true. This
is similar
to
!=
operator.
> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.
Page | 7
< If the value of left operand is less than the value of right operand, (a < b)
then condition becomes true. istrue.
>= If the value of left operand is greater than or equal to the value of (a >= b)
right operand, then condition becomes true. isnot
true.
<= If the value of left operand is less than or equal to the value ofright (a <= b)
operand, then condition becomes true. istrue.
= Assigns values from right side operands to left side operand c=a+b
assigns
value of a
+ b into c
+= Add AND It adds right operand to the left operand and assign the c += a is
result to left operand equivalent
to c = c +
a
-= Subtract It subtracts right operand from the left operand and assign c -= a is
AND the result to left operand equivalent
to c = c - a
Page | 8
*= It multiplies right operand with the left operand and assignthe
Multiply result to left operand c *= a is
AND equivalent
to c = c * a
/= Divide AND It divides left operand with the right operand and assign the c /= a is
result to left operand equivalent
to c = c /
ac /= a is
equivalent
to c = c / a
//= Floor It performs floor division on operators and assign value tothe c //= a is
Division left operand equivalent
to c = c //
a
Page | 9
a&b = 0000 1100
= 0011 0001
~a = 1100 0011
& Binary AND Operator copies a bit to the result if it exists in both (a & b)
operands (means
0000 1100)
^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49
both. (means
0011 0001)
~ Binary Ones It is unary and has the effect of 'flipping' bits. (~a ) = -61
Complement (means 1100
0011
in 2's
complement
form due to
a signed
binary
number.
Page | 10
<< Binary Left Shift The left operands value is moved left by the numberof a << 2 = 240
bits specified by the right operand. (means
1111 0000)
>> Binary Right The left operands value is moved right by the a >> 2 = 15
Shift number of bits specified by the right operand. (means
0000 1111)
[ Show Example ]
Operator Descriptio Example
and If both the operands are true then condition becomes true. (a and
Logical b) is
AND true.
Page | 11
Operator Description Example
a 1 if x is a member
of sequencey.
not in Evaluates to true if it does not finds a variable in the specified x not in y,here not
sequence and false otherwise. in results in
a 1 if x is not a
member of
sequencey.
**
1 Exponentiation (raise to the power)
~+- Page | 12
2
Complement, unary plus and minus (method names for the last two are +@ and -
@)
<= < > >=
8
Comparison operators
<> == !=
9
Equality operators
= %= /= //= -= += *= **=
10
Assignment operators
Is, is not
11
Identity operators
In, not in
12
Membership operators
not, or, and
13 Logical operators
Page | 13
Assignment 2
Aim: To study strings in Python
Theory:
String Literals
String literals in python are surrounded by either single quotation marks, or double quotation marks.
is th'hello
e sa m' e as "hello".
Example
print("Hello") print('Hello')Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and the string:
Example
a = "Hello"print(a)
Multiline Strings
Like many other popular programming languages, strings in Python are arrays of bytes representingunicode
characters.
However, Python does not have a character data type, a single character is simply a string with a length
Page | 14
of 1. Square brackets can be used to access elements of the string.
Example
Get the character at position 1 (remember that the first character has the position 0):
Example
b = "Hello, World!"print(b[2:5])
Page | 15
Assignment: 3
Python programming language assumes any non-zero and non-null values as TRUE,
and if it iseither zero or null, then it is assumed as FALSE value.
Page | 16
Sr. No. Statement & Description
if statements
1
An if statement consists of a boolean expression followed by one or
morestatements.
if...else statements
2
An if statement can be followed by an optional else statement,
which executeswhen the boolean expression is FALSE.
nested if statements
3
You can use one if or else if statement inside another if or else
ifstatement(s).
Let us go through each decision making briefly −Single Statement Suites
If the suite of an if clause consists only of a single line, it may go on the same line as the
header
statement.
Page | 17
Assignment: 4
Aim: To study Loops in Python
Theory:
1 while loop
Repeats a statement or group of statements while a given condition is
TRUE. It teststhe condition before executing the loop body.
for loop
2
Executes a sequence of statements multiple times and abbreviates the
code thatmanages the loop variable.
nested loops
3
You can use one or more loop inside any another while, for or do..while
loop.
Page | 18
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution
leaves ascope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements. Click the following links to check their
detail.Let us go through the loop control statements briefly
1
break statement
2
continue statement
Causes the loop to skip the remainder of its body and immediately retest its
conditionprior to reiterating.
3 pass statement
The pass statement in Python is used when a statement is required
syntacticallybut youdo not want any command or code to execute.
Page | 19
Assignment 5
Aim: To study python arrays, list, tuples, set, dictionary
Theory: What is an Array?
An array is a special variable, which can hold more than one value at a time. If you have
a list ofitems (a list of car names, for example), storing the cars in single variables could
look like this:
However, what if you want to loop through the cars and find a specific one? And what if
you hadnot 3 cars, but 300?
An array can hold many values under a single name, and you can access the values by
referring toan index number.
x = cars[0]
Example
cars[0] = "Toyota"
x = len(cars)
Note: The length of an array is always one more than the highest array index.
Page | 20
Looping Array Elements
You can use the for in loop to loop through all the elements of an array.
Example
for x in cars:print(x)
cars.append("Honda")
You can use the pop() method to remove an element from the array.
Example
cars.pop(1)
You can also use the remove() method to remove an element from the array.
Example
cars.remove("Volvo")
Note: The remove() method only removes the first occurrence of the specified value.
Array Methods
Python has a set of built-in methods that you can use on lists/arrays.
Page | 21
Method Description
extend() Add the elements of a list (or any iterable), to the end
of the current list
Note: Python does not have built-in support for Arrays, but Python Lists can be used
instead
Python List:
The list is a most versatile datatype available in Python which can be written as a list of
comma separated values (items) between square brackets. Important thing about a list is
that items in a list need not be of the same type.
Creating a list is as simple as putting different comma-separated values between square
brackets.For example −
Note − append() method is discussed in subsequent section. When the above code is
executed, it produces the following result −
Value available at index 2 :
1997
New value available at index 2 :
2001
Delete List Elements
To remove a list element, you can use either the del statement if you know exactly which
element(s) you are deleting or the remove() method if you do not know. For example −
Page | 23
list1 = ['physics', 'chemistry', 1997, 2000]; print list1
Page | 24
Python Results Description
Expression
1
cmp(list1, list2)
2
len(list)
Gives the total length of the list.
3
max(list)
Returns item from the list with max value.
4
min(list)
Returns item from the list with min value.
5
list(seq)
Converts a tuple into list.
Page | 25
Python includes following list methods
1 list.append(obj)
list.count(obj)
2 Returns count of how many times obj occurs in list
list.extend(seq)
3 Appends the contents of seq to list
list.index(obj)
4 Returns the lowest index in list that obj appears
list.insert(index, obj)
5 Inserts object obj into list at offset index
list.pop(obj=list[-1])
6 Removes and returns last object or obj from list
list.remove(obj)
7 Removes object obj from list
list.reverse()
8 Reverses objects of list in place
list.sort([func])
9 Sorts objects of list, use compare func if given
Page | 26
Python Tuple:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
The differences between tuples and lists are, the tuples cannot be changed unlike lists and
tuples use parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you
can putthese comma-separated values between parentheses also. For example −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so
on.
Accessing Values in Tuples
To access values in tuple, use the square brackets for slicing along with the index or
indices toobtain value available at that index. For example −
Page | 27
tup1 = (12, 34.56); tup2
= ('abc', 'xyz');
tup3;
tup = ('physics', 'chemistry', 1997, 2000); print tup; del tup; print "After
This produces the following result. Note an exception raised, this is because after del tup
tupledoes not exist any more −
('physics', 'chemistry', 1997, 2000) After
deleting tup :
Traceback (most recent call last): File
"test.py", line 9, in <module> print
tup;
NameError: name 'tup' is not defined
Page | 28
Basic Tuples Operations
Tuples respond to the + and * operators much like strings; they mean concatenation
andrepetition here too, except that the result is a new tuple, not a string.
In fact, tuples respond to all of the general sequence operations we used on strings in the
priorchapter −
Page | 29
No Enclosing Delimiters
Any set of multiple objects, comma-separated, written without identifying symbols, i.e.,
brackets for lists, parentheses for tuples, etc., default to tuples, as indicated in these short
examples −
x,y;
cmp(tuple1, tuple2)
1
Compares elements of both tuples.
len(tuple)
2 Gives the total length of the tuple.
max(tuple)
3 Returns item from the tuple with max value.
min(tuple)
4 Returns item from the tuple with min value.
5
tuple(seq)
Converts a list into tuple.
Python Sets:
A set is a collection which is unordered and unindexed. In Python sets are written
with curlybrackets.
Page | 30
Example
Create a Set:
Note: Sets are unordered, so the items will appear in a random order.
Access Items
You cannot access items in a set by referring to an index, since sets are unordered the
items hasno index.
But you can loop through the loop, or ask if a specified
setitems using a f valueis present in a
r
set, by using thein keyword.
Example
for x in thisset:print(x)
Example
Change Items
Once a set is created, you cannot change its items, but you can add new items.
Add Items
To add more than one item to a set use the update() method.
Example
print(thisset)
Example
print(thisset)
Page | 32
Get the Length of a Set
To determine how many items a set has, use the len() method.
Example
Remove Item
Example
You can also use thepop(), method to remove an item, but this method will remove item
ts are unordered, so you will not know what item that gets last
removed
Note: If the item to remove does not exist, discard() will NOT raise an error.
Page | 33
The return value of the pop() method is the removed item.
Example
print(x) print(thisset)
thisset.clear()print(thisset)
Dictionary
Page | 34
Example
Accessing Items
You can access the items of a dictionary by referring to its key name, inside square
Example
brackets:
x = thisdict["model"]
There is also a method called get() that will give you the same result:
Example
x = thisdict.get("model")
Page | 35
Assignment:6
Aim: To study functions in python
Theory:
A function is a block of code which only runs when it is called. You can pass data,
known asparameters, into a function. A function can return data as a result.
Creating a Function
Example
Example
Parameters
Information can be passed to functions as parameter. Parameters are specified after the
function name, inside the parentheses. You can add as many parameters as you want, just
separate them with a comma. The following example has a function with one parameter
(fname). When the function is called, we pass along a first name, which is used inside the
function to print the full name:
Example
my_function("Emil") my_function("Tobias")
my_function("Linus") Default Parameter
Page | 36
Value
The following example shows how to use a default parameter value. If we call the
functionwithout parameter, it uses the default value:
Example
You can send any data types of parameter to a function (string, number, list, dictionary
etc.), and it will be treated as the same data type inside the function. E.g. if you send a List
as a parameter,it will still be a List when it reaches the function:
Example
Return Values
Example
def my_function(x):
return 5 * x
Page | 37
Python also accepts function recursion, which means a defined function can call itself.
Recursion is a common mathematical and programming concept. It means that a function
calls itself. This has the benefit of meaning that you can loop through data to reach a
result.
The developer should be very careful with recursion as it can be quite easy to slip into
writing a function which never terminates, or one that uses excess amounts of memory or
processor power. However, when written correctly recursion can be a very efficient and
mathematically elegant approach to programming.
In this example, tri_recursion() is a function that we have defined to call itself ("recurse").
We use the k variable as the data, which decrements-1) every time we recurse. The
recursion ends when
To a new developer it can take some time to work out how exactly this works, best way
to findout is by testing and modifying it.
Example
Recursion Example
def tri_recursion(k):
if(k>0):
result = k+tri_recursion(k-1)print(result)
else: result
=0
return result
Page | 38
Assignment:7
Aim: To study classes in python
Theory:
Python Classes/Objects
Almost everything in Python is an object, with its properties and methods.A Class is like
Create a Class
To create a class, use the keyword class:
Example
class MyClass:
x=5
Create Object
Now we can use the class named myClass to create objects:
Example
p1 = MyClass()print(p1.x)
The examples above are classes and objects in their simplest form, and are not really
useful inreal life applications.
Page | 39
Use the init () function to assign values to object properties, or other
operations that arenecessary to do when the object is being created:
Example
Create a class named Person, use the init () function to assign values for name and age:
class Person:
def init (self, name, age):self.name = name
self.age = age
X–X-X
Page | 40