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

Raisoni TYBBA (CA) Sem V LabBook of Java & Python

Bshsjjs

Uploaded by

life99724
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Raisoni TYBBA (CA) Sem V LabBook of Java & Python

Bshsjjs

Uploaded by

life99724
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 68

G H Raisoni College, Wagholi, Pune

T. Y. B. B. A. (C. A.) Semester-V


(CBCS 2019 Pattern)

Core Java and Python


BCAP506 : Lab Book

Student Name:

College Name:

Roll No.: Division: Seat No: _

Academic Year:
CERTIFICATE

This is to certify that Mr./Ms.


Seat Number _ _ of T.Y.B.B.A. (C.A) Sem-V has
successfully completed Laboratory course (Core Java, Mongo DB/
Python in the year _. He/She has scored
mark out of 10 (For Lab Book).

Subject Teacher H.O.D./Coordinator

Internal Examiner External Examiner


Editorial Board: Dr. D. Y. Patil ACS College, Pimpri, Pune

Section-I: Core Java

Mr. Satyavan Kunjir

Mrs. Reshma Masurekar

Mrs. Malati Tribhuvan

Section-II: Python

Mr. Yogesh Ingale

Mrs. Kanchan Rathi

Mrs. Trupti Kulkarni

Reviewed By:

Dr. Ranjit Patil

Dr. Sujata Patil

Mrs. Shakila Siddavatam

Mr. Sudarshan Lakhdive

Mr. Shivendu Bhushan

Mrs. Sangeeta Nimbalkar

Mrs. Leena Bhat


Introduction

1. About the work book:


This workbook is intended to be used by T.Y.B.B.A. (C.A.) Semester-V students for
Core java, MongoDB and Python Practical assignments. This workbook is designed
by considering all the practical topics mentioned in syllabus.

2. The objectives of this workbook are:


 Defining the scope of the course.
 To bring the uniformity in the practical conduction and implementation in all
colleges affiliated to SPPU.
 To have continuous assessment of the course and students.
 Providing ready reference for the students during practical implementation.
 Provide more options to students so that they can have good practice before facing
the examination.
 Catering to the demand of slow and fast learners and accordingly providing the
practice assignments to them.

3. How to use this workbook:


The workbook is divided into two sections. Section-I is related to Core Java
assignments, Section-II is related to MongoDB assignments or Python assignments.

Section-I: Core java is divided into five assignments.


Section-II: MongoDB is divided into five assignments.
OR
Section-II: Python is divided into eight assignments.

Students have to perform practical assignments of selected elective subject from


Section-II.
Each assignment of all sections has three SETs-A, B and C. It is mandatory for
students to complete SET A and SET B in lab. It also includes practice set which are
expected to be solved by students as home assignments and to be evaluated by subject
teachers.

4. Instructions to the students:


Please read the following instructions carefully and follow them during practical.
 Students are expected to carry this workbook every time they come to the lab for
computer practical.
 Students should prepare for the assignment by reading the relevant material which is
mentioned in ready reference and the concepts taught in class.
 Instructor will specify which problems to solve in the lab during the allotted slot and
student should complete them and get verified by the instructor. However, student
should spend additional hours in Lab and at home to cover all workbook assignments
if needed.
 Students will be assessed for each exercise on a scale from 0 to 5.
Not Done 0
Incomplete 1
Late Complete 2
Needs improvement 3
Complete 4
Well Done 5

5. Instruction to the Instructors:

Make sure that students should follow above instructions.


 Explain the assignment and related concepts in around ten minutes using
whiteboard if required or by demonstrating the software.
 Evaluate each assignment carried out by a student on a scale of 5 as specified
above by ticking appropriate box.
 The value should also be entered on assignment completion page of the
respective Lab course.

6. Instructions to the Lab administrator:

You have to ensure appropriate hardware and software is made available to each
student.
The operating system and software requirements on server side and also client side
are as given below:
 Operating System - Windows
 Python 3.0
 MongoDB Community Edition
 JDK
Assignment Completion Sheet

Section-I: Core Java

Sr. Assignment Name Marks Teacher’s


No. (out of 5) Sign
1 Introduction to Java

2 Classes, Objects and Methods

3 Inheritance, Package and Collection

4 File and Exception Handling

5 Enhancement in java 8 & Java 9

Total ( Out of 25 )

Total (Out of 5)

Instructor Signature:
Section-II: Python

Sr. Assignment Name Marks Teacher’s


No. (out of 5) Sign
1 Introduction to Basic Python

2 Working with Strings and List

3 Working with Tuples, Sets and Dictionaries

4 Working with Functions, Modules and Packages

5 Python Classes and Objects

6 Inheritance

7 Exception Handling

8 Python GUI Programming using Tkinter

Total ( Out of 40 )

Total (Out of 5)

Instructor Signature:
Section – I
Core Java
Assignment No. 1: Introduction to Java
Jdk (Java Development Kit) Tools:

Java environment includes a number of development tools, classes and methods. The development
tools are part of the system known as Java Development Kit (JDK) and the classes and methods are
part of theJava Standard Library (JSL), also known as the Application Programming Interface (API).

Java Development kit (JDK) – The JDK comes with a set of tools that are used for developing and
running Java program. It includes:

1) appletviewer: It is used for viewing the applet


2) javac: It is a Java Compiler
3) java: It is a java interpreter
4) javap: It is Java diassembler, which convert byte code into program description.
5) javah: It is for java C header files.
6) javadoc: It is for creating HTML document.
7) jdb: It is Java debugger.

Data Types:

Type Description(Range)

boolean These have values of either true or false.


byte 7-bit 2s-compliment integer with values between –27 and 27-1 (–128 to 127).

short 16-bit 2s-compliment integer with values between –215 and 215-1 (–32,768 to
32,767).
char 16-bit Unicode characters. For alphanumerics, these are the same as ASCII
with the high byte set to 0. The numerical values are unsigned 16-bit values
between 0 and 65535.
int 32-bit 2s-compliment integer with values between –231 and 231-1
(–2,147,483,648 to 2, 147,483,647).
long 64-bit 2s-compliment integer with values between –263 and 263-1
(–9223372036854775808 to 9223372036854775807).
float 32-bit single precision floating point numbers using the IEEE 754-1985 standard
(+/– about 1039).

double 64-bit double precision floating point numbers using the IEEE 754-1985 standard
(+/– about 10317).
Java Array
Array is a collection of similar type of elements that have contiguous memory location. Java array is an
object that contains elements of similar data type. Only fixed set of elements can be stored in a java array.
Syntax:
There are two sections in the syntax of an array:
Declaration:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation:
arrayRefVar=new datatype[size];
Use of length property of an array:
To calculate size of an array.
Size=arrayname.length;
For Example: Java Program for demonstration of an array using command line arguments.
class Demo
{
public static void main (String args [])
{
int i,n;
n=args.length;
int a[]=new int[n];
for(i=0;i<n;i++)
{
a[i]=Integer.parseInt(args[i]);
}
//printing array
for (int i=0;i<n;i++)
System.out.println (a[i]);
}}

String:
The set of characters are collectively called String. It is Wrapper class. Anything, if we declare with
String class, java compiler considered it as an object. It is immutable.

The List of functions of String:


Sr. No Methods with Description
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
It is the Abstract Window Tool Kit package contains classes that implements platform independent
graphical user interface.
6) Applet Package:
This includes an act of classes that allows us to create Java applets.

For adding the packages in an application, import statement is used.


Syntax:
import package_Name;

Example 1: Java program to accept the data and display it.(Use Scanner Class)
import java.util.*;
class Emp
{
public static void main(String args[])
{
int e;
String en;
float s;
Scanner ob=new Scanner(System.in);
System.out.println(“Eno Ename and Salary”);
e=ob.nextInt();
en=ob.next();
s=ob.nextFloat ();
System.out.println(“Emp No Is “ + e);
System.out.println(“Emp Name” + en);
System.out.println(“Salary Is “ + s);
}
}

Example 2: Java Program to display date and time of a system.


import java.util.*;
class DateTime
{
public static void main(String args[])
{
Date d=new Date();
System.out.println(“Date and Time of a System is “ + d);
}
}
Practice Set:
1. Write a java Program to check whether given String is Palindrome or not.
2. Write a Java program which accepts three integer values and prints the maximum and
minimum.
3. Write a Java program to accept a number from command prompt and generate
multiplication table of a number.
4. Write a Java program to display Fibonacci series.
5. Write a Java program to calculate sum of digits of a number.
6. Write a Java program to accept a year and check if it is leap year or not.
7. Write a Java program to display characters from A to Z using loop.
8. Write a Java program to accept two numbers using command line argument and calculate
addition, subtraction, multiplication and division.
9. Write a java Program to calculate the sum of first and last digit of a number.
10. Write a java program to calculate the sum of even numbers from an array.
Set A:
1.Write a java Program to check whether given number is Prime or Not.
2.Write a java Program to display all the perfect numbers between 1 to n.
3.Write a java Program to accept employee name from a user and display it in reverse order.
4.Write a java program to display all the even numbers from an array. (Use Command Line
arguments)
5. Write a java program to display the vowels from a given string.

Set B:
1. Write a java program to accept n city names and display them in ascending order.
2. Write a java program to accept n numbers from a user store only Armstrong numbers in an array
and display it.
3. Write a java program to search given name into the array, if it is found then display its index
otherwise display appropriate message.
4. Write a java program to display following pattern:
5
45
345
2345
12345
5. Write a java program to display following pattern:
1
01
010
1010

Set C:
1. Write a java program to count the frequency of each character in a given string.
2. Write a java program to display each word in reverse order from a string array.
3. Write a java program for union of two integer array.
4. Write a java program to display transpose of given matrix.
5. Write a java program to display alternate character from a given string.
Assignment Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone [ ]

Signature of Instructor
Recursion:
A method that calls itself is known as a recursive method and this process is known as
recursion. In java Recursion is a process in which a method calls itself continuously.

class RecFibbonacci
{
int fib(int n)
{
if(n==0)
return 0;
else if (n==1)
return 1;
else
return fib(n-1)+fib(n-2);
}

public static void main(String args[])


{
int n,i;
n=Integer.parseInt(args[0]);
RecFibbonacci R=new RecFibbonacci();
for(i=0;i<=n;i++)
{
System.out.println(R.fib(i));
}

}
}

Passing Object as Parameter:


When primitive type is passed to a method, it is passed by value. But when an object is
passed to a method, then it is known as call-by-reference. The updation done with in method will
be reflected in the object.
Syntax:
methodName(Object obj)

Returning Objects:
In java, a method can return any type of data, including objects.
Syntax:
ObjectName methodName();
The new operator:
The new operator is used in Java to create new objects. It can also be used to create an array
object.
Syntax to create object using new operartor
ClassName object=new ClassName();

The Array of Objects


Syntax :
Class_name [] objArray;
or
Class_name objArray[];
Example:
Student[] S;
or
Student S[] ;
Declare and instantiate the array of objects
Class obj[]= new Class[array_length]
Ex. Student S[] = new student[2];
It will create an array of objects ‘S’ with 2 elements/object references.
Imp Note that once an array of objects is instantiated; the individual elements of the array of
objects need to be created using new.

For Example: Java Program to demonstrate Array of Object.


import java.util.*;
class Student
{
int sid;
String Sname;
void accept(int id, String name)
{
sid=id;
Sname=name;
}
void display()
{
System.out.println("Sid = " +sid);
System.out.println("Sname= " + Sname);
}
}
class ArrayObjectEx
{
public static void main(String args[])
public static void main(String[] args)
{
Number Obj = new Number (5);
System.out.println("Value of x = " + Obj.x);
}
}
Static Keyword:
The static keyword is used for memory management. It is applied with variables,
methods, blocks and nested classes. Static keyword belongs to the class than an instance of the
class.

The static is used with variable and method.


Static Variable:
Static variable is declared using static keyword. The static variable gets memory only
once in the class area at the time of class loading and it is shared by all objects of its class.
Syntax:
static datatype varName;

For Example: Java Program to demonstrate static variable.


class Number
{
static int count=0;

Demo()
{
count++;
System.out.println(count);
}
public static void main(String args[])
{
Number N1=new Number ();
Number N2=new Number ();
Number N3=new Number ();
}
}

Static Method:
Static method is declared using static keyword. It is called using class name. A static
method can access static data member and can change the value of it.
For Example: Java Program to get the cube of a given number using the static method.
Nested class:
A class defined within another class is called as nested class. A nested class is a member
of its Outer class. Nested /Inner class can access all the members of outer class including private
data members and methods. Outer class does not have access to the members of the nested/Inner
class.
Syntax:
class OuterClass
{
class NetsedClass
{
---
---
}
}
For Example: Java Program to demonstrate nested class concept.
class Outer
{
int x =10;
class Inner
{
int y=20;
void display()
{
System.out.println("x= " + x);
System.out.println("y= " + y);
}
}
void show()
{
Inner I =new Inner();
System.out.println("Outer Show ");
I.display();
}
}
class NestedEx
{
public static void main(String args[])
{
Outer O =new Outer();
O.show();
}
}
{
System.out.println("I am in Number class");
}
}

class AnonymousDemo
{
public void createC()
{
Number N = new Number ()
{
public void display()
{
System.out.println("I am in anonymous class.");
}
};
N.display();
}
}
class Demo
{
public static void main(String[] args)
{
AnonymousDemo obj = new AnonymousDemo();
obj.createC();
}
}

Practice Set:
1. Write a Java program to for the implementation of reference variable.
2. Write a Java program to keep the count of object created of a class. Display the count
each time when the object is created.
3. Write a Java program to convert integer primitive data. (use toString()).
4. Write a Java program to calculate sum of digits of a number using Recursion.
5. Write a Java program to for the implementation of this keyword.

Set A:
1. Write a Java program to calculate power of a number using recursion.
2. Write a Java program to display Fibonacci series using function.
3. Write a Java program to calculate area of Circle, Triangle & Rectangle.(Use Method
Overloading)
4. Write a Java program to Copy data of one object to another Object.
5. Write a Java program to calculate factorial of a number using recursion.
Set B:
1. Define a class person(pid,pname,age,gender). Define Default and parameterised
constructor. Overload the constructor. Accept the 5 person details and display it.(use this
keyword).
2. Define a class product(pid,pname,price). Write a function to accept the product details, to
display product details and to calculate total amount. (use array of Objects)
3. Define a class Student(rollno,name,per). Create n objects of the student class and Display
it using toString().(Use parameterized constructor)
4. Define a class MyNumber having one private integer data member. Write a default
constructor to initialize it to 0 and another constructor to initialize it to a value. Write
methods isNegative, isPositive. Use command line argument to pass a value to the object
and perform the above tests.
Set C:
1. Define class Student(rno, name, mark1, mark2). Define Result class(total, percentage)
inside the student class. Accept the student details & display the mark sheet with rno,
name, mark1, mark2, total, percentage. (Use inner class concept)
2. Write a java program to accept n employee names from user. Sort them in ascending
order and Display them.(Use array of object nd Static keyword)
3. Write a java program to accept details of ‘n’ cricket players(pid, pname, totalRuns,
InningsPlayed, NotOuttimes). Calculate the average of all the players. Display the details
of player having maximum average.
4. Write a java program to accept details of ‘n’ books. And Display the quantity of given
book.

Assignment Evaluation:

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone [ ]

Signature of Instructor
Assignment No. 3: Inheritance, Package and Collection

The mechanism of deriving a new class from an old class is called as Inheritance. Old class is
called as Superclass or Base class and the new derived class is called as Subclass or Derived
class. It is also defined as the process where one class acquires the properties (methods and
fields) of another class. The keyword extends is used to inherit the properties of a base/super
class in derived/sub class.

Syntax:
class Superclass
{
// Superclass data variables
// Superclass member functions
}
class Subclass extends Superclass
{
// Subclass data variables
// Subclass member functions
}

Types of inheritance:
A) Single Inheritance:
One subclass is derived from only one superclass is called as single inheritance.

B
Syntax:
class ClassA
{
..... .....
}
class ClassB extends ClassA
{
..... .....
class FinalMethodDemo
{
public static void main(String args[])
{
Subclass obj=new Subclass();
obj.display();
obj.display1();
}
}

For example: Java Program to demonstrate final class.


final class Superclass
{
void display()
{
System.out.println("This is a final method.");
}
}
class Subclass extends Superclass
{
void display()
{
System.out.println("The final method is overridden.");
}
}
class FinalClass
{
public static void main(String args[])
{
Subclass obj = new Subclass();
obj.display();
}
}
Output will be:
C:\Program Files\Java\jdk1.8.0_221\bin>javac FinalClass.java
FinalClass.java:9: error: cannot inherit from final Superclass
class Subclass extends Superclass
^
1 error
Syntax to implement inteface:
class className implements InterfaceName
{
...
body-of-the-class
...
}
“implements” keyword is used to inherit interface in interface/class.

For example: Java Program to demonstrate interface.


interface I1
{
void display();
}

class Demo implements I1


{
public void display()
{
System.out.println("Intreface Demo .... ");
}
}

class InterfaceDemo
{
public static void main(String args[])
{
Demo D=new Demo();
D.display();
}
}

Interface inheritance
Interface inheritance is used when a class wants to implement more than one interface. List of
interfaces are seprated using comma implemented by the class. Multiple inheritance is possible
using interfaces but not by using class.

Syntax to implement multiple interfaces:


class className implements InterfaceName1 extends InterfaceName2, InterfaceName3 ...
{
...
body-of-the-class

...
}
Access Control:
Access modifiers define the scope of the class and its members (data and methods).
Private No Modifier Protected Public
Same Class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No No Yes Yes
Different package non-subclass No No No Yes

Packages:
A java package is a group of similar types of classes, interfaces and sub-packages.In Java,
Package is categorized in two forms:
a. User-defined package
b. Predefined package

User-defined package: The package created by user is called user-defined package. To create
user defined package, Java uses a file system directory to store them just like folders on your
computer:
Example
└── root/bin
└── mypackage
└── MyPackageClass.java
First we create a directory mypackage (name should be same as the name of the package).
Then create the MyPackageClass.java inside the directory with the first statement being
the package names. To create a package, package keyword is used.
Syntax:
package packagename;

For example:
package mypackage;
class MyPackageClass
{
public static void main(String[] args)
{
System.out.println("This is my package!");
}
}
Keyword import is used to use a class or a package from the library.
Syntax:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
Collection:
A collection is an object that groups multiple elements into a single unit i.e. single unit of
objects. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
Collection Framework:
The collection framework is the collection of classes and interfaces.
A Java collection framework provides architecture to store and manipulate a group of objects. A
Java collection framework includes the following:
1. Interfaces
2. Classes
3. Algorithm

The List of interfaces:


➢ Collection
➢ Set
➢ List
➢ Map
➢ SortedMap
➢ Enumeration

The List of classes:


➢ ArrayList
➢ LinkedList
➢ HashSet
➢ TreeSet

Algorithm: Algorithm refers to the methods which are used to perform operations such as
searching and sorting, on objects that implement collection interfaces.
Interfaces: Collection, List, Set
Collection Interface:
The group of data or the set of data which is binding in a unit in object form that unit is called
Collection. Collection is an interface present at topmost position in collection framework.
For the implementation of collection interface any class can be used which is at last level as leaf
node in collection framework.
For Example:
Collection c=new HashSet()
Collection c=new ArrayList()
Collection c=new Vector()

Sr. No. Methods with Description


1. boolean add(Object obj)
Adds obj to the invoking collection. Returns true if obj is added to the
collection. Returns false if obj is already a member of the collection, or if the
collection does not allow duplicates.
2. boolean addAll(Collection c)
Adds all the elements of c to the invoking collection. Returns true if the
operation succeeds (i.e., the elements were added). Otherwise, returns false.
3. void clear( )
Removes all elements from the invoking collection.
4. boolean contains(Object obj)
Returns true if obj is an element of the invoking collection. Otherwise,
returns false.
5. boolean containsAll(Collection c)
Returns true if the invoking collection contains all elements of c. Otherwise,
returns false.
6. boolean equals(Object obj)
Returns true if the invoking collection and obj are equal. Otherwise, returns
false.
7. int hashCode( )
Returns the hash code for the invoking collection.
8. boolean isEmpty( )
Returns true if the invoking collection is empty. Otherwise, returns false.
9. Iterator iterator( )
Returns an iterator for the invoking collection.
10. boolean remove(Object obj)
List interface:
The List interface extends Collection and declares the behavior of a collection that stores a
sequence of elements. Elements can be inserted or accessed by their position in the list, using a
zero-based index. A list may contain duplicate elements.
Sr. No. Methods with Description
1. void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in index. Any pre-
existing elements at or beyond the point of insertion are shifted up. Thus, no
elements are overwritten.
2. boolean addAll(int index, Collection c)
Inserts all elements of c into the invoking list at the index passed in index.
Any pre-existing elements at or beyond the point of insertion are shifted up.
Thus, no elements are overwritten. Returns true if the invoking list changes
and returns false otherwise.
3. Object get(int index)
Returns the object stored at the specified index within the invoking
collection.
4. int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not
an element of the list, .1 is returned.
5. int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not
an element of the list, .1 is returned.
6. ListIterator listIterator( )
Returns an iterator to the start of the invoking list.
7. ListIterator listIterator(int index)
Returns an iterator to the invoking list that begins at the specified index.
8. Object remove(int index)
Removes the element at position index from the invoking list and returns
the deleted element. The resulting list is compacted. That is, the indexes of
subsequent elements are decremented by one
9. Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.
10. List subList(int start, int end)
Returns a list that includes elements from start to end. in the invoking list.
Elements in the returned list are also referenced by the invoking object.
List interface has been implemented in various classes like ArrayList or LinkedList, etc.
For Example: Java Program to demonstrate List Interface.
import java.util.*;
class ListDemo
Set have its implementation in various classes like HashSet, TreeSet, LinkedHashSet.
For Example: Java Program to demonstrate Set Interface.
import java.util.*;
class SetDemo
{
public static void main(String[] args)
{
Set C1 = new HashSet ();
C1.add(2);
C1.add(3);
System.out.println("Set1: " + C1);

Set C2 = new HashSet ();


C2.add(1);
C2.add(2);
System.out.println("Set2: " + C2);

C2.addAll(C1);
System.out.println("Union is: " + C2);
}
}

Navigation: Enumeration, Iterator, ListIterator


Enumeration:
The enumeration() method of java.util.Collections class is used to return an enumeration over the
specified collection. This method takes the collection c as a parameter for which an enumeration
is to be returned. This method returns an enumeration over the specified collection.
Syntax:
public static Enumeration enumeration(Collection C)

For Example: Java program to demonstrate enumeration() method.

import java.util.*;
public class EnumDemo
{
public static void main(String[] argv) throws Exception
{
try
{
List<Integer> arrlist = new ArrayList<Integer>();
arrlist.add(20);
arrlist.add(30);
arrlist.add(40);
System.out.println("List: " + arrlist);
Enumeration<Integer> e = Collections.enumeration(arrlist);
7. void remove():
Removes from the list the last element that was returned by next() or
previous().
8. void set(E e):
Replaces the last element returned by next() or previous() with the specified
element.
9. E next():
Returns the next element in the list and advances the cursor position.

For Example: Java program to accept N students names from user and display them in reverse
order.
import java.util.*;
class ListDemo
{
public static void main(String args[])
{
int i,n;
String sn;
Scanner ob=new Scanner (System.in);
List l=new LinkedList();
System.out.println (“How Many”);
n=ob.nextInt ();
for(i=1;i<=n;i++)
{
System.out.println (“Student Name”);
sn=ob.next();
l.add(sn);
}
ListIterator lst=l.listIterator ();
while(lst.hasPrevious())
{
sn=(String)lst.previous();
}
}
}

Classes: LinkedList, ArrayList, Vector, HashSet


LinkedList:
The LinkedList class extends AbstractSequentialList and implements the List interface. It
provides a linked-list data structure.
The LinkedList class supports two constructors.
➢ LinkedList( ) : Builds an empty linked list:
{
int i,n;
String sn;
Scanner ob=new Scanner (System.in);
List l=new LinkedList ();
System.out.println ("How Many");
n=ob.nextInt ();
for(i=1;i<=n;i++)
{
System.out.println ("Enter Data");
sn=ob.next();
l.add(sn);
}
System.out.println ("Entered Data " + l);
}
}

ArrayList:
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports
dynamic arrays that can grow as needed. Standard Java arrays are of a fixed length. After arrays
are created, they cannot grow or shrink, which means that user must know in advance how many
elements an array will hold. Array lists are created with an initial size. When this size is
exceeded, the collection is automatically enlarged. When objects are removed, the array may be
shrunk.
The ArrayList class supports three constructors.
➢ ArrayList( ) : Builds an empty array list.
➢ ArrayList(Collection c) : Builds an array list that is initialized with the elements of the
collection c.
➢ ArrayList(int capacity) : Builds an array list that has the specified initial capacity. The
capacity is the size of the underlying array that is used to store the elements. The capacity
grows automatically as elements are added to an array list.
Sr. No. Methods with Description
1. void add(int index, Object element)
Inserts the specified element at the specified position index in this list.
Throws IndexOutOfBoundsException if the specified index is out of range
(index < 0 || index > size()).
2. boolean add(Object o)
Appends the specified element to the end of this list.
3. boolean addAll(Collection c)
Appends all of the elements in the specified collection to the end of this
list, in the order that they are returned by the specified collection's iterator.
Throws NullPointerException if the specified collection is null.
class VectDemo
{
public static void main(String args[])
{
int i,n;
n=args.length;
Vector v=new Vector ();
String str[]=new String[n];
for(i=0;i<n;i++)
{
v.addElement (args[i]);
}

v.copyInto (str);
for(i=0;i<n;i++)
{
if(str[i].endsWith(“.java”)==0)
{
System.out.println(str[i]);
}
}
}
}

Map Classes:
Following are the two main classes of the Map Class:
A) HashMap:
A HashMap contains values based on the key. It implements the Map interface and extends
AbstractMap class. It contains only unique elements. It may have one null key and multiple
null values. It maintains no order.

For Example: Java program to demonstrate HashMap.


import java.util.*;
class TestCollection
{
public static void main(String args[])
{
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet())
while(E.hasMoreElements())
{
String k=(String)E.nextElement();
System.out.println( k + " : " + H.get(k) );
}

Scanner S=new Scanner(System.in);


System.out.println("enter Employee name to search : ");
String Ename=S.next();
E=H.keys();
while(E.hasMoreElements())
{
String s=(String)E.nextElement();

if(Ename.equals(s))
{
System.out.println(s+" value="+H.get(s));
break;
}
}

}
}

Practice Set:
1. Create abstract class Shape with abstract method area().Write a Java program to
calculate are of Rectangle and Triangle.(Inherit Shape class in classes Rectangle and
Triangle )
2. Create a class Teacher(Tid, Tname, Designation, Salary, Subject). Write a Java program
to accept the details of ‘n’ teachers and display the details of teacher who is teaching
Java Subject.(Use array of Object)
3. Create a class Doctor(Dno, Dname, Qualification, Specialization). Write a Java program
to accept the details of ‘n’ doctors and display the details of doctor in ascending order by
doctor name.
4. Write a Java program to accept ‘n’ employee names through command line, Store them
in vector. Display the name of employees starting with character ‘S’.
5. Create a package Mathematics with two classes Maximum and Power. Write a java
program to accept two numbers from user and perform the following operations on it:
a. Find Maximum of two numbers.
b. Calculate the power(XY);

Set A:
1. Write a java program to calculate area of Cylinder and Circle.(Use super keyword)
2. Define an Interface Shape with abstract method area(). Write a java program to calculate
an area of Circle and Sphere.(use final keyword)
3. Define an Interface “Integer” with a abstract method check().Write a Java program to
check whether a given number is Positive or Negative.
4. Define a class Student with attributes rollno and name. Define default and parameterized
constructor. Override the toString() method. Keep the count of Objects created. Create
objects using parameterized constructor and Display the object count after each object is
created.
5. Write a java program to accept ‘n’ integers from the user & store them in an ArrayList
collection. Display the elements of ArrayList collection in reverse order.
Set B:
1. Create an abstract class Shape with methods calc_area() & calc_volume(). Derive two
classes Sphere(radius)& Cone(radius, height) from it. Calculate area and volume of both.
(Use Method Overriding)
2. Define a class Employee having private members-id, name, department, salary. Define
default & parameterized constructors. Create a subclass called Manager with private
member bonus. Define methods accept & display in both the classes. Create n objects of
the manager class & display the details of the manager having the maximum total
salary(salary+bonus).
3. Construct a Linked List containg name: CPP, Java, Python and PHP. Then extend your
program to do the following:
i. Display the contents of the List using an iterator
ii. Display the contents of the List in reverse order using a ListIterator.
4. Create a hashtable containing employee name & salary. Display the details of the
hashtable. Also search for a specific Employee and display salary of that employee.
5. Write a package game which will have 2 classes Indoor & Outdoor. Use a function
display() to generate the list of player for the specific game. Use default & parameterized
constructor.
Set C:
1. Create a hashtable containing city name & STD code. Display the details of the
hashtable. Also search for a specific city and display STD code of that city.
2. Construct a Linked List containing name: red, blue, yellow and orange. Then extend your
program to do the following:
Display the contents of the List using an iterator
Display the contents of the List in reverse order using a ListIterator.
Create another list containing pink & green. Insert the elements of this list between blue
& yellow.
3. Define an abstract class Staff with members name &address. Define two sub classes
FullTimeStaff(Departmet, Salary) and PartTimeStaff(numberOfHours, ratePerHour).
Define appropriate constructors. Create n objects which could be of either FullTimeStaff
or PartTimeStaff class by asking the user’s choice. Display details of FulltimeStaff and
PartTimeStaff.
4. Derive a class Square from class Rectangle. Create one more class Circle. Create an
interface with only one method called area(). Implement this interface in all classes.
Include appropriate data members and constructors in all classes. Write a java program to
accept details of Square, Circle & Rectangle and display the area.
5. Create a package named Series having three different classes to print series:
i. Fibonacci series
ii. Cube of numbers
iii. Square of numbers
Write a java program to generate ‘n’ terms of the above series.

Assignment Evaluation:

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone [ ]

Signature of Instructor
Assignment No. 4 : File and Exception Handling
Exception:
Exceptions are generated when an error condition occur during the execution f a method. It is
possible that a statement might throw more than one kind of exception. Exception can be
generated by Java-runtime system or they can be manually generated by code. Error-Handling
becomes a necessary while developing an application to account for exceptional situations that
may occur during the program execution, such as
a) Run out of memory
b) Resource allocation Error
c) Inability to find a file
d) Problems in Network connectivity

Abnormal condition of a program that terminates its execution is called Ex eption.

Exception Types:
In Java, exception is an event that occurs during the execution of a program and disrupts the
normal flow of the program's instructions. Bugs or errors that we don't want and restrict our
program's normal execution of code are referred to as exceptions.

Exceptions can be categorized into two ways:


1. Built-in Exceptions
o Checked Excepti on
o Unchecked Exception
2. User-Defined Exceptions
BufferedReader br=new BufferedReader (new InputStreamReader
(System.in));
System.out.println (“Enter the Number”);
n=Integer.parseInt (br.readLine ());
a=n%10;
while (n>0)
{
b=n%10;
n=n/10;
}
s=a+b;
System.out.println (“Sum Is “ + s);
}
}

finally Block:
To guarantee that a line of code runs, whether an exception occurs or not, use a finally
block after the try and catch blocks. The code in the finally block will almost always execute,
even if an unhandled exception occurs; in fact, even if a return statement is encountered
Syntax:
try
{
Risky code/ unsafe code block
}
catch (ExceptionClassName exceptionObjectName)
{
Code to resolve problem
}
finally
{
Code that will always execute
}

Example: Java program to demonstrate finally block.


class FinDemo
{
public static void main(String args[])
{
int a=5,b=0,c;
try
{
c=a/b;
ch=nm.charAt(i);
if(!(Character.isLetter(ch)))
{
throw new NameValExc();
flag=0;
}
else
flag=1;
}
if(flag==1)
System.out.println (“Name Is Valid”);
}
catch(NameValExc obj)
{
System.out.println (“Name Is Invalid”);
}
}
}

Example 2: Java program to check given number is valid or not. If it is valid then display its
factors, otherwise display appropriate message.
import java.io.*;
class ZeroNumExc extends Exception{}
class ZeroNumDemo
{
public static void main(String args[])
{
int n,i;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader (System.in));
System.out.println(“Enter a Number”);
n=Integer.parseInt(br.readLine());
if(n==0)
{
throw new ZeroNumExc();
}
else
{
for(i=1;i<n;i++)
{
if(n%i==0)
Byte Stream
Byte Stream classes are used to read bytes from the input stream and write bytes to the
output stream. In other words, w e can say that ByteStream classes read/write the data of 8-bits.
We can store video, audio, characters, etc., by using ByteStream classes. These classes are part
of the java.io package.

The ByteStream classes are divided into two types of classes, i.e., InputStream and
OutputStream. These classes are abstract and the super classes of all the Input/Output stream
classes.

The List of Byte Stream classes are :


Stream class Description
BufferedInputStream Used for Buffered Input Stream.
BufferedOutputStream Used for Buffered Output Stream.
DataInputStream Contains method for reading java standard datatype
An output stream that contain method for writing java
DataOutputStream
standard data type
FileInputStream Input stream that reads from a file
FileOutputStream Output stream that write to a file.
InputStream Abstract class that describe stream input.
OutputStream Abstract class that describe stream output.
PrintStream Output Stream that contain print() and println() method
Example 1: Java program to display the data from a file. (Use command Line argument)

import java.io.*;
class FileRead
{
public static void main (String args[]) throws Exception
{
int b;
FileInputStream fin=new FileInputStream (args[0]);
while((b=fin.read())!=-1)
{
System.out.print ((char)b);
}
fin.close();
}
}
Example 2: Java program to copy the data from one file into another file.
import java.io.*;
class FileReadWrite
{
public static void main (String args[]) throws Exception
{
int b;
FileInputStream fin=new FileInputStream (args[0]);
FileOutputStream fout=new FileOutputStream (args[1]);
while((b=fin.read())!=-1)
{
fout.write(b);
}
fin.close();
fout.close();
}
}

Character Stream Classes:


The java.io package provides CharacterStream classes to overcome the limitations of ByteStream
classes, which can only handle the 8-bit bytes and is not compatible to work directly with the
Unicode characters. CharacterStream classes are used to work with 16-bit Unicode characters.
They can perform operations on characters, char arrays and Strings.
Example 2 : Java program to write data into the file.
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
String data = "This is the data in the output file";
try
{
FileWriter output = new FileWriter("output.txt");
output.write (data);
System.out.println("Data is written to the file.");
output.close ();
}
catch (Exception e)
{
e.getStackTrace ();
}
}
}

File class:
It is related with characteristics of a file such as name, size, location etc.
Syntax:
File f=new File (“Path”);

Methods of File Class:

Method Description

createTempFile(String prefix, It creates an empty file in the default temporary-file directory, using
String suffix) the given prefix and suffix to generate its name.

createNewFile() It atomically creates a new, empty file named by this abstract


pathname if and only if a file with this name does not yet exist.

canWrite() It tests whether the application can modify the file denoted by this
abstract pathname.String[]

canExecute() It tests whether the application can execute the file denoted by this
abstract pathname.
canRead() It tests whether the application can read the file denoted by this
abstract pathname.

isAbsolute() It tests whether this abstract pathname is absolute.

isDirectory() It tests whether the file denoted by this abstract pathname is a


directory.

isFile() It tests whether the file denoted by this abstract pathname is a normal
file.

getName() It returns the name of the file or directory denoted by this abstract
pathname.

getParent() It returns the pathname string of this abstract pathname's parent, or


null if this pathname does not name a parent directory.

toPath() It returns a java.nio.file.Path object constructed from the this abstract


path.

toURI() It constructs a file: URI that represents this abstract pathname.

listFiles() It returns an array of abstract pathnames denoting the files in the


directory denoted by this abstract pathname

getFreeSpace() It returns the number of unallocated bytes in the partition named by


this abstract path name.

list(FilenameFilter filter) It returns an array of strings naming the files and directories in the
directory denoted by this abstract pathname that satisfy the specified
filter.

mkdir() It creates the directory named by this abstract pathname.

Example 1: Java Program to create a new File.

import java.io.*;
class FileDemo
{
public static void main (String args[])
{
try
{
File file = new File ("DYP.txt");
if (file.createNewFile())
{
}
else
{
System.out.println ("The File is not deleted.");
}
}
}

Example 4: Java program to rename a given file.


import java.io.*;
class FileRename
{
public static void main(String args[])
{
File file = new File("oldName");
try
{
file.createNewFile();
}
catch(Exception e)
{
e.getStackTrace();
}
File newFile = new File("newName");
boolean value = file.renameTo(newFile);
if(value)
{
System.out.println("The name of the file is changed.");
}
else
{
System.out.println("The name cannot be changed.");
}
}
}
Practice Set:
1. Write a java program to accept the data from a user and write it into the file.
2. Write a java program to display ASCII values of the characters from a file.
3. Write a java program to count number of digits, spaces and characters from a file.
4. Write a java program to accept a number from user if it is non-zero then check whether it
is Armstrong or not, otherwise throws user defined Exception “Number is Invalid”.
5. Write a java program to check whether given file is hidden or not.
6. Write a java program to display name and size of the given files.

Set A:

1. Write a java program to count the number of integers from a given list.(Use command
line arguments).
2. Write a java program to check whether given candidate is eligible for voting or not.
Handle user defined as well as system defined Exception.
3. Write a java program to calculate the size of a file.
4. Write a java program to accept a number from a user, if it is zero then throw user defined
Exception “Number is Zero”. If it is non-numeric then generate an error “Number is
Invalid” otherwise check whether it is palindrome or not.
5. Write a java program to accept a number from user, If it is greater than 100 then throw
user defined exception “Number is out of Range” otherwise do the addition of digits of
that number. (Use static keyword)

Set B:
1. Write a java program to copy the data from one file into another file, while copying
change the case of characters in target file and replaces all digits by ‘*’ symbol.
2. Write a java program to accept string from a user. Write ASCII values of the characters
from a string into the file.
3. Write a java program to accept a number from a user, if it less than 5 then throw user
defined Exception “Number is small”, if it is greater than 10 then throw user defined
exception “Number is Greater”, otherwise calculate its factorial.
4. Write a java program to display contents of a file in reverse order.
5. Write a java program to display each word from a file in reverse order.

Set C:

1. Write a java program to accept list of file names through command line. Delete the files
having extension .txt. Display name, location and size of remaining files.
2. Write a java program to display the files having extension .txt from a given directory.
3. Write a java program to count number of lines, words and characters from a given file.
4. Write a java program to read the characters from a file, if a character is alphabet then
reverse its case, if not then display its category on the Screen. (whether it is Digit or
Space)
5. Write a java program to validate PAN number and Mobile Number. If it is invalid then
throw user defined Exception “Invalid Data”, otherwise display it.

Assignment Evaluation:

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]


3: Needs Improvement [ ] 4: Complete [ ] 5: WellDone [ ]

Signature of Instructor
Section – II
Python Programming

1
Assignment 1: Introduction to Basic Python

Basic Python:
Python is an interpreted high-level programming language for general-purpose programming. Python
features a dynamic type system and automatic memory management. It supports multiple programming
paradigms, including object-oriented, imperative, functional and procedural, and has a large and
comprehensive standard library.

How to Install Python (Environment Set-up):


In order to become Python developer, the first step is to learn how to install or update Python on a local
machine or computer. Now, we will discuss the installation of Python on windows operating systems.

Visit the link https://www.python.org/downloads/ to download the latest release of Python. In this process,
we will install Python 3.8.6 on our Windows operating system. When we click on the above link, it will
bring us the following page.

Step - 1: Select the Python's version to download.


Click on the download button.

Step - 2: Click on the Install Now

Double-click the executable file, which is downloaded; the following window will open. Select Customize
installation and proceed. Click on the Add Path check box, it will set the Python path automatically.

We can also click on the customize installation to choose desired location and features. Other important
thing is install launcher for the all user must be checked.

2
Python Input and Output:
The functions like input() and print() are widely used for standard input and output operations
respectively.

Python Output Using print() function:


We use the print() function to output data to the standard output device (screen).
For example
>>>print(“Python is very easy”) Output: Python is very easy
>>> a=5
>>> print(“The value of a is “,a) Output: The value of a is 5
In the second print() statement, we can notice that a space was added between the string and the value of
variable a. This is by default. The actual syntax of the print() function is
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects is the value(s) to be printed.
The sep separator is used between the values. It defaults into a space character.
After all values are printed, end is printed. It defaults into a new line.
The file is the object where the values are printed and its default value is sys.stdout (screen).
>>>print(1,2,3,4) output: 1 2 3 4
>>>print(1,2,3,4,sep='*') Output:1*2*3*4
>>>print(1,2,3,4,sep='#',end='&') Output: 1#2#3#4&

Python Input: The function input() is used to accept the input from user Syntax of input function is
input(string)

Eg. >>>num=input(“Enter any number=“)


>>> print(num)
Output: Enter any number=10
10

In python each input is accepted in the form of string. To convert it into number we can use int() or float()
function
Eg. >>>num1=int(input(“Enter any Number”))
>>>num2=float(input(“Enter anyNumber”))

Assignments:

Practice Set:
1. A cashier has currency notes of denomination 1, 5 and 10. Write python script to accept the amount to
be withdrawn from the user and print the total number of currency notes of each denomination the
cashier will have to give.
2. Write a python script to accepts annual basic salary of an employee and calculates and displays the
Income tax as per the following rules.
Basic: < 2,50,000 Tax = 0
Basic: 2,50,000 to 5,00,000 Tax = 10%
8
Basic: > 5,00,000 Tax = 20
3. Write python script to accept the x and y coordinate of a point and find the quadrant in which the
point lies.
4. Write a python script to accept the cost price and selling price from the keyboard. Find out if the
seller has made a profit orloss and display how much profit or loss has been made.

Set A:

1. Write python script to calculate sum of digits of a given input number.


2. Write python script to check whether a input number is Armstrong number or not.
3. Write python script to check whether a input number is perfect number of not.
4. Write a program to calculate XY
5. Write a program to check whether a input number is palindrome or not.
6. Write a program to calculate sum of first and last digit of a number.

Set B:

1. Write a program to accept a number and count number of even, odd, zero digits within that number.
2. Write a program to accept a binary number and convert it into decimal number.
3. Write a program which accepts an integer value as command line and print “Ok” if value is between 1 to
50 (both inclusive) otherwise it prints ”Out of range”
4. Write a program which accept an integer value ‘n’ and display all prime numbers till ‘n’.
5. Write python script to accept two numbers as range and display multiplication table of all numbers within
that range.

Set C:
1. Write a python script to generate the following pattern upto n lines
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1

Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Need Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

9
Replace and Resize part of the list:
It’s also possible to replace a bigger chunk with a smaller number of items:
>>>L1=[10,20,30,40,50,60]
>>>L1[:3]=[1]
>>>print(L1) #[1,40,50,60]
We can also replace part of list with bigger chunk
>>>L1=[10,20,30,40,50,60]
>>>L1[:3]=[6,7,8,9,25]
>>>print(L1) #[6,7,8,9,25,40,50,60]
Slice Deletion:
We can use del statement to remove a slice out of a list:
>>>L1=[10,20,30,40,50,60]
>>>del L1[2:5]
>>>print (L1) #[10,20,60]
➢ We can also provide step parameter to slice and remove each n-th element:
>>>L1=[10,20,30,40,50,60,70,80]
>>>del L1[ : : 2]
>>>print(L1) #[20,40,60,80]

Assignments:

Practice Set
1. Write a python script to create a list and display the list element in reverse order
2. Write a python script to display alternate characters of string from both the direction.
3. Write a python program to count vowels and consonants in a string.

Set A
1. Write a python script which accepts 5 integer values and prints “DUPLICATES” if any of the
values entered are duplicates otherwise it prints “ALL UNIQUE”. Example: Let 5 integers are (32,
45, 90, 45, 6) then output “DUPLICATES” to be printed.
2. Write a python script to count the number of characters (character frequency) in a string. Sample
String : google.com'. Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
3. Write a Python program to remove the characters which have odd index values of a given string.
4. Write a program to implement the concept of stack using list
5. Write a Python program to get a string from a given string where all occurrences of its first char
have been changed to '$', except the first char itself. Sample String: 'restart' Expected Result :
'resta$t'

Set B

1. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
If the string length is less than 2, return instead of the empty string.
Sample String : 'General12'
Expected Result : 'Ge12'
Sample String : 'Ka'
Expected Result : 'KaKa'
Sample String : ' K'

17
Expected Result : Empty String

2. Write a Python program to get a single string from two given strings, separated by a space and
swap the first two characters of each string.
Sample String : 'abc', 'xyz'
Expected Result : 'xycabz'
3. Write a Python program to count the occurrences of each word in a given sentence.
4. Write a program to implement the concept of queue using list
5. Write a python program to count repeated characters in a string.
Sample string: 'thequickbrownfoxjumpsoverthelazydog'
Expected output:
o4
e3
u2
h2
r2
t2
Set C:

1. Write a binary search function which searches an item in a sorted list. The function should return
the index of element to be searched in the list.

Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Need Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

18
Packing and Unpacking:
In tuple packing, we place value into a new tuple while in tuple unpacking we extract those values back
into variables.
Ex >>> t=(101,”Nilesh”,80.78) #tuple packing
>>> (rollno, name, marks)=t #tuple unpacking
>>> print(rollno) # 101
>>>print(name, marks) #Nilesh 80.78

Python Set:
The set in python can be defined as the unordered collection of various items enclosed within the curly
braces. The elements of the set can not be duplicate. The elements of the python set can not be
changed.There is no index attached to the elements of the set, i.e., we cannot directly access any element of
the set by the index. However, we can print them all together or we can get the list of elements by looping
through the set.

Creating a set:
The set can be created by enclosing the comma separated items with the curly braces.
Python also provides the set method which can be used to create the set by the passed sequence.

Creating set using curly brackets:


>>> city={"Pune", "Mumbai", "Nashik"}
>>> print(city) # {'Pune', 'Nashik', 'Mumbai'}
>>> for i in city:
print(i, end=“ “) # Pune Nashik Mumbai
Creating set using set() method:
>>> names=set([“Shubham”, “Nilesh”, “Pranav”])
>>>print(names) #{'Pranav', 'Shubham', 'Nilesh'}

Adding items to the set:


Python provides the add() method which can be used to add some particular item to the set.
>>> names.add("Rajesh")
>>> print(names) #{'Pranav', 'Shubham', 'Rajesh', 'Nilesh'}
To add more than one item in the set, Python provides the update() method.
>>> print(city) #{'Pune', 'Nashik', 'Mumbai'}
>>> city.update(["Jalgaon","Nagpur","Satara"])
>>> print(city)
# {'Satara', 'Jalgaon', 'Pune', 'Mumbai', 'Nagpur', 'Nashik'}
Removing items from the set:
Python provides discard() method which can be used to remove the items from the set.
>>> city.discard("Mumbai")
>>> print(city) # {'Satara', 'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
Python also provide the remove() method to remove the items from the set.
>>> print(city) #{'Satara', 'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
>>> city.remove("Satara")
>>> print(city) #{'Jalgaon', 'Pune', 'Nagpur', 'Nashik'}
We can also use the pop() method to remove the item. However, this method will always remove the first
item.
21
Set A:

1. Write a Python program to find maximum and the minimum value in a set.
2. Write a Python program to add an item in a tuple.
3. Write a Python program to convert a tuple to a string.
4. Write a Python program to create an intersection of sets.
5. Write a Python program to create a union of sets.
6. Write a Python script to check if a given key already exists in a dictionary.
7. Write a Python script to sort (ascending and descending) a dictionary by value.

Set B:
1. Write a Python program to create set difference and a symmetric difference.
2. Write a Python program to create a list of tuples with the first element as the number and second
element as the square of the number.
3. Write a Python program to unpack a tuple in several variables.
4. Write a Python program to get the 4th element from front and 4th element from last of a tuple.
5. Write a Python program to find the repeated items of a tuple.
6. Write a Python program to check whether an element exists within a tuple.
7. Write a Python script to concatenate following dictionaries to create a new one. Sample
Dictionary : dic1={1:10, 2:20} dic2={3:30, 4:40} dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

Set C:
1. Write a Python program to create a shallow copy of sets.
2. Write a Python program to combine two dictionary adding values for common keys.
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})

Evaluation

0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Need Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

27
return n%10+sumofd(n//10)
N=int(input(“Enter any Number =“)) #123
print(“Sum of digits= “,sumofd(N)) #Sum of Digits=7

Unpacking argument lists:


We can use * to unpack the list elements so that all elements of list can be passed as different parameters.
Consider a situation where we have a function that receives four arguments. We want to make call to this
function and we have a list of size 4.
If we simply pass list to the function, the call doesn’t work.
Following program illustrate unpacking of arguments
def myfun(a,b,c,d):
print(a,b,c,d)

L=[1,2,3,4]
myfun(L) #error
myfun(*L) #unpacking of argument using *
output : 1 2 3 4

We use two operators * (for list, string and tuple) and ** (for dictionaries) for unpacking of argument
def Myfun(a,b,c):
print(a,b,c)
T=(10,20,30)
D={‘a’:10, ‘b’:20, ‘c’:30}
Myfun(*T) #10 20 30
Myfun(**D) #10 20 30

Packing Arguments:
When we don’t know how many arguments need to be passed to a python function, we can use Packing to
pack all arguments in a tuple.
def myfun(*a):
print(a)
def fun(**d):
print(d)
myfun(10,20,30) #packing to tuple Output: (10, 20, 30)
fun(x=10, y=20) #packing to dictionary Output:{‘x’:10, ‘y’:20}

Generator Function in Python:


If a function contains at least one yield statement, it becomes a generator function.
Both yield and return statement will return some value from a function.
The difference is that, while a return statement terminates a function entirely, yield statement pauses the
function saving all its states and later continues from there on successive calls.
>>> def gen():
n=1
yield n
n=n+1
yield n
n=n+1
yield n
30
6. To use the modules defined inside the package Employees, we must have to import this in our python
source file. Let's create a simple python source file at our home directory (/home) which uses the modules
defined in this package.

Test.py
import Employees
print(Employees.getNames())
Output: ["John", "David", "Nick", "Martin"]

Assignments:

Practice Set:

1. Write a Python program to print Calendar of specific month of input year using calendar module
2. Write a Python script to display datetime in various formats using datetime module

a. Current date and time


b. Current year
c. Month of year
d. Week number of the year
e. Weekday of the week
f. Day of year
g. Day of the month
h. Day of week
3. Write an anonymous function to find area of circle.

Set A:

1. Write a recursive function which print string in reverse order.


2. Write a python script using function to calculate XY
3. Define a function that accept two strings as input and find union and intersection of them.
4. Write a recursive function to calculate sum of digits of a given input number.
5. Write generator function which generate even numbers up to n

Set B:

1. Write a python script to generate Fibonacci terms using generator function.


2. Write python script using package to calculate area and volume of cylinder and cuboids.
3. Write a python script to accept decimal number and convert it to binary and octal number using
function.
33
4. Write a function which print a dictionary where the keys are numbers between 1 and 20
5. (both included) and the values are square of keys
6. Write a generator function which generates prime numbers up to n.

Set C:
1. Write a program to illustrate function duck typing.

Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

34
Example of non parameterized constructor
>>> class myclass:
def init (self):
print("Object is created")

>>> obj=myclass()
Object is created
Operator Overloading in Python:
The same built-in operator shows different behavior for objects of different classes, this is called Operator
Overloading.
Operator Overloading means giving extended meaning beyond their predefined operational meaning.
For example operator + is used to add two integers as well as join two strings and merge two lists.
To perform operator overloading, Python provides some special function or magic function that is
automatically invoked when it is associated with that particular operator.
For example, when we use + operator, the magic method add__ is automatically invoked in which the
operation for + operator is defined.

37
# Python Program illustrate how to overload an binary + operator
class A:
def init (self, a):
self.a = a
def add (self, o):
return self.a + o.a
ob1 = A(10)
ob2 = A(20)
ob3 = A(“DYP")
ob4 = A(“College")
print(ob1 + ob2) #30
print(ob3 + ob4) #DYPCollege

# Python program to overload a comparison operators


class A:
def init (self, a):
self.a = a
def gt (self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
Python Method Overloading:
Like other languages (for example method overloading in C++) do, python does not supports
method overloading.
We may overload the methods but can only use the latest defined method.
def product(a, b):
p=a*b
print(p)
def product(a, b, c):
p = a * b*c
print(p)
product(4, 5) #Error
product(4, 5, 5) #14
Assignments:
Practice Set :
1) Write a python program using simple class having class name as Student.
2) Write a python program for Counting the number of students using more objects of a
class.

38
3) Write a python program for parameterized constructor has multiple parameters along
with the self Keyword.
Set A:

1) Write a Python Program to Accept, Delete and Display students details such as
Roll.No, Name, Marks in three subject, using Classes. Also display percentage of
each student.
2) Write a Python program that defines a class named circle with attributes radius
and center, where center is a point object and radius is number. Accept center and
radius from user. Instantiate a circle object that represents a circle with its center
and radius as accepted input.
3) Write a Python class which has two methods get_String and print_String.
get_String accept a string from the user and print_String print the string in upper
case. Further modify the program to reverse a string word by word and print it in
lower case.
4) Write Python class to perform addition of two complex numbers using binary +
operator overloading.
Set B:
1) Define a class named Rectangle which can be constructed by a length and
width. The Rectangle class has a method which can compute the area and
volume.
2) Write a function named pt_in_circle that takes a circle and a point and returns
true if point lies on the boundry of circle.
3) Write a Python Program to Create a Class Set and Get All Possible Subsets
from a Set of Distinct Integers.
4) Write a python class to accept a string and number n from user and display n
repetition of strings using by overloading * operator.
Set C:
1) Python Program to Create a Class which Performs Basic Calculator Operations.
2) Define datetime module that provides time object. Using this module write a program
that gets current date and time and print day of the week.
Evaluation :
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

39
 Use isinstance() to check an instance’s type: isinstance(obj, int) will be True only
if obj. class is int or some class derived from int.
 Use issubclass() to check class inheritance: issubclass(bool, int) is True since bool is a
subclass of int. However, issubclass(float, int) is False since float is not a subclass of int.
Inheritance is an important aspect of the object-oriented paradigm. Inheritance provides code
reusability to the program because we can use an existing class to create a ne w class instead of
creating it from scratch. In python, a derived class can inherit base class by just mentioning the
base in the bracket after the derived class name. Consider the followingsyntax to inherit a base
class into the derived class.

Syntax is ,

class derived-class (base class):


<class-suite>

A class can inherit multiple classes by mentioning all of them inside the bracket. Consider the
following
Syntax:
class derive-class(<base class 1>, <base class 2>, ...... <base class n>):
<class - suite>

Example :
class Human:
def speak(self):
print("Human Speaking")
#child class Mohan inherits the base class Human

41
def sleep(self):
print("Mohan sleeping")
#The child class Kids inherits another child class Dog
class Kids(Mohan):
def eat(self):
print("Eating Rice ...")
k = Kids()
k.sleep()
k.speak()
k.eat()

Multiple inheritance:
Python provides us the flexibility to inherit multiple base classes in the child class.
Python supports a form of multiple inheritance as well. A class definition with multiple base
classes looks like this:

class DerivedClassName(Base1, Base2, Base3):


<statement-1>
.
.
.
<statement-N>

For most purposes, in the simplest cases, you can think of the search for attributes inherited from
a parent class as depth-first, left-to-right, not searching twice in the same class where there is an
overlap in the hierarchy. Thus, if an attribute is not found in DerivedClassName, it is searched
for in Base1, then (recursively) in the base classes of Base1, and if it was not found there, it was
searched for in Base2, and so on.

In fact, it is slightly more complex than that; the method resolution order changes dynamically to
support cooperative calls to super(). This approach is known in some other multiple-inheritance
languages as call-next-method and is more powerful than the super call found in single-
inheritance languages.

Dynamic ordering is necessary because all cases of multiple inheritance exhibit one or more
diamond relationships (where at least one of the parent classes can be accessed through multiple
paths from the bottommost class). For example, all classes inherit from object, so any case of
multiple inheritance provides more than one path to reach object. To keep the base classes from
being accessed more than once, the dynamic algorithm linearizes the search order in a way that
preserves the left-to-right ordering specified in each class, that calls each parent only once, and
that is monotonic (meaning that a class can be subclassed without affecting the precedence order

43
2) HAS-A Relationship
Composition (HAS-A) simply mean the use of instance variables that are references to other
objects. For example Maruti has Engine, or House has Bathroom.
Let’s understand these concepts with an example of Car class.

 Has-a relationship is composition relationship which is a productive way of code reuse.

Assignments:

Practice Set :
1) Write a python program to demonstrate single inheritance using findArea() function.
2) Write a python program that will show the simplest form of inheritance using info()
function.

SET A:
1) Write a python program to demonstrate multilevel inheritance by using Base class name
as “Team” which inherits Derived class name as “Dev”.
2) Write a python program by considering Baseclass as TeamMember and Derived class as
TeamLeader use multiple inheritance concept to demonstrate the code.
3) Write a python program to make use of issubclass () or isinstance() functions to check the
relationships of two classes and instances.
SET B :

1) Write a python program to inherit (Derived class) “course“ from (base class)
“University” Using hybrid inheritance concept.
2) Write a python program to show the Hierarchical inheritance of two or more classes
named as “Square “ & “ Triangle” inherit from a single Base class as “Area “ .
3) Define a class named Shape and its subclass (Square/Circle). The subclass has an init
function which takes an argument (length/radius). Both classes have an area and volume

47
function which can print the area and volume of the shape where Shape's area is 0 by
default.
4) Python Program to Create a Class in which One Method Accepts a String from
the User and Another method Prints it. Define a class named Country which has
a method called print Nationality. Define subclass named state from Country
which has a method called print State . Write a method to print state, country and
nationality.

SET C :
1) Write a Python Program to depict multiple inheritance when method is overridden in both
classes and check the output accordingly.
2) Write a Python Program to describe a HAS-A Relationship(Composition).

Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of the Instructor

48
Assignment 7: Exception Handling

What is exception?
The exception is an abnormal condition that halts the execution of the program.
An exception can be defined as an abnormal condition in a program resulting in halting of
program execution and thus the further code is not executed.
Python provides us with the way to handle the Exception so that the other part of the code can be
executed without any disruption.
However, if we do not handle the exception, the interpreter doesn't execute all the code that
exists after that.
Common Exceptions:
A list of common exceptions that can be thrown from a normal python program is given below.
1. ZeroDivisionError: Occurs when a number is divided by zero.
2. NameError: It occurs when a name is not found. It may be local or global.
3. IOError: It occurs when Input Output operation fails.
4. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.
5. ArithmeticError: Base class for all errors that occur for numeric calculation.
6. OverflowError: Raised when a calculation exceeds maximum limit for a numeric type.
7. KeyboardInterrupt: Raised when the user interrupts program execution, usually by
pressing Ctrl+c.
8. IndexError: Raised when an index is not found in a sequence.
9. KeyError: Raised when the specified key is not found in the dictionary.
10. IOError: Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.

Exception handling in python:


If the python program contains suspicious code that may throw the exception, we must place that
code in the try block. The try block must be followed with the except statement which contains a
block of code that will be executed if there is some exception in the try block.
Syntax:
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code

49
Declaring multiple exceptions:
The python allows us to declare the multiple exceptions with the except clause.
Declaring multiple exceptions is useful in the cases where a try block throws multiple
exceptions.
Syntax:
try:
#block of code
except (Exception 1, Exception 2,...,Exception n)
#block of code
else:
#block of code

Example Declaring Multiple Exception:


try:
a=10/0
fp=open(“e:\sms2.txt”,”r”)
except (ArithmeticError, IOError):
print "Arithmetic Exception"
else:
print "Successfully Done"

The try-finally Clause:


You can use a finally: block along with a try: block.
The finally block is a place to put any code that must execute, whether the try-block raised an
exception or not.
The syntax of the try-finally statement is this
try:
# block of code
# this may throw an exception
except Exception:
#Exception code
finally:
# block of code
# this will always be executed

Custom Exception:
The python allows us to create our exceptions that can be raised from the program and caught
using the except clause.

51
Raising exceptions:
An exception can be raised by using the raise clause in python. The syntax to use the raise
statement is given below.
Syntax: raise Exception
To raise an exception, raise statement is used. The exception class name follows it.
#Example User defined exception
a=10
b=12
try:
if b>10:
raise Exception
c=a/b
print("c=",c)
except Exception:
print("Error occur")

The assert Statement:


When it encounters an assert statement, Python evaluates the accompanying expression, which is
hopefully true.
If the expression is false, Python raises an Assertion Error exception.
The syntax for assert is −
assert Expression , “Error Msg”
If the assertion fails, Python uses Argument Expression as the argument for the Assertion Error.
Assertion Error exceptions can be caught and handled like any other exception using the try-
except statement, but if not handled, they will terminate the program and produce a traceback.

Assignments:

Practice Set :

1) write a python program that try to access the array element whose index is out of bound
and handle the corresponding exception.
2) Write a Python program to input a positive integer. Display correct message for correct
and incorrect input.

SET A :
1) Define a custom exception class which takes a string message as attribute.
2) Write a function called oops that explicitly raises a IndexError exception when called. Then
write another function that calls oops inside a try/except statement to catch the error.

52
3) Change the oops function you just wrote to raise an exception you define yourself, called
MyError, and pass an extra data item along with the exception. Then, extend the try
statement in the catcher function to catch this exception and its data in addition to
IndexError, and print the extra data item.

SET B :

1) Define a class Date(Day, Month, Year) with functions to accept and display it. Accept
date from user. Throw user defined exception “invalidDateException” if the date is
invalid.
2) Write text file named test.txt that contains integers, characters and float numbers. Write a
Python program to read the test.txt file. And print appropriate message using exception

SET C:

1) Write a function called safe (func, *args) that runs any function using apply, catches any
exception raised while the function runs, and prints the exception using the exc_type and
exc_value attributes in the sys module. Then, use your safe function to run the oops
function you wrote in Exercises 3. Put safe in a module file called tools.py, and pass it
the oops function interactively. Finally, expand safe to also print a Python stack trace
when an error occurs by calling the built-in print_exc() function in the standard traceback
module (see the Python library reference manual or other Python books for details)

2) Change the oops function in question 4 from SET A to raise an exception you define
yourself, called MyError, and pass an extra data item along with the exception. You may
identify your exception with either a string or a class. Then, extend the try statement in
the catcher function to catch this exception and its data in addition to IndexError, and
print the extra data item. Finally, if you used a string for your exception, go back and
change it be a class instance.

Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]

3: Needs Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

53
➢ Fill: By default, the fill is set to NONE. However, we can set it to X or Y to determine
whether the widget contains any extra space.
➢ size: it represents the side of the parent to which the widget is to be placed on the
window.

Example:
# !/usr/bin/python3
from tkinter import *
parent = Tk()
redbutton = Button(parent, text = "Red", fg = "red")
redbutton.pack( side = LEFT)
greenbutton = Button(parent, text = "Black", fg = "black")
greenbutton.pack( side = RIGHT )
bluebutton = Button(parent, text = "Blue", fg = "blue")
bluebutton.pack( side = TOP )
blackbutton = Button(parent, text = "Green", fg = "red")
blackbutton.pack( side = BOTTOM)
parent.mainloop()
Output:

Python Tkinter grid() method:


The grid() geometry manager organizes the widgets in the tabular form. We can specify the rows
and columns as the options in t h e method call. We can also specify the column span (width) or
rowspan(height) of a widget.
This is a more organized way t o place the widgets to the python application. The syntax to use
the grid() is given below.
Syntax: widget.grid(options)
A list of possible options that can be passed inside the grid() method is given below.
➢ Column- The column number in which the widget is to be placed. The leftmost column is
represented by 0.
➢ Columnspan- The width of the widget. It represents the number of columns up to which,
the column is expanded.
➢ ipadx, ipady- It represe n ts the number of pixels to pad the widget inside the widget's
border.
➢ padx, pady- It represents the number of pixels to pad the widget outside the widget's
border.
➢ Row- The row number in which the widget is to be placed. The topmost row is
represented by 0.
➢ Rowspan- The height of the widget, i.e. the number of the row up to w hich the widget is
expanded.

55
Assignments:

Practice Set:
1. Write a Python GUI program to import Tkinter package and create a window and set its
title.
2. Write a Python GUI program to create two buttons exit and hello using tkinter module.
3. Write a Python GUI program to create a Checkbutton widget using tkinter module.
Write a Python GUI program to create three single line text-box to accept a value from
the user using tkinter module.
4. Write a Python GUI program to create three radio buttons widgets using tkinter module.
5. Write a Python GUI program to create a Listbox bar widgets using tkinter module.

Set A:
1. Write Python GUI program to display an alert message when a button is pressed.
2. Write Python GUI program to Create background with changing colors
3. Write a Python GUI program to create a label and change the label font style (font name,
bold, size) using tkinter module.
4. Write a Python GUI program to create a Text widget using tkinter module. Insert a string
at the beginning then insert a string into the current text. Delete the first and last character
of the text.
5. Write a Python GUI program to accept dimensions of a cylinder and display the surface
area and volume of cylinder.
6. Write Python GUI program that takes input string and change letter to upper case when a
button is pressed.

Set B:
1. Write Python GUI program to take input of your date of birth and output your age when a
button is pressed.
2. Write Python GUI program which accepts a sentence from the user and alters it when a
button is pressed. Every space should be replaced by *, case of all alphabets should be
reversed, digits are replaced by ?.
3. Write Python GUI A program to create a digital clock with Tkinter to display the time.
4. Create a program to generate a random password with upper and lower case letters.
5. Write Python GUI program which accepts a number n to displays each digit of number in
words.
6. Write Python GUI program to accept a decimal number and convert and display it to
binary, octal and hexadecimal number.
7. Write Python GUI program to add items in listbox widget to print and delete the selected
items from listbox on button click. Provide two separate button for print and delete.

79
8. Write Python GUI program to add menu bar with name of colors as options to change the
background color as per selection from menu option.
9. Write Python GUI program to accept a number n and check whether it is Prime, Perfect
or Armstrong number or not. Specify three radio buttons.
10. Write a Python GUI program to create a label and change the label font style (font name,
bold, size). Specify separate checkbuttton for each style.
Set C:
1. Write a Python GUI program to implement simple calculator.

Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
3: Need Improvement [ ] 4: Complete [ ] 5: Well Done [ ]

Signature of Instructor

80

You might also like