Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

PythonSBL

The document outlines experiments focused on Python programming, specifically studying input/output methods, operators, and data types including strings, lists, dictionaries, tuples, and sets. It includes theoretical explanations, rules for identifiers and variables, type conversion, and examples of programs demonstrating these concepts. The conclusion of each experiment emphasizes the understanding gained in the respective areas of Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

PythonSBL

The document outlines experiments focused on Python programming, specifically studying input/output methods, operators, and data types including strings, lists, dictionaries, tuples, and sets. It includes theoretical explanations, rules for identifiers and variables, type conversion, and examples of programs demonstrating these concepts. The conclusion of each experiment emphasizes the understanding gained in the respective areas of Python programming.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 86

EXPERIMENT NO: 01

Date of Performance :

Date of Submission :

AIM: To study basics of input/output methods and operators in python.

SOFTWARE REQUIREMENT: Python

THEORY:

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is


designed to be highly readable. It uses English keywords frequently where as other languages
use punctuation, and it has fewer syntactical constructions than other languages.

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

Implicit Type Conversion:


In Implicit type conversion, Python automatically converts one data type to another data type. This
process doesn't need any user involvement.

Explicit Type Conversion:


In Explicit Type Conversion, users convert the data type of an object to required data type.
Functions like int(), float(), str(), etc to perform explicit type conversion.This type conversion
is also called typecasting because the user casts (change) the data type of the objects.
Syntax :
(required_datatype)(expression)
Python Input, Output
Python provides numerous built-in functions that are readily available at the Python prompt.Some
of the functions like input() and print() are widely used for standard input and output operations
respectively.
the print() function to output data to the standard output device (screen).
To allow flexibility to take the input from the user. In Python, we have the input() function

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

Arithmetic operators in Python


Operator Meaning Example
x + y
+ Add two operands or unary plus
+2
x - y
- Subtract right operand from the left or unary minus
-2
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)
Floor division - division that results into whole number adjusted to
// x // y
the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)

Logical operators

Logical operators in Python


Operator Meaning Example
And True if both the operands are true x and y
Or True if either of the operands is true x or y
Not True if operand is false (complements the operand) not x
Comparison Operators

Comparison operators in Python


Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater than
>= x >= y
or equal to the right
Less than or equal to - True if left operand is less than or
<= x <= y
equal to the right

Membership operators

Operator Meaning Example


In True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x
PROGRAMS

a) Write a python program to input student details and display welcome message to newly added
student record.

INPUT:

print("NEW STUDENT REGISTRATION !\n")


name = input("Please Enter your name : ")
course = input("Please Enter your course : ")
class_div = input("Please Enter your class : ")
rollno = input("Please Enter your roll no : ")

print("\nWELCOME,",name+"!!")

print("\nYour Details are :\n")


print("Name :",name)
print("Course :",course)
print("Class :",class_div)
print("Roll No :",rollno)

OUTPUT:
b) Write a python Program to perform arithmetic operations on any given inputs

INPUT:

print("Arithemetic Operations !\n")


num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))

add = num1 + num2


sub = num1 - num2
mul = num1 * num2
div = num1 / num2

print("\nAddition of First Number and Second Number is ",add)


print("\nSubstraction of First Number and Second Number is ",sub)
print("\nMultiplication of First Number and Second Number is ",mul)
print("\nDivsion of First Number and Second Number is ",div)

OUTPUT:
c) Write a python Program for Password Length Checker.

INPUT:

print("Password Length Checker !!")

user_input = input("Enter a password : ")

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:

CONCLUSION: Thus, studied basic input/output methods and operators in python.


EXPERIMENT NO: 02
Date of Performance :

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.

Built-in Data Types

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:

Text Type: str


Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: Dict
Set Types: Set
Boolean Type: Bool

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

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

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

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Tuple
A tuple is a collection which is ordered and unchangeable

Tuple Methods
Method Description

count() Returns the number of times a specified value occurs in a tuple

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

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

Returns the value of the specified key. If the key does not exist: insert the key,
setdefault()
with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


PROGRAMS
Create a menu driven python program to study various methods associated to datatypes string, list,
dictionary, set and tuple.
INPUT:

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:

CONCLUSION: Thus, studied different methods of Python data types.


EXPERIMENT NO: 03
Date of Performance :

Date of Submission :

AIM: To study loops and control statements in python


THEORY:
Control statements:
Decision making is anticipation of conditions occurring while execution of the program and
specifying actions taken according to the conditions.

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.

Sr.No. Statement & Description

1 if statements

An if statement consists of a boolean expression followed by one or more 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.

Sr.No. Loop Type & Description

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

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.

Sr.No. Control Statement & Description

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:

print("Python program to print Fibonacci series!\n")


pos = int (input ("Enter position : "))
fno = 0
sno =1
print (fno , end = " ")
print (sno , end = " ")
i=1
while (i <= pos):
tno = fno + sno
print (tno , end = " ")
fno = sno
sno = tno
i=i+1

OUTPUT:

B) Write a python program that finds duplicates from the list [`a`,`b`,’c`,`a`,`a`,`b`,`d`].

INPUT:

print("Python program that finds duplicates from the list!\n")


given_list=['a','b','c','a','a','b','d']

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:

print("Python program to print Character H !\n")


count=1;
alphabet = [
[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]
]
newList = [];
for l in alphabet:
newList.extend(l);
for x in newList:
print("*" if x==1 else " ",end="")
if count%7==0:
print("\n")
count+=1

OUTPUT:

CONCLUSION: Program executed successfully.


EXPERIMENT NO: 04
Date of Performance :

Date of Submission :

AIM: Creating functions, classes, objects and inheritance in python

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")

Pass by reference vs value


All parameters (arguments) in the Python language are passed by reference. It means if you change
what a parameter refers to within a function, the change also reflects back in the calling function.
Function Arguments
You can call a function by using the following types of formal arguments −
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments
Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition
Keyword Arguments
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters.
Default arguments
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument.
Variable-length arguments
You may need to process a function for more arguments than you specified while defining the
function. These arguments are called variable-lengtharguments and are not named in the
function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is this –
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword
variable arguments. This tuple remains empty if no additional arguments are specified during
the function call.
Python class and objects:
Creating Classes
The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows –
class ClassName:
'Optional class documentation string' class_suite
 The class has a documentation string, which can be accessed via ClassName. doc .
 The class_suite consists of all the component statements defining class members, data
attributes and functions
 Create instance object
To create instances of a class, you call the class using class name and pass in
whatever arguments its init method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing Attributes
You access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows –
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" %
Employee.empCount
Built-In Class Attributes
Every Python class keeps following built-in attributes and they can be accessed using dot
operator like any other attribute −
 dict − Dictionary containing the class's namespace.
 doc − Class documentation string or none, if undefined.
 name − Class name.
 module − Module name in which the class is defined. This attribute is " main " in
interactive mode.
 bases − A possibly empty tuple containing the base classes, in the order of their
occurrence in the base class list.
PROGRAMS

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!")

s1=input("Enter First String: ")


s2=input("Enter Second String: ")
printVal(s1,s2)

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.

CONCEPT : CLASS AND OBJECTS


INPUT:

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

# instantiate the Parrot class


blu = Parrot("Blu", 10)
woo = Parrot("Woo", 15)

# access the class attributes


print("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))

# access the instance attributes


print("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
OUTPUT:

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)

# instantiate the object


blu = Parrot("Blu", 10)

# call our instance methods


print(blu.sing("'Happy'"))
print(blu.dance())

OUTPUT:
CONCEPT : INHERITANCE
INPUT:

print("Python program to implement Object Oriented Programming concept like Inheritance!\n")


# parent class
class Bird:

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))

def setMaxPrice(self, price):


self.__maxprice = price

c = Computer()
c.sell()

# change the price


c.__maxprice = 1000
c.sell()

# using setter function


c.setMaxPrice(1000)
c.sell()

OUTPUT:
CONCEPT : POLYMORPHISM

INPUT:

print("Python program to implement Object Oriented Programming concept like Polymorphism!\n")

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()

# passing the object


flying_test(blu)
flying_test(peggy)

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:

CONCLUSION: Program executed successfully.


EXPERIMENT NO: 05
Date of Performance :

Date of Submission :

AIM: To Explore files and directories using python

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.

Opening and Closing Files


Python provides basic functions and methods necessary to manipulate files by default. You can
do most of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open() function.
This function creates a file object, which would be utilized to call other support methods
associated with it.
Syntax

file object = open(file_name [, access_mode][, buffering])


Here are parameter details −

 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 −

Sr.No. Attribute &


Description
1
file.closed Returns true if file is closed, false otherwise.
2
file.mode Returns access mode with which file was opened.
3
file.name Returns name of the file.
4
file.softspaceReturns false if space explicitly required with print, true otherwise.

The close() Method


The close() method of a file object flushes any unwritten information and closes the file object,
after which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It
is a good practice to use the close() method to close a file.
Syntax

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

the new filename. Syntax

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

working directory. Syntax


os.getcwd()
The rmdir() Method
The rmdir() method deletes the directory, which is passed as an

argument in the method. Before removing a directory, all the contents in

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")

file_a = open("AkshayPython.txt", "w" )


C = ["My Name is Akshay Chandarkar! \n", "Computer Engineer \n"]
file_a.writelines(C)
print()
file_a.close()

file_a = open("AkshayPython.txt", "r")


print("Output of Readlines before appending !")
print(file_a.read())
print()
file_a.close()

# append
file_a = open("AkshayPython.txt", "a")

file_a.write("\n")
file_a.write("Python program to append data to existing file succeeded!")

file_a = open("AkshayPython.txt", "r")


print("Output of Readlines after appending !")
print(file_a.read())
print()
file_a.close()

OUTPUT:
2. Python program to count number of lines, words and characters in a file.

INPUT:

print("Python program to count number of lines, words and characters in a file!\n")

file_a = open("AkshayPython.txt", "r")

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()

print("Lines : ", number_lines, "\nWords : ", number_words, "\nCharacters :


",number_characters)

OUTPUT:
3. Python program to display file available in current directory

INPUT:

print("Python program to display file available in current directory!\n")


import glob

print("List of All Files in Current Directory:")


for file in glob.glob("*.*"):
print(file)

OUTPUT:

CONCLUSION: Program executed successfully.


EXPERIMENT NO: 06
Date of Performance :

Date of Submission :

AIM: To send emails using python modules and packages

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

There are actually three different ways to define a module in Python:

1. A module can be written in Python itself.


2. A module can be written in C and loaded dynamically at run-time, like the re (regular expression) module.
3. A built-in module is intrinsically contained in the interpreter, like the itertools module.

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

Python program to send emails using modules and packages.

INPUT:

print("Python program to send mail!\n")

import smtplib

from email.mime.text import MIMEText

froma = 'cm.a.70. pushkaraj.chaudhary@gmail.com'


to = 'cm.a.70.pushkaraj.chaudhary@gmail.com'
msg = MIMEText('Hello !\nPushkaraj Chaudhary here! \nThis mail is sent by using Python Program !')
msg['Subject'] = 'PYTHON EXPERIMENT'
msg['From'] = froma
msg['To'] = to

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 :

AIM: Exploring basics of NumPy Methods.

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.

There are several ways to create a NumPy array.


To create a one-dimensional NumPy array,
import numpy as np
x = [2, 3, 4, 5, 6]
nums = np.array([2, 3, 4, 5, 6])
type(nums)

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]])

The arange Method


Another commonly used method for creating a NumPy array is the arange method. This method takes
the start index of the array, the end index, and the step size (which is optional).

nums = np.arange(2, 7)
array([2, 3, 4, 5, 6])
nums = np.arange(2, 7, 2)
array([2, 4, 6])

The zeros Method


Apart from generating custom arrays with your pre-filled data, you can also create NumPy arrays with a
simpler set of data. For instance, you can use the zeros method to create an array of all zeros as shown
below:

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.]])

The ones Method


create one-dimensional and two-dimensional arrays of all ones using the ones method as follows:
ones = np.ones(5)
array([1., 1., 1., 1., 1.])

And again, for the two-dimensional array, try out the following code:

ones = np.ones((5, 4))


Now if you print the ones array on the screen, you should see the following two-dimensional array:
[[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]

The linspace Method


This method takes three arguments: a start index, end index, and the number of linearly-spaced numbers
that you want between the specified range. For instance, if the first index is 1, the last index is 10 and
you need 10 equally spaced elements within this range, you can use the linspace method as follows:
lin = np.linspace(1, 10, 10)

The output will return integers from 1 to 10:


array([1., 2., 3., 4., 5., 6., 7., 8., 9., 10.])
Now let's try to create an array with 20 linearly-spaced elements between 1 and 10. Execute the
following script:
lin = np.linspace(1, 10, 20)

This will result in the following array:


array([ 1. , 1.47368421, 1.94736842, 2.42105263, 2.89473684,
3.36842105, 3.84210526, 4.31578947, 4.78947368, 5.26315789,
5.73684211, 6.21052632, 6.68421053, 7.15789474, 7.63157895,
8.10526316, 8.57894737, 9.05263158, 9.52631579, 10. ])

The random Method


create arrays with random numbers. You can use the rand function of NumPy's random module to do so.
Here is a simple example of the rand function:
random = np.random.rand(2, 3)
The above script returns a matrix of 2 rows and 3 columns. The matrix contains uniform distribution of
numbers between 0 and 1:
array([[0.26818562, 0.65506793, 0.50035001],
[0.527117 , 0.445688 , 0.99661 ]])
Similarly, to create a matrix of random numbers with the Gaussian distribution (or "normal"
distribution), you can instead use the randn method as shown below:
random = np.random.randn(2, 3)
The randint method takes the lower bound, upper bound, and the number of integers to return. For
instance, if you want to create an array of 5 random integers between 50 and 100, you can use this
method as follows:

random = np.random.randint(50, 100, 5)


array([54, 59, 84, 62, 74])
PROGRAMS
1. Import Numpy
INPUT:

2. Create an array of 10 zeroes


INPUT:
print("Python program to create array of 10 zeros!\n")
import numpy as np
array=np.zeros(10)
print("An array of 10 zeros:")
print(array)

OUTPUT:

3. Create an array of 10 ones


INPUT:
print("Python program to create array of 10 ones!\n")
import numpy as np
array=np.ones(10)
print("An array of 10 ones:")
print(array)

OUTPUT:
4. Create an array of 10 fives
INPUT:

print("Python program to create array of 10 fives!\n")


import numpy as np
array=np.ones(10)*5
print("An array of 10 fives:")
print(array)

OUTPUT:

5. Create an array of the integers from 10 to 50


INPUT:

print("Python program to create array of all the integers from 10 to 50!\n")


import numpy as np
array=np.arange(10,51)
print("Array of all the integers from 10 to 50:\n")
print(array)

OUTPUT:

6. Create an array of all the even integers from 10 to 50


INPUT:

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:

7. Create a 3x3 matrix with values ranging from 0 to 8


INPUT:
print("Python program to create a 3x3 matrix with values ranging from 0 to 8!\n")
import numpy as np
x = np.arange(0, 9).reshape(3,3)
print(x)

OUTPUT:

8. Create a 3x3 identity matrix


INPUT:

print("Python program to create a 3x3 identity matrix!\n")


import numpy as np
array_2D=np.identity(3)
print('3x3 matrix:')
print(array_2D)

OUTPUT:

9. Use Numpy to generate a random number between 0 to 1


INPUT:
print("Python program to generate a random number between 0 to 1!\n")
import numpy as np
rand_num = np.random.normal(0,1,1)
print("Random number between 0 and 1 : ")
print(rand_num)

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:

11. Create a matrix 10x10 matrix values between 0 to 1


INPUT:
print("Python program to generate a matrix 10x10 matrix values between 0 to 1!\n")
import numpy as np
x = np.ones((10, 10))
x[1:-1, 1:-1] = 0
print(x)
OUTPUT:
12. Create an array of 20 linearly spaced points between 0 and 1
INPUT:
print("Python program to create an array of 20 linearly spaced points between 0 and 1!\n")
import numpy as np
num_line = np.linspace(0,1,20)
print(num_line)

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:

14. Write code to Extract value 20 from 2d array


INPUT:
print("Python program to Extract value 20 from 2d array!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extracted Value : ",x[2:,0])

OUTPUT:

15. Write code to Extract only first two rows


INPUT:
print("Python program to Extract only first two rows!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extract first two rows : ")
r = x[:2]
print(r)

OUTPUT:

16. Write code to Extract first column


INPUT:
print("Python program to Extract first column!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extract first column:")
r = x[:,[0]]
print(r)
OUTPUT:
17. Write code to Extract second column and Third column
INPUT:
print("Python program to Extract first column!\n")
import numpy as np
x = np.arange(12, 24).reshape(3,4)
print(x)
print("Extract second and third columns:")
r = x[:,[1,2]]
print(r)

OUTPUT:

18. Write code to Perform basic numpy operation on arr(1,25)


INPUT:
print("Python program to Perform basic numpy operation on arr(1,25)!\n")
import numpy as np
arr1 = np.arange(1,25)
print('First array:')
print(arr1)
print('\nSecond array:')
arr2 = np.arange(1,25)
print(arr2)
print('\nAdding the two arrays:')
print(np.add(arr1, arr2))
print('\nSubtracting the two arrays:')
print(np.subtract(arr1, arr2))
print('\nMultiplying the two arrays:')
print(np.multiply(arr1, arr2))
print('\nDividing the two arrays:')
print(np.divide(arr1, arr2))
OUTPUT:

CONCLUSION: Program executed successfully.


EXPERIMENT NO: 08

Date of Performance :

Date of Submission :

AIM: Program to demonstrate Data Series using Pandas

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

A pandas Series can be created using the following constructor −


pandas.Series( data, index, dtype, copy)

The parameters of the constructor are as follows −


Sr.No Parameter & Description
data
1
data takes various forms like ndarray, list, constants
index
2
Index values must be unique and hashable, same length as data. Default np.arrange(n) if no
index is passed.
dtype
3
dtype is for data type. If None, data type will be inferred
copy
4
Copy data. Default False

A series can be created using various inputs like −

 Array
 Dict
 Scalar value or constant
Create an Empty Series

A basic series, which can be created is an Empty Series.


Example
#import the pandas library and aliasing as pd
import pandas as pd
s = pd.Series()
print s

Its output is as follows –

Series([], dtype: float64)

Create a Series from ndarray

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

Its output is as follows −


0 a
1 b
2 c
3 d
dtype: object

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

Its output is as follows −


100 a
101 b
102 c
103 d
dtype: object

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

Its output is as follows −


a 0.0
b 1.0
c 2.0
dtype: float64

Observe − Dictionary keys are used to construct index.

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

Its output is as follows −


b 1.0
c 2.0
d NaN
a 0.0
dtype: float64

Observe − Index order is persisted and the missing element is filled with NaN (Not a Number).

Create a Series from Scalar

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

Its output is as follows −


0 5
1 5
2 5
3 5
dtype: int64

Accessing Data from Series with Position

Data in the series can be accessed similar to that in an ndarray.

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 element


print s[0]

Its output is as follows −


1

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'])

#retrieve the first three element


print s[:3]

Its output is as follows −


a 1
b 2
c 3
dtype: int64

Retrieve the last three elements.


import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve the last three element


print s[-3:]

Its output is as follows −


c 3
d 4
e 5
dtype: int64

Retrieve Data Using Label (Index)

A Series is like a fixed-size dict in that you can get and set values by index label.
Example

Retrieve a single element using index label value.


import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve a single element


print s['a']

Its output is as follows −

Retrieve multiple elements using a list of index label values.import pandas as pd


s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve multiple elements


print s[['a','c','d']]

Its output is as follows −


a 1
c 3
d 4
dtype: int64

If a label is not contained, an exception is raised.


import pandas as pd
s = pd.Series([1,2,3,4,5],index = ['a','b','c','d','e'])

#retrieve multiple elements


print s['f']

Its output is as follows −



KeyError: 'f'
PROGRAMS
[1] Import Pandas Library
INPUT:

[2] Create a series from a list, numpy array and dict


INPUT:
print("Python program to create a series from a list, numpy array and dictionary!\n")
import pandas as pd
import numpy as np
print('Series')
lst = ['A','B','C','D','E']
s = pd.Series(lst)
print(s)
print('')
print('Dictionary')
dct = {'G':2,'O':2,'A':1,'L':1}
s = pd.Series(dct)
print(s)
print('')
print('Numpy')
arr = np.array(['F','O','C','U','S'])
s = pd.Series(arr)
print(s)

OUTPUT:

[3] Convert the index of a series into a column of a dataframe


INPUT:
print("Python program to convert the index of a series into a column of a dataframe!\n")
import pandas as pd
df = pd.DataFrame({'Name': ['ABC', 'DEF', 'GHI', 'XYZ'],
'Grade': ['A', 'A', 'C', 'B'],
'Subject': ['Python', 'Microprocessor', 'Java', 'Python']})
print(df)
OUTPUT:

[4] Combine many series to form a dataframe


INPUT:

print("Python program to combine many series to form a dataframe!\n")


import pandas as pd
def createSeries (series_list):
series_list = pd.Series(series_list)
return series_list
students = createSeries(['ABC', 'DEF',
'GHI', 'JKL',
'MNO', 'PQR'])
subject = createSeries(['C++', 'C#',
'RUBY', 'SWIFT',
'GO', 'PYTHON'])
marks = createSeries([90, 30,
50, 70,
80, 60])
data = {"students": students,
"subject": subject,
"marks": marks}
df = pd.concat(data, axis = 1)
print(df)
OUTPUT:

[5] Assign name to the series’ index


INPUT:

print("Python program to Assign name to the series’ index!\n")


import pandas as pd
sr = pd.Series([10, 25, 3, 45])
index_ = ['ABC', 'DEF', 'XZA', 'CDW']
sr.index = index_
print(sr)
result = sr.rename('Details')
print(result)

OUTPUT:

[6] Get the items of series A not present in series B


INPUT:
print("Python program to Get the items of series A not present in series B!\n")
import pandas as pd
psA = pd.Series([2, 4, 8, 20, 10, 47, 99])
psB = pd.Series([1, 3, 6, 4, 10, 99, 50])
print("Series A :")
print(ps1)
print("\nSeries B :")
print(ps2)
print("\nItems of Series A not present in Series B:")
res = ps1[~ps1.isin(ps2)]
print(res)

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:

print("Python program to Explore various useful methods of Data series!\n")


import pandas as pd
import numpy as np
data = np.array(['Q','W','E','R','T','Y','A','S','D','F'])
ser = pd.Series(data,index=[10,11,12,13,14,15,16,17,18,19])
ser = pd.Series(data)
print('retrieve the first element')
print(ser[:5])
print('Retriving the element at 5th location')
print(ser[5])
print('retrieve the last three element')
print(ser[-3:])

OUTPUT:

CONCLUSION: Program executed successfully/


EXPERIMENT NO: 09
Date of Performance :

Date of Submission :

AIM: Program to demonstrate Data Frames using Pandas

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.

You can think of it as an SQL table or a spreadsheet data representation.


pandas.DataFrame
A pandas DataFrame can be created using the following constructor −
pandas.DataFrame( data, index, columns, dtype, copy)
The parameters of the constructor are as follows −
Sr.No Parameter & Description
data
1 data takes various forms like ndarray, series, map, lists, dict, constants and also another
DataFrame.
index
2 For the row labels, the Index to be used for the resulting frame is Optional Default np.arange(n) if
no index is passed.
columns
3 For column labels, the optional default syntax is - np.arange(n). This is only true if no index is
passed.
dtype
4
Data type of each column.
copy
5
This command (or whatever it is) is used for copying of data, if the default is False.
Create DataFrame
A pandas DataFrame can be created using various inputs like −
 Lists
 dict
 Series
 Numpy ndarrays
 Another DataFrame
In the subsequent sections of this chapter, we will see how to create a DataFrame using these inputs.
Create an Empty DataFrame
A basic DataFrame, which can be created is an Empty Dataframe.
Example
#import the pandas library and aliasing as pd
import pandas as pd
df = pd.DataFrame()
print df
Its output is as follows −
Empty DataFrame
Columns: []
Index: []
Create a DataFrame from Lists
The DataFrame can be created using a single list or a list of lists.
Example 1
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print df
Its output is as follows −
0
0 1
1 2
2 3
3 4
4 5
Example 2
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print df
Its output is as follows −
Name Age
0 Alex 10
1 Bob 12
2 Clarke 13
Example 3
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'],dtype=float)
print df
Its output is as follows −
Name Age
0 Alex 10.0
1 Bob 12.0
2 Clarke 13.0
Note − Observe, the dtype parameter changes the type of Age column to floating point.
Create a DataFrame from Dict of ndarrays / Lists
All the ndarrays must be of same length. If index is passed, then the length of the index should equal to
the length of the arrays.
If no index is passed, then by default, index will be range(n), where n is the array length.
Example 1
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print df
Its output is as follows −
Age Name
0 28 Tom
1 34 Jack
2 29 Steve
3 42 Ricky
Note − Observe the values 0,1,2,3. They are the default index assigned to each using the function
range(n).
Example 2
Let us now create an indexed DataFrame using arrays.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data, index=['rank1','rank2','rank3','rank4'])
print df
Its output is as follows −
Age Name
rank1 28 Tom
rank2 34 Jack
rank3 29 Steve
rank4 42 Ricky
Note − Observe, the index parameter assigns an index to each row.
Create a DataFrame from List of Dicts
List of Dictionaries can be passed as input data to create a DataFrame. The dictionary keys are by
default taken as column names.
Example 1
The following example shows how to create a DataFrame by passing a list of dictionaries.
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print df
Its output is as follows −
a b c
0 1 2 NaN
1 5 10 20.0
Note − Observe, NaN (Not a Number) is appended in missing areas.
Example 2
The following example shows how to create a DataFrame by passing a list of dictionaries and the row
indices.
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data, index=['first', 'second'])
print df
Its output is as follows −
a b c
first 1 2 NaN
second 5 10 20.0
Example 3
The following example shows how to create a DataFrame with a list of dictionaries, row indices, and
column indices.
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]

#With two column indices, values same as dictionary keys


df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])

#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

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)
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

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)
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 ("Adding a new column by passing as Series:")


df['three']=pd.Series([10,20,30],index=['a','b','c'])
print df

print ("Adding a new column using the existing columns in DataFrame:")


df['four']=df['one']+df['three']

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

Adding a new column using the existing columns in DataFrame:


one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
d NaN 4 NaN NaN
Column Deletion
Columns can be deleted or popped; let us take an example to understand how.
Example
# Using the previous DataFrame, we will delete a column
# using del function
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']),
'three' : pd.Series([10,20,30], index=['a','b','c'])}

df = pd.DataFrame(d)
print ("Our dataframe is:")
print df

# using del function


print ("Deleting the first column using DEL function:")
del df['one']
print df

# using pop function


print ("Deleting another column using POP function:")
df.pop('two')
print df
Its output is as follows −
Our dataframe is:
one three two
a 1.0 10.0 1
b 2.0 20.0 2
c 3.0 30.0 3
d NaN NaN 4

Deleting the first column using DEL function:


three two
a 10.0 1
b 20.0 2
c 30.0 3
d NaN 4

Deleting another column using POP function:


three
a 10.0
b 20.0
c 30.0
d NaN
Row Selection, Addition, and Deletion
We will now understand row selection, addition and deletion through examples. Let us begin with the
concept of selection.
Selection by Label
Rows can be selected by passing row label to a loc function.
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)
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

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)
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

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)
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 = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])


df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

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 = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])


df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df = df.append(df2)

# Drop rows with label 0


df = df.drop(0)

print df
Its output is as follows −
a b
1 3 4
1 7 8
PROGRAMS
1. Import Pandas Library
INPUT:

2. Import tips.csv file


INPUT:

3. Display dataframe
INPUT:

print("Python program to display dataframe!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df)

OUTPUT:
4. Display total_bill & tips Column
INPUT:

print("Python program to display total_bill & tips Column!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df[['total_bill','tip']])

OUTPUT:

5. Calculate tip percent over total bill


INPUT:

print("Python program to calculate tip percent over total bill!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
df['tip_percent'] = df['tip'] / df['total_bill'] * 100
print(df)

OUTPUT:
6. Create a new column having tip percent
INPUT:

print("Python program to create a new column having tip percent!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
df['tip_percent'] = df['tip'] / df['total_bill'] * 100
print(df)

OUTPUT:

7. Set new index Payment_ID of df


INPUT:

print("Python program to set new index Payment_ID of df!\n")


import pandas as pd
import csv
data = pd.read_csv("tips.csv")
data.set_index("tip", inplace = True)
data.head()
print(data)
OUTPUT:

8. Display first 3 rows of df using numerical index


INPUT:
print("Python program to display first 3 rows of df using numerical index!\n")
import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df[:3])

OUTPUT:

9. Drop row having ID ‘Sun2959’


INPUT:

print("Python program to drop row having ID ‘Sun2959’!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df[df['Payment ID']=='Sun2959'])
OUTPUT:

10. Drop first two rows from df


INPUT:

print("Python program to drop first two rows from df!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.drop(index= df[:2].index))

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:

12. Find records where tip>5 and Gender =’Female’


INPUT:

print("Python program to find records where tip>5 and Gender =’Female’!\n")


import pandas as pd
import csv
df = pd.read_csv('tips.csv')
print(df.loc[(df['tip'] > 5) & (df['sex'] == 'Female')])

OUTPUT:

13. Apply useful methods on df


01.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.nunique())
01.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:

CONCLUSION: Program executed successfully.


EXPERIMENT NO: 10

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

methods of list objects: list.append(x)


Add an item to the end of the list; equivalent to
a[len(a):] = [x]. list.extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before
which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is
equivalent to a.append(x).
list.remove(x)
Remove the first item from the list whose value is x. It is an error if there
is no such item. list.pop([i])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop()
removes and
returns the last item in the list. (The square brackets around the i in the method signature denote
that the parameter is optional, not that you should type square brackets at that position. You will
see this notation frequently in the Python Library Reference.)
list.index(x)
Return the index in the list of the first item whose value is x. It is an error if there
is no such item. list.count(x)
Return the number of times x appears in the list.
list.sort()

Sort the items of


the list, in place.
list.reverse()
Reverse the elements of the list, in place.

Using List as Stack

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.

Using List as Queues

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 Push(stk,item): # Allow additions to the stack


stk.append(item)
top=len(stk)-1

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:

CONCLUSION: Program executed successfully

You might also like