PythonSBL
PythonSBL
Date of Performance :
Date of Submission :
THEORY:
Python Keywords
Keywords are the reserved words in Python. We cannot use a keyword as a variable name, function
name or any other identifier. They are used to define the syntax and structure of the Python
language. In Python, keywords are case sensitive.
Keywords in Python
False Class finally Is return
None Continue for lambda try
True Def from nonlocal while
and Del global not with
as elif if or yield
assert else import pass
break except in raise
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate
one entity from another.
Rules for writing identifiers
1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0
to 9) or an underscore _. Names like myClass, var_1 and print_this_to_screen, all
are valid example.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is perfectly fine.
3. Keywords cannot be used as identifiers.
Python Comments
In Python, the hash (#) symbol to start writing a comment. It extends up to the newline character.
Comments are for programmers for better understanding of a program. Python Interpreter ignores
comment.
Multi-line comments
If we have comments that extend multiple lines, one way of doing it is to use hash (#) in the
beginning of each line. For example: Another way of doing this is to use triple quotes, either ''' or
""".
Python Variables
A variable is a named location used to store data in the memory. It is helpful to think of variables
as a container that holds data which can be changed later throughout programming.
Rules and Naming Convention for Variables and constants
1. Constant and variable names should have a combination of letters in lowercase (a to z) or uppercase
(A to Z) or digits (0 to 9) or an underscore (_). For example:
2. snake_case
3. MACRO_CASE
4. camelCase
5. CapWords
Type Conversion:
The process of converting the value of one data type (integer, string, float, etc.) to another data type
is called type conversion. Python has two types of type conversion.
1. Implicit Type Conversion
2. Explicit Type Conversion
Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value
that the operator operates on is called the operand.
Arithmetic operators
Logical operators
Membership operators
a) Write a python program to input student details and display welcome message to newly added
student record.
INPUT:
print("\nWELCOME,",name+"!!")
OUTPUT:
b) Write a python Program to perform arithmetic operations on any given inputs
INPUT:
OUTPUT:
c) Write a python Program for Password Length Checker.
INPUT:
if (len(user_input)<8 or len(user_input)>12):
print("Not valid ! Total characters should be between 8 and 12 !")
else:
print("Password is valid !")
print("Length of Password :",len(user_input))
OUTPUT:
Date of Submission :
AIM: To study methods of python data types like string, list, dictionary, tuple and set
THEORY:
Data types:
The data stored in memory can be of many types. For example, a person's age is stored as a numeric
value and his or her address is stored as alphanumeric characters. Python has various standard data types
that are used to define the operations possible on them and the storage method for each of them.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:
Numbers
Number data types store numeric values. Number objects are created when you assign a value to them.
Strings
Strings in Python are identified as a contiguous set of characters represented in the quotation marks
String Methods
Python has a set of built-in methods that you can use on strings.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and returns the position of where
find()
it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
Searches the string for a specified value and returns the position of where
index()
it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
Searches the string for a specified value and returns the last position of
rfind()
where it was found
Searches the string for a specified value and returns the last position of
rindex()
where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.
List Methods
Method Description
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
Tuple
A tuple is a collection which is ordered and unchangeable
Tuple Methods
Method Description
Searches the tuple for a specified value and returns the position of where
index()
it was found
Set
A set is a collection which is unordered and unindexed.
Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference between two or more sets
Removes the items in this set that are also included in another, specified
difference_update()
set
discard() Remove the specified item
intersection() Returns a set, that is the intersection of two other sets
Removes the items in this set that are not present in other, specified
intersection_update()
set(s)
isdisjoint() Returns whether two sets have a intersection or not
issubset() Returns whether another set contains this set or not
issuperset() Returns whether this set contains another set or not
pop() Removes an element from the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric differences of two sets
symmetric_difference_update() inserts the symmetric differences from this set and another
union() Return a set containing the union of sets
update() Update the set with the union of this set and others
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.
Method Description
items() Returns a list containing a tuple for each key value pair
Returns the value of the specified key. If the key does not exist: insert the key,
setdefault()
with the specified value
print("Menu Driven Python Program to study various methods associated to datatypes string, list,
dictionary, set and tuple !!\n")
def m_tuples():
print("Tuples :")
t = (1, 2, 3, 4, 4, 5, 12, 1, 87, 88, 3)
t.count(1)
print("First", t[0])
print("First 4 : ", t[:4])
print("\n")
def m_list():
print("List :")
l = []
l.append(20)
l.append(9)
l.append(2000)
print("First : ", l[0])
print("Excluding First : ", l[1:])
l.remove(9)
l.pop()
l.extend([416602,550])
print("\n")
pass
def m_strings():
print("Strings :")
str = input("Enter Any String : ")
print(str.count("n"))
print(str.upper())
print(str.split(" "))
print(str.capitalize())
print("\n")
pass
def m_dictionary():
print("Dictionary :")
n=5
numbers = {}
for i in range(1, n + 1):
numbers[i] = i * i
print(numbers)
print("\n")
def m_set():
print("Set :")
my_set = {1, 3}
print(my_set)
my_set.add(2)
print(my_set)
my_set.update([2, 3, 4])
print(my_set)
my_set.update([4, 5], {1, 6, 8})
print(my_set)
print("\n")
m_strings()
m_tuples()
m_list()
m_dictionary()
m_set()
OUTPUT:
Date of Submission :
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome.
You need to determine which action to take and which statements to execute if outcome is
TRUE or FALSE otherwise.
1 if statements
2 if...else statements
An if statement can be followed by an optional else statement, which executes when the
boolean expression is FALSE.
3 nested if statements
You can use one if or else if statement inside another if or else ifstatement(s).
A loop statement allows us to execute a statement or group of statements multiple times.
1 while loop Repeats a statement or group of statements while a given condition is TRUE.
It tests the condition before executing the loop body.
2 for loop
Executes a sequence of statements multiple times and abbreviates the code that manages
the loop variable.
3 nested loops
You can use one or more loop inside any another while, for or do..while loop.
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
Python supports the following control statements.
1 break statement
Terminates the loop statement and transfers execution to the statement immediately following the
loop.
2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition prior to
reiterating.
3 pass statement
The pass statement in Python is used when a statement is required syntactically but you do not want
any command or code to execute.
PROGRAMS
A) Write a python program that finds the Fibonacci series from 0 to 20.
INPUT:
OUTPUT:
B) Write a python program that finds duplicates from the list [`a`,`b`,’c`,`a`,`a`,`b`,`d`].
INPUT:
my_list=sorted(given_list)
duplicates=[]
for d in my_list:
if my_list.count(d)>1:
if d not in duplicates:
duplicates.append(d)
print("Given List : ",given_list)
print("Duplicate Elements in List : ",duplicates)
OUTPUT:
C) Write a python program that reads alphabet and print desired output.
Alpahbet = [
[1,0,0,0,0,0,1],
[1,0,0,0,0,0,1],
[1,1,1,1,1,1,1],
[1,0,0,0,0,0,1],
[1,0,0,0,0,0,1]]
Output
* *
* *
*******
* *
* *
INPUT:
OUTPUT:
Date of Submission :
THEORY:
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.
Python gives you many built- in functions like print(), etc. but you can also create your own
functions. These functions are called user- defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string
of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
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 def printme( str ):
"This prints a passed string into this function"
print str
return
Calling a Function
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 the example to call printme()
def printme( str ):
"This prints a passed string into this function" print str
return;
# Now you can call printme function printme("I'm first call to user defined function!")
printme("Again second call to the same function")
a) Write a python program that accepts two strings as input and find the string with max length.
INPUT:
print("Python program that accepts two strings as input and find the string with max length!\n")
def printVal(s1,s2):
len1 = len(s1)
len2 = len(s2)
if len1 > len2:
print("String with max length is : ",s1)
elif len1 < len2:
print("String with max length is : ",s2)
else:
print("Both Strings have same Length!")
OUTPUT:
b) Write a python program to print dictionary where keys are no’s between 1 and 20(both included)
& values are square of keys.
INPUT:
print("Python program to print dictionary where keys are no's between 1 and 20(both included) &
values are square of keys!\n")
def printDict():
d=dict()
for i in range(1,21):
d[i]=i**2
print(d)
printDict()
OUTPUT:
c) Write a python program to implement Object Oriented Programming concept like Classes,
encapsulation, inheritance and multiple inheritance.
print("Python program to implement Object Oriented Programming concept like Creating Class
and Object!\n")
class Parrot:
# class attribute
species = "bird"
# instance attribute
def __init__(self, name, age):
self.name = name
self.age = age
CONCEPT : METHODS
INPUT:
print("Python program to implement Object Oriented Programming concept like Creating Methods!\n")
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
OUTPUT:
CONCEPT : INHERITANCE
INPUT:
def __init__(self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def __init__(self):
# call super() function
super().__init__()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin()
peggy.whoisThis()
peggy.swim()
peggy.run()
OUTPUT:
CONCEPT : DATA ENCAPSULATION
INPUT:
print("Python program to implement Object Oriented Programming concept like Data Encapsulation!\n")
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
c = Computer()
c.sell()
OUTPUT:
CONCEPT : POLYMORPHISM
INPUT:
class Parrot:
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
OUTPUT:
CONCEPT : MULTIPLE INHERITANCE
INPUT:
print("Python program to implement Multiple Inheritance!\n")
class marks:
def getdata1(self):
self.pt1 = int (input ("Enter IA1 Marks : "))
self.pt2 = int (input ("Enter IA2 Marks : "))
def display1(self):
print ("IA 1 : ", self.pt1)
print ("IA 2 : ", self.pt2)
class microproject :
def getdata2(self):
self.m = int (input ("Enter Microproject Marks : "))
def display2(self):
print("Microproject : ", self.m)
class student (marks, microproject):
def display3(self):
total = self.pt1 + self.pt2 + self.m
print("Total : ", total)
s1 = student()
s1.getdata1()
s1.getdata2()
s1.display1()
s1.display2()
s1.display3()
OUTPUT:
Date of Submission :
THEORY:
File handling
When working with Python, no need to import a library in order to read and write files.
It’s handled natively in the language.
file_name − The file_name argument is a string value that contains the name of the file
that you want to access.
access_mode − The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given below
in the table. This is optional parameter and the default file access mode is read (r).
buffering − If the buffering value is set to 0, no buffering takes place. If the buffering
value is 1, line buffering is performed while accessing a file. If you specify the
buffering value as an integer greater
than 1, then buffering action is performed with the indicated buffer size. If negative, the buffer size
is the system default(default behavior).
list of the different modes of opening a file −
Sr.No. Modes &
Description
1
r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is
the default mode.
2
rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of
the file. This is the default mode.
3
r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
4
rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the
beginning of the file.
5
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist,
creates a new file for writing.
6
wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file
does not
exist, creates a new file for writing.
7
w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.
8
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.
9
a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the
file is in the append mode. If the file does not exist, it creates a new file for writing.
10
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.
11
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for
reading and writing.
12
ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of
the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a
new file for reading and writing.
The file Object Attributes
Once a file is opened and you have one file object, you can get various information
related to that file. Here is a list of all attributes related to file object −
fileObject.close();
Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would
see how to use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings
can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings
can have binary data. apart from text data.
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as much
as possible, maybe until the end of file.
File Positions
The tell() method tells you the current position within the file; in other words, the next read or
write will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offsetargument indicates
the number of bytes to be moved. The from argument specifies the reference position from
where the bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means
use the current position as the reference position and if it is set to 2 then the end of the file
would be taken as the reference position.
Renaming and
Deleting Files
The rename()
Method
The rename() method takes two arguments, the current filename and
os.rename(current_file_name, new_file_name)
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted
as the argument.
Syntax
os.remove(file_name)
Directories in Python
All files are contained within various directories, and Python has no problem
handling these too. The os module has several methods that help you create, remove, and
change directories.
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the current directory.
You need to supply an argument to this method which contains the name of the directory to be
created.
Syntax
os.mkdir("newdir")
The chdir() Method
You can use the chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory.
Syntax
os.chdir("newdir")
The getcwd() Method
The getcwd() method displays the current
it should be removed.
Syntax
os.rmdir('dirname')
Example
File & Directory Related Methods
There are three important sources, which provide a wide range of utility methods to handle and
manipulate files & directories on Windows and Unix operating systems. They are as follows
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
PROGRAM
1. Python program to append data to existing file and then display the entire file
INPUT:
print("Python program to append data to existing file and then display the entire file!\n")
# append
file_a = open("AkshayPython.txt", "a")
file_a.write("\n")
file_a.write("Python program to append data to existing file succeeded!")
OUTPUT:
2. Python program to count number of lines, words and characters in a file.
INPUT:
number_lines = 0
number_words = 0
number_characters = 0
for line in file_a:
line = line.strip("\n")
#Won't count \n as character
words = line.split()
number_lines += 1
number_words += len(words)
number_characters += len(line)
file_a.close()
OUTPUT:
3. Python program to display file available in current directory
INPUT:
OUTPUT:
Date of Submission :
THEORY:
Python modules and Python packages, two mechanisms that facilitate modular programming.
Modular programming refers to the process of breaking a large, unwieldy programming task into
separate, smaller, more manageable subtasks or modules. Individual modules can then be cobbled
together like building blocks to create a larger application.
Python Modules
A module’s contents are accessed the same way in all three cases: with the import statement.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Use a Module
Now we can use the module we just created, by using the import statement:
Example
Import the module named mymodule, and call the greeting function:
import mymodule
mymodule.greeting("Jonathan")
Built-in Modules
There are several built-in modules in Python, which you can import whenever you like.
Example
Import and use the platform module:
import platform
x = platform.system()
print(x)
Using the dir() Function
There is a built-in function to list all the function names (or variable names) in a module. The dir()
function:
Example
List all the defined names belonging to the platform module:
import platform
x = dir(platform)
print(x)
Note: The dir() function can be used on all modules, also the ones you create yourself.
Import From Module
You can choose to import only parts from a module, by using the from keyword.
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Example
Import only the person1 dictionary from the module:
from mymodule import person1
print (person1["age"])
PROGRAMS
INPUT:
import smtplib
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('cm.a.70.pushkaraj.chaudhary@gmail.com', '*********')
server.sendmail(froma, to, msg.as_string())
print("Your Mail was sent Successfully !!!")
server.quit()
OUTPUT:
CONCLUSION: Program executed successfully.
EXPERIMENT NO: 07
Date of Performance :
Date of Submission :
THEORY:
The NumPy library is a popular Python library used for scientific computing applications, and is an
acronym for "Numerical Python". NumPy's operations are divided into three main categories: Fourier
Transform and Shape Manipulation, Mathematical and Logical Operations, and Linear Algebra and
Random Number Generation. To make it as fast as possible, NumPy is written in C and Python.
import numpy as np
nums = np.array([2, 3, 4, 5, 6])
nums2 = nums + 2
To install the NumPy package, you can use the pip installer. Execute the following command to install:
$ pip install numpy
Otherwise, if you are running Python via the Anaconda distribution, you can execute the following
command instead:
$ conda install numpy
NumPy arrays are the building blocks of most of the NumPy operations. The NumPy arrays can be
divided into two types: One-dimensional arrays and Two-Dimensional arrays.
In the script above we first imported the NumPy library as np, and created a list x.
To create a two-dimensional array, you can pass a list of lists to the array method as shown below:
nums = np.array([[2,4,6], [8,10,12], [14,16,18]])
The above script results in a matrix where every inner list in the outer list becomes a row. The number
of columns is equal to the number of elements in each inner list. The output matrix will look like this:
array([[ 2, 4, 6],
[ 8, 10, 12],
[14, 16, 18]])
nums = np.arange(2, 7)
array([2, 3, 4, 5, 6])
nums = np.arange(2, 7, 2)
array([2, 4, 6])
zeros = np.zeros(5)
The above script will return a one-dimensional array of 5 zeros. Print the zeros array and you should see
the following:
array([0., 0., 0., 0., 0.])
Similarly, to create a two-dimensional array, you can pass both the number of rows and columns to the
zeros method, as shown below:
zeros = np.zeros((5, 4))
The above script will return a two-dimensional array of 5 rows and 4 columns:
array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
And again, for the two-dimensional array, try out the following code:
OUTPUT:
OUTPUT:
4. Create an array of 10 fives
INPUT:
OUTPUT:
OUTPUT:
print("Python program to create array of all the even integers from 10 to 50!\n")
import numpy as np
array=np.arange(10,51,2)
print("Array of all the even integers from 10 to 50 :\n")
print(array)
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
10. Use Numpy to generate an array of 25 random numbers sampled from standard normal
distribution
INPUT:
print("Python program to generate an array of 25 random numbers sampled from standard
normal distribution!\n")
import numpy as np
rand_num = np.random.normal(0,1,25)
print("25 random numbers from a standard normal distribution : ")
print(rand_num)
OUTPUT:
OUTPUT:
13. Create an 2D array with 3 rows and 4 columns values starting from 12 to 25
INPUT:
print("Python program to create an 2D array with 3 rows and 4 columns values starting from 12
to 25!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
OUTPUT:
OUTPUT:
OUTPUT:
OUTPUT:
Date of Performance :
Date of Submission :
THEORY:
Series is a one-dimensional labeled array capable of holding data of any type (integer, string, float,
python objects, etc.). The axis labels are collectively called index.
pandas.Series
Array
Dict
Scalar value or constant
Create an Empty Series
If data is an ndarray, then index passed must be of the same length. If no index is passed, then by default
index will be range(n) where n is array length, i.e., [0,1,2,3…. range(len(array))-1].
Example
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data)
print s
We did not pass any index, so by default, it assigned the indexes ranging from 0 to len(data)-1, i.e., 0 to
3.
Example
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = np.array(['a','b','c','d'])
s = pd.Series(data,index=[100,101,102,103])
print s
We passed the index values here. Now we can see the customized indexed values in the output.
Create a Series from dict
A dict can be passed as input and if no index is specified, then the dictionary keys are taken in a sorted
order to construct index. If index is passed, the values in data corresponding to the labels in the index
will be pulled out.
Example
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data)
print s
Example
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
data = {'a' : 0., 'b' : 1., 'c' : 2.}
s = pd.Series(data,index=['b','c','d','a'])
print s
Observe − Index order is persisted and the missing element is filled with NaN (Not a Number).
If data is a scalar value, an index must be provided. The value will be repeated to match the length of
index
#import the pandas library and aliasing as pd
import pandas as pd
import numpy as np
s = pd.Series(5, index=[0, 1, 2, 3])
print s
Retrieve the first element. As we already know, the counting starts from zero for the array, which means
the first element is stored at zeroth position and so on.
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
Retrieve the first three elements in the Series. If a : is inserted in front of it, all items from that index
onwards will be extracted. If two parameters (with : between them) is used, items between the two
indexes (not including the stop index)
import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])
A Series is like a fixed-size dict in that you can get and set values by index label.
Example
OUTPUT:
OUTPUT:
OUTPUT:
[7] Get the minimum, 25th percentile, median, 75th, and max of a numeric series
INPUT:
print("Python program to Get the minimum, 25th percentile, median, 75th, and max of a numeric
series!\n")
import pandas as pd
import numpy as np
num_state = np.random.RandomState(100)
num_series = pd.Series(num_state.normal(10, 4, 20))
print("Original Series:")
print(num_series)
result = np.percentile(num_series, q=[0, 25, 50, 75, 100])
print("\nMinimum, 25th percentile, median, 75th, and maximum of a given series:")
print(result)
OUTPUT:
[8] Explore various useful methods of Data series
INPUT:
OUTPUT:
Date of Submission :
THEORY:
A Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and
columns.
Features of DataFrame
Potentially columns are of different types
Size – Mutable
Labeled axes (rows and columns)
Can Perform Arithmetic operations on rows and columns
Structure
Let us assume that we are creating a data frame with student’s data.
#With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print df1
print df2
Its output is as follows −
#df1 output
a b
first 1 2
second 5 10
#df2 output
a b1
first 1 NaN
second 5 NaN
Note − Observe, df2 DataFrame is created with a column index other than the dictionary key; thus,
appended the NaN’s in place. Whereas, df1 is created with column indices same as dictionary keys, so
NaN’s appended.
Create a DataFrame from Dict of Series
Dictionary of Series can be passed to form a DataFrame. The resultant index is the union of all the series
indexes passed.
Example
import pandas as pd
df = pd.DataFrame(d)
print df
Its output is as follows −
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
Note − Observe, for the series one, there is no label ‘d’ passed, but in the result, for the d label, NaN is
appended with NaN.
Let us now understand column selection, addition, and deletion through examples.
Column Selection
We will understand this by selecting a column from the DataFrame.
Example
import pandas as pd
df = pd.DataFrame(d)
print df ['one']
Its output is as follows −
a 1.0
b 2.0
c 3.0
d NaN
Name: one, dtype: float64
Column Addition
We will understand this by adding a new column to an existing data frame.
Example
import pandas as pd
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(d)
# Adding a new column to an existing DataFrame object with column label by passing
new series
print df
Its output is as follows −
Adding a new column by passing as Series:
one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
df = pd.DataFrame(d)
print ("Our dataframe is:")
print df
df = pd.DataFrame(d)
print df.loc['b']
Its output is as follows −
one 2.0
two 2.0
Name: b, dtype: float64
The result is a series with labels as column names of the DataFrame. And, the Name of the series is the
label with which it is retrieved.
Selection by integer location
Rows can be selected by passing integer location to an iloc function.
import pandas as pd
df = pd.DataFrame(d)
print df.iloc[2]
Its output is as follows −
one 3.0
two 3.0
Name: c, dtype: float64
Slice Rows
Multiple rows can be selected using ‘ : ’ operator.
import pandas as pd
df = pd.DataFrame(d)
print df[2:4]
Its output is as follows −
one two
c 3.0 3
d NaN 4
Addition of Rows
Add new rows to a DataFrame using the append function. This function will append the rows at the end.
import pandas as pd
df = df.append(df2)
print df
Its output is as follows −
a b
0 1 2
1 3 4
0 5 6
1 7 8
Deletion of Rows
Use index label to delete or drop rows from a DataFrame. If label is duplicated, then multiple rows will
be dropped.
If you observe, in the above example, the labels are duplicate. Let us drop a label and will see how many
rows will get dropped.
import pandas as pd
df = df.append(df2)
print df
Its output is as follows −
a b
1 3 4
1 7 8
PROGRAMS
1. Import Pandas Library
INPUT:
3. Display dataframe
INPUT:
OUTPUT:
4. Display total_bill & tips Column
INPUT:
OUTPUT:
OUTPUT:
6. Create a new column having tip percent
INPUT:
OUTPUT:
OUTPUT:
OUTPUT:
11. Find records where total_bill is more than $40 and Day is ‘Sun’
INPUT:
print("Python program to find records where total_bill is more than $40 and Day is ‘Sun’!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.loc[(df['total_bill'] > 40) & (df['day']=="Sun")])
OUTPUT:
OUTPUT:
02.INPUT:
print("Python program to apply useful methods on df!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.groupby(by='sex')['total_bill'].max())
02.OUTPUT:
03.INPUT:
print("Python program to apply useful methods on df!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.describe())
03.OUTPUT:
04.INPUT:
print("Python program to apply useful methods on df!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.sort_values(by='tip',ascending=False))
04.OUTPUT:
Date of Performance :
Date of Submission :
AIM: Menu driven program for data structure using built in function for link list,
stack and queues.
THEORY:
A list is a data structure in Python that is a mutable, or changeable, ordered sequence of
elements. Each element or value that is inside of a list is called an item. Just as strings are
defined as characters between quotes, lists are defined by having values between square brackets
[ ]. Lists are great to use when you want to work with many related values. They enable you to
keep data together that belongs together, condense your code, and perform the same methods and
operations on multiple values at once.
The list data type has some more methods. Here are all of the
The list methods make it very easy to use a list as a stack, where the last element added is the
first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append().
To retrieve an item from the top of the stack, use pop() without an explicit index.
It is also possible to use a list as a queue, where the first element added is the first element
retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends
and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow
(because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque which was designed to have fast appends and pops
from both ends.
PROGRAMS
Menu driven program for data structure using built in function for link list, stack and queue.
INPUT:
print("Python Menu driven program for data structure using built in function for link list, stack and
queue!\n")
def enqueue(data):
queue.insert(0,data)
def dequeue():
if len(queue)>0:
return queue.pop()
return ("Queue Empty!")
def display():
print("Elements on queue are:");
for i in range(len(queue)):
print(queue[i])
def isEmpty(stk): # checks whether the stack is empty or not
if stk==[]:
return True
else:
return False
def Pop(stk):
if isEmpty(stk): # verifies whether the stack is empty or not
print("Underflow")
else: # Allow deletions from the stack
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)
print("Popped item is "+str(item))
def Display(stk):
if isEmpty(stk):
print("Stack is empty")
else:
top=len(stk)-1
print("Elements in the stack are: ")
for i in range(top,-1,-1):
print (str(stk[i]))
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def insert(self, data):
newNode = Node(data)
if (self.head):
current = self.head
while (current.next):
current = current.next
current.next = newNode
else:
self.head = newNode
def printLL(self):
current = self.head
while (current):
print(current.data)
current = current.next
if __name__=="__main__":
print("Queue is as follows:")
queue=[]
enqueue(1)
enqueue(2)
enqueue(3)
enqueue(4)
enqueue(5)
print("Popped Element is: "+str(dequeue()))
display()
print()
print("Stack is as follows:")
stk = []
top = None
Push(stk, 10)
Push(stk, 20)
Push(stk, 30)
Push(stk, 40)
Pop(stk)
Display(stk)
print ( )
print ( "List is as follows:" )
LL = LinkedList()
LL.insert ( 23 )
LL.insert ( 46 )
LL.insert ( 57 )
LL.printLL ( )
OUTPUT: