Raisoni TYBBA (CA) Sem V LabBook of Java & Python
Raisoni TYBBA (CA) Sem V LabBook of Java & Python
Student Name:
College Name:
Academic Year:
CERTIFICATE
Section-II: Python
Reviewed By:
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
Total ( Out of 25 )
Total (Out of 5)
Instructor Signature:
Section-II: Python
6 Inheritance
7 Exception Handling
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:
Data Types:
Type Description(Range)
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.
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);
}
}
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
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);
}
}
}
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();
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:
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();
}
}
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.
...
}
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
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()
C2.addAll(C1);
System.out.println("Union is: " + C2);
}
}
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();
}
}
}
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.
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:
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
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.
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 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.
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();
}
}
File class:
It is related with characteristics of a file such as name, size, location etc.
Syntax:
File f=new File (“Path”);
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.
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.
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.
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.
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.");
}
}
}
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:
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.
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.
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 Input: The function input() is used to accept the input from user Syntax of input function is
input(string)
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:
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
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
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.
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
27
return n%10+sumofd(n//10)
N=int(input(“Enter any Number =“)) #123
print(“Sum of digits= “,sumofd(N)) #Sum of Digits=7
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}
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
Set A:
Set B:
Set C:
1. Write a program to illustrate function duck typing.
Evaluation
0: Not Done [ ] 1: Incomplete [ ] 2: Late Complete [ ]
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
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 [ ]
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 ,
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:
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.
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 [ ]
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.
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
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")
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 [ ]
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:
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