My Document
My Document
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: MongoDB
2 MongoDB Operators
4 MongoDB Cursor
Total (Out of 5)
‘OR’
Section-II: Python
6 Inheritance
7 Exception Handling
Total ( Out of 40 )
Total (Out of 5)
Instructor Signature:
Section – I
Core Java
Assignment Evaluation
Signature of Instructor
Assignment No. 2: Classes, Objects and Methods
Object: Objects have states and behaviors. It is defined as an instance of a class. An object
contains an address and takes up some space in memory. Classes create objects and objects use
methods to communicate between them.
Syntax to create an Object:
An object is created for a class by using the class name and new keyword.
For Example:
ClassName objectName=new ClassName();
Number Obj=new Number();
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
{
..... .....
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 of a method. It is
possible that a statement might throw more than one kind of exception. Exception can be
generated by Java-runtime
runtime system or they can be manually generated by cod
code.
e. Error-Handling
Error
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.
Assignment Evaluation:
Signature of Instructor
Assignment No. 5: Applet, AWT, Event and Swing Programming
Graphical User Interface elements are implemented in two java packages – AWT and
Swing. Swing is the newer package and swing classes are based on AWT classes. In
this assignment we will learn three important concepts of java Applet, AWT, Event and
Swing Programming
APPLET: Applets are small java programs which are executed and displayed in a java
compatible web browser.
Applet Lifecycle
Creating an applet
All applets are subclasses of the java.applet.Applet class. You can also create an
applet by extending the javax.swing.JApplet class. The syntax is:
Set C:
1. Write a java program to accept the details of employee employee eno,ename, sal and
display it on next frame using appropriate even .
2. Write a java program to display at least five records of employee in JTable.( Eno, Ename
,Sal).
3. Write a java Program to change the color of frame. If user clicks on close button then the
position of frame should get change.
4. Write a java program to display following screen.
Assignment Evaluation:
Signature of Instructor
Section-II
MongoDB
Assignment No. 1: MongoDB Basics
1
o Select Install MongoD as a Service MongoDB as a service.
o Select either:
▪ Run the service as Network Service user (Default)
This is a Windows user account that is built-in to Windows
or
▪ Run the service as a local or domain user
▪ For an existing local user account, specify a period (i.e. .) for
the Account Domain and specify the Account Name and
the Account Password for the user.
▪ For an existing domain user, specify the Account Domain,
the Account Name and the Account Password for that user.
o Service Name. Specify the service name. Default name is MongoDB. If you
already have a service with the specified name, you must choose another name.
o Data Directory. Specify the data directory, which corresponds to the --dbpath. If
the directory does not exist, the installer will create the directory and sets the
directory access to the service user.
o Log Directory. Specify the Log directory, which corresponds to the --logpath. If
the directory does not exist, the installer will create the directory and sets the
directory access to the service user.
2
Database, Collection and Documents in MongoDB:
Databases, collections, documents are important parts of MongoDB without them you are not
able to store data on the MongoDB server. A Database contains a collection, and a collection
contains documents and the documents contain data in the form of key-value pair, they are
related to each other.
Database
In MongoDB, a database contains the collections of documents. One can create multiple
databases on the MongoDB server.
Command to view database : >show dbs
It gives list of databases that are present in your MongoDB server.
Command to create a database : >use database_name
This command actually switches you to the new database if the given name does not exist and
if the given name exists, then it will switch you to the existing database. Now at this stage, if
you use the show command to see the database list, you will find that your new database is not
present in that database list because, in MongoDB, the database is actually created when you
start entering data in that database.
Command to check currently selected database : >db
Command to delete database : >db.dropDatabase()
This command drop/delete a database. If you have not selected any database, then by default it
will delete ‘test’ database. To delete specific database first switch to that database using ‘use’
command and then give ‘dropDatabase’ command.
Collection
Collections are just like tables in relational databases, they also store data, but in the form of
documents. A single database is allowed to store multiple collections.
As we know that MongoDB databases are schemaless, it is not necessary in a collection that
the schema of one document is similar to another document. Or in other words, a single
collection contains different types of documents. Create a collection to store documents.
Command to create collection implicitly: >db.collection_name.insertOne({..})
Here, in a single command you can insert a document and create a collection implicitly.
insertOne() function is used to store single document in the specified collection. And in the
curly braces {} we store our data or document.
Command to create collection explicitly: >db.createCollection(“student”)
Command to display the collections from database: >show collections
Command to delete a Collection: >db.student.drop()
Document
In MongoDB, the data records are stored as BSON documents. Here, BSON stands for binary
representation of JSON(JavaScript Object Notation) documents, although BSON contains
more data types as compared to JSON. The document is created using key-value pairs and the
value of the field can be of any BSON type.
Command to insert a single document at a time:
>db.collection_name.insertOne({field1: value1, field2: value2, ...., fieldN: valueN})
Command to insert many documents at a time:
>db.collection_name.insertMany([{document 1},{document 2}…{document N}])
3
Command to query data from MongoDB collection:
>db.collection_name.find(query, projection)
Here the first parameter is query which is optional. It specifies the query selection criteria
using query operators. Second parameter is projection which is also optional, which
specifies the fields return using projection operators. In projection parameter {field:1 or true}
shows that the field is included in result and {field:0 or false} shows that the field is excluded
from result.
Command to display first document of the collection:
>db.collection_name.findOne(query, projection)
Command to display the documents of the collection in a well-formatted way:
>db.collection_name.find().pretty()
Example:
Use the mongo command to connect with a MongoDB database
C:\Program Files\MongoDB\Server\5.0\bin>mongo
Use following command to list out databases that are present in your MongoDB server.
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
This command switches you to the new database which you want to create.
> use mydatabase
switched to db mydatabase
Using following command you can check currently selected database. Before creating
collection and inserting document make sure that currently selected database is your own
database. In MongoDB default database is test.
> db
mydatabase
After this, if you give a command “show dbs”, it will not show your newly created database
because in MongoDB the database is actually created when you start entering data in that
database.
Use following command to create new collection named “student” under database “mydatabase”
and to insert a new document inside it.
>db.student.insertOne({"_id":1, "Sname":"Manisha Kadam", "class":"TYBBA_CA",
"Contact_details":{"e-mail": "[email protected]", "phone":"9876543210"}})
{ "acknowledged" : true, "insertedId" : 1 }
4
Once data will get added inside your database “show dbs” command will list out your newly
created database “mydatabase”.
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
mydatabase 0.000GB
Flexible Schema
Unlike SQL databases, Data in MongoDB has a flexible schema. The documents in the same
collection do not need to have the same set of fields or structure. Common fields in a
collection’s documents may hold different types of data. To change the structure of the
documents in a collection, such as add new fields, remove existing fields, or change the field
values to a new type, update the documents to the new structure.
This flexibility facilitates the mapping of documents to an entity or an object. Each document
can match the data fields of the represented entity, even if the document has substantial variation
from other documents in the collection.
5
i) Embedded Data Model
In this model, you can have (embed) all the related data in a single document, it is also known as
de-normalized data model. Embedding provides better performance for read operations, as well
as the ability to request and retrieve related data in a single database operation. Embedded data
models make it possible to update related data in a single atomic write operation.
For example, assume we are getting the details of students in three different documents namely,
Personal_details, Contact and, Address, you can embed all the three sub documents in a single
one as shown below –
{
_id: <ObjectId101>,
Stud_ID: "S1001",
Personal_details:{
First_Name: "Pramod",
Last_Name: "Mane",
Date_Of_Birth: "1999-07-17"
},
Contact_details: {
e-mail: "[email protected]",
phone: "9876543210"
},
Address: {
city: "Pune",
Area: "Wakad",
State: "Maharashtra"
}
}
6
Contact_details:
{
_id: <ObjectId103>,
studDocID: "ObjectId101",
e-mail: "[email protected]",
phone: "9876543210"
}
Address:
{
_id: <ObjectId104>,
studDocID: " ObjectId101",
city: "Pune",
Area: "Wakad",
State: "Maharashtra"
}
7
Modeling relationships between documents:
One-to-one Relationship:
One-to-Many Relationship:
8
Modeling tree structures in MongoDB:
MongoDB allows different ways to use tree data structures to model large hierarchical or nested
data relationship.
The following example models the tree using Parent References, storing the reference to the
parent category in the field parent:
>db.categories.insertMany( [
{ _id: "MongoDB", parent: "Databases" },
{ _id: "dbm", parent: "Databases" },
{ _id: "Databases", parent: "Programming" },
{ _id: "Languages", parent: "Programming" },
{ _id: "Programming", parent: "Books" },
{ _id: "Books", parent: null }
])
• The query to retrieve the parent of a node is fast and straightforward:
>db.categories.findOne( { _id: "MongoDB" } ).parent
• You can query by the parent field to find its immediate children nodes:
>db.categories.find( { parent: "Databases" } )
This model describes a tree-like structure in MongoDB documents by storing references in the
parent-nodes to children nodes. The Child References pattern stores each tree node in a
document; in addition to the tree node, document stores in an array the id(s) of the node's
children.
9
The following example models the tree using Child References, storing the reference to the
node's children in the field children:
>db.categories.insertMany( [
{ _id: "MongoDB", children: [] },
{ _id: "dbm", children: [] },
{ _id: "Databases", children: [ "MongoDB", "dbm" ] },
{ _id: "Languages", children: [] },
{ _id: "Programming", children: [ "Databases", "Languages" ] },
{ _id: "Books", children: [ "Programming" ] }
])
• The query to retrieve the immediate children of a node is fast and straightforward:
>db.categories.findOne( { _id: "Databases" } ).children
• You can query for a node in the children field to find its parent node as well as its
siblings:
>db.categories.find( { children: "MongoDB" } )
The Child References pattern provides a suitable solution to tree storage as long as no operations
on subtrees are necessary. This pattern may also provide a suitable solution for storing graphs
where a node may have multiple parents.
The following example models the tree using Array of Ancestors. In addition to the
ancestors field, these documents also store the reference to the immediate parent category in the
parent field.
>db.categories.insertMany( [
{ _id: "MongoDB", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" },
{ _id: "dbm", ancestors: [ "Books", "Programming", "Databases" ], parent: "Databases" },
{ _id: "Databases", ancestors: [ "Books", "Programming" ], parent: "Programming" },
{ _id: "Languages", ancestors: [ "Books", "Programming" ], parent: "Programming" },
{ _id: "Programming", ancestors: [ "Books" ], parent: "Books" },
{ _id: "Books", ancestors: [ ], parent: null }
])
• The query to retrieve the ancestors or path of a node is fast and straightforward:
>db.categories.findOne( { _id: "MongoDB" } ).ancestors
• You can query by the field ancestors to find all its descendants:
>db.categories.find( { ancestors: "Programming" } )
The Array of Ancestors pattern provides a fast and efficient solution to find the descendants and
the ancestors of a node by creating an index on the elements of the ancestors field. This
makes Array of Ancestors a good choice for working with subtrees. The Array of
Ancestors pattern is slightly slower than the Materialized Paths pattern but is more
straightforward to use.
10
Model Tree Structures with Materialized Paths
This model describes a tree-like structure in MongoDB documents by storing full relationship
paths between documents.
The Materialized Paths pattern stores each tree node in a document; in addition to the tree node,
document stores as a string the id(s) of the node's ancestors or path. Although the Materialized
Paths pattern requires additional steps of working with strings and regular expressions, the
pattern also provides more flexibility in working with the path, such as finding nodes by partial
paths.
The following example models the tree using Materialized Paths, storing the path in the
field path; the path string uses the comma ‘,’ as a delimiter:
>db.categories.insertMany( [
{ _id: "Books", path: null },
{ _id: "Programming", path: ",Books," },
{ _id: "Databases", path: ",Books,Programming," },
{ _id: "Languages", path: ",Books,Programming," },
{ _id: "MongoDB", path: ",Books,Programming,Databases," },
{ _id: "dbm", path: ",Books,Programming,Databases," }
])
• You can query to retrieve the whole tree, sorting by the field path:
>db.categories.find().sort( { path: 1 } )
• You can use regular expressions on the path field to find the descendants
of Programming:
>db.categories.find( { path: /,Programming,/ } )
• You can also retrieve the descendants of Books where the Books is also at the topmost
level of the hierarchy:
>db.categories.find( { path: /^,Books,/ } )
11
The following example models the tree using Nested Sets:
>db.categories.insertMany( [
{ _id: "Books", parent: 0, left: 1, right: 12 },
{ _id: "Programming", parent: "Books", left: 2, right: 11 },
{ _id: "Languages", parent: "Programming", left: 3, right: 4 },
{ _id: "Databases", parent: "Programming", left: 5, right: 10 },
{ _id: "MongoDB", parent: "Databases", left: 6, right: 7 },
{ _id: "dbm", parent: "Databases", left: 8, right: 9 }
])
You can query to retrieve the descendants of a node:
>var databaseCategory = db.categories.findOne( { _id: "Databases" } );
>db.categories.find( { left: { $gt: databaseCategory.left }, right: { $lt: databaseCategory.right } } );
The Nested Sets pattern provides a fast and efficient solution for finding subtrees but is
inefficient for modifying the tree structure. As such, this pattern is best for static trees that do not
change.
12
MongoDB Data Types:
MongoDB supports many data types. Some of them are
• String − This is the most commonly used data type to store the data. String in MongoDB
must be UTF-8 valid.
• Integer − This type is used to store a numerical value. Integer can be 32 bit or 64 bit
depending upon your server.
• Boolean − This type is used to store a Boolean (true/ false) value.
• Double − This type is used to store floating point values.
• Arrays − This type is used to store arrays or list or multiple values into one key. The
array is created using square brackets.
• Timestamp − This type is used to store timestamp and value of this data type is 64 bit.
This can be handy for recording when a document has been modified or added.
• Object − This data type is used for embedded documents.
• Null − This type is used to store a Null value.
• Date − This data type is used to store the current date or time in UNIX time format. You
can specify your own date time by creating object of Date and passing day, month, year
into it.
• Object ID − This data type is used to store the document’s ID.
• Binary data − This data type is used to store binary data.
• Code − This data type is used to store JavaScript code into the document.
• Regular expression − This data type is used to store regular expression.
The save() method uses either the insert or the update command internally. If you don't specify
_id in the document then save() method will work same as insert() method. If you specify _id
then it will replace whole data of document containing _id as specified in save() method.
In the following example, save() method performs an insert since the document passed to the
method does not contain the _id field:
>db.student.save({sname: “Vinaya Sane”, percentage:90})
During the insert, the shell will create the _id field with a unique ObjectId value,
The ObjectId values are specific to the machine and time when the operation is run. As such,
your values may differ from those in the example.
13
In the following example, save() performs an update with upsert:true since the document
contains an _id field:
>db.student.save({_id:100, sname: “Vinaya Sane”, percentage:90})
If the _id field holds a value that does not exist in the collection, the update operation results in
an insertion of the document. The results of these operations are identical to an update() method
with the upsert option set to true.
Bulk Insert:
In MongoDB, the Bulk.insert() method is used to perform insert operations in bulk or in other
words it is used to insert multiple documents in one go.
With an unordered operations list, MongoDB can execute in parallel the write operations in the
list and in any order. If the order of operations matter,
use db.collection.initializeOrderedBulkOp() instead.
With an ordered operations list, MongoDB executes the write operations in the list serially.
14
Practice Set:
1. Create a database named ‘Society’. Create collection named ‘Buildings’ in it. This
collection should contain a document. Inside this document, we have a field named
‘committee for buildings’ which contains another document and this document contain
three fields(i.e, Manager, Secretary, Member) with their values.
2. Create a database in Mongo DB called DB. Create a collection Employee in it. Use
Bulk.insert() to insert at least 5 documents. Check if all the documents are inserted
correctly.
3. Create a collection to embed the 3 courses document inside the Institute document like
i. (“Institute_name":
ii. "Contact":
iii. "Address":
iv. "Courses": )
that maintains all the related data in a single document. Courses should contain fields like
Course_id, Course_name & Fees.
Set A:
1. Create a database in Mongo DB called usermanaged, drop it and create it again. Check
which database you are currently in.
2. Create a collection called customers in usermanaged database created and insert the
document below. Check if the document is inserted correctly.
{ "firstName":"John",
"lastName":"West",
"email":"[email protected]",
"phone":"032345432134",
"BusinessType": ["Sell", "Sugar", "Drinks"],
"Reference":100,
"Company":"Coca-Cola"}
Write a MongoDB query to display all the documents in the collection
3. Create a database named ‘tybbaca’. Create collection named ‘Courses’ in it. This
collection should contain a document. Inside this document, we have a field named
‘name’ which contains another document and this document contain three fields (i.e,
first, middle, last) with their values.
Set B:
1. Create a database in Mongo DB called myDatabase. Create a collection student in it. Use
Bulk.insert() to insert at least 5 documents. Check if all the documents are inserted
correctly.
2. Create a collection to embed the 2 address document inside the user document like
(“contact":
"dob":
"name":
"address": )
that maintains all the related data in a single document.
15
3. Write and run mongo DB query to models the following tree using Parent References and
store the reference to the parent category in the field parent
Set C:
1. Write and run mongo DB query to create following tree
For above tree query the parent field to list type of Electronics Gadgets
i) Write and run mongo DB queries to create tree structure with child references and
ancestors for above tree.
ii) Write and run mongo DB query to retrieve the children of Televisions gadgets
iii) Write and run mongo DB query to find parent node and siblings of Laptop
Assignment Evaluation
Signature of Instructor
16
Assignment No. 2 : MongoDB Operators
MongoDB Operators:
Operators are special symbols that tell the compiler or interpreter to carry out specific
mathematical or logical manipulations. Basically, all sorts of operators are available in
MongoDB as we have in other programming languages.
17
a) $eq
Display the students from TYBBA_CA class.
>db.student.find({"class":{$eq:"TYBBA_CA"}})
b) $ne
Display Name of students not having TYBBA_CA class.
> db.student.find({"class":{$ne:"TYBBA_CA"}},{"_id":0, "stud_name":1})
c) $gt
Display the students having percentage greater than 80
>db.student.find({"percentage":{"$gt":80}})
d) $gte
Display the students having percentage greater than or equal to 80
>db.student.find({"percentage":{"$gte":80}})
e) $in
Display the students having percentage either 80 or 90.
>db.student.find({"percentage":{$in:[80,90]}})
f) $nin
Display the students who do not have percentage either 80 or 90.
>db.student.find({"percentage":{$nin:[80,90]}})
These MongoDB operators are used to perform logical operations on the given expressions. They
help to make a decision based on multiple conditions.
Various logical operators in MongoDB are –
Name Description
$and It returns all documents that match the conditions of both expressions.
$or It returns all documents that match the conditions of either expression.
$nor It returns all documents that do not match the conditions of either
expression
$not It inverts the effect of a query expression and returns documents
that do not match the query expression.
a) $and
Display students having percentage less than 80 and class TYBBA_CA
>db.student.find({$and:[{"percentage":{"$lt":80}},{"class":"TYBBA_CA"}]})
b) $or
Display students having percentage 80 or class SYBBA_CA.
>db.student.find({$or:[{"percentage":80},{"class":"SYBBA_CA"}]})
18
c) $nor
Display students not having percentage 80 or class SYBBA_CA.
>db.student.find({$nor:[{"percentage":80},{"class":"SYBBA_CA"}]})
d) $not
Display students not having the class as TYBBA_CA.
>db.student.find({"class":{$not:{$eq:"TYBBA_CA"}}})
The next operators in MongoDB operators are element query operators. There are two operators
under this category – $exists & $type.
Name Description
$exists It returns documents that have a specific field.
$type It returns documents if field is of a specified type.
a) $exists
Display document having “contact” element.
>db.student.find({"contact":{"$exists":true}},{"_id":0})
b) $type
Display documents where “stud_id” is of type “String”.
>db.student.find({"stud_id":{$type:"string"}})
There are operators specified for projections for the documents having arrays. Below are the 3
operators in Array Query Operators –
Name Description
$all It returns documents from a collection if it matches all values in the
specified array.
$size It returns documents from the collection to match an array with the
provided number of elements in it.
$elemMatch It returns documents if they Match more than one component (all
specified $elemMatch conditions) within an array element.
19
>db.classtest.insert({ "testResults" : [{ "subject" : "Maths", "marks" : 95 }, {"subject" :
"Science", "marks" : 80}, {"subject" : "English", "marks" : 80}], "tags" : ["Maths", "Science",
"English" ]})
a) $size
Display documents where there are 3 elements in testResults array.
> db.classtest.find({"testResults":{$size:3}})
b) $all
Display all the documents having Maths and English both in tags.
> db.classtest.find({"tags":{$all:["Maths","English"]}})
c) $elemMatch
Display documents where the subject is Maths and marks are greater than or equal to 95.
> db.classtest.find( { "testResults": { $elemMatch: { "subject" : "Maths", "marks":{$gte:95}}}})
MongoDB provides the functionality to search a pattern in a string during a query using
following symbols.
Document Validation:
To Create a document for the practical life we need to apply the document validators for the
collection, means if we want to create the table with some rules and regulations like this field is
accept only this data type, this field values must met some requirements like this then document
validators are very essential.
MongoDB provides the capability to validate documents during updates and insertions.
Validation rules are specified on a per-collection basis using the validator option, which takes a
document that specifies the validation rules or expressions.
20
Example:
Create a collection name 'address' with the following rules
Field Details
firstname string type
lastname string type
emailId string type must be of tutorialtous.com domain
country string only of (UK,INDIA)
pincode String type min and max chars 5
21
Practice Set:
1) Write and run Mongo DB Query to create inventory collection with the following
documents
{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C"
]}
{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] }
{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] }
{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] }
{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ],
"C" ] }
Query the inventory collection to select all documents where the value of the qty field
equals 20.
Query the inventory collection to select all documents where the tags array equals exactly
the specified array or the tags array contains an element that equals the array [ "A", "B" ].
Set A:
1. Write and run Mongo DB Query to create products collection with the following
documents
([
{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate" : ISODate("2011-05-
14T00:00:00Z"), "spec" : { "ram" : 4, "screen" : 6.5, "cpu" : 2.66 }, "color" : [ "white",
"black" ], "storage" : [ 64, 128, 256 ] },
{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate" : ISODate("2011-09-
01T00:00:00Z"), "spec" : { "ram" : 16, "screen" : 9.5, "cpu" : 3.66 }, "color" : [ "white",
"black", "purple" ], "storage" : [ 128, 256, 512 ] },
{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate" : ISODate("2015-01-
14T00:00:00Z"), "spec" : { "ram" : 12, "screen" : 9.7, "cpu" : 3.66 }, "color" : [ "blue" ],
"storage" : [ 16, 64, 128 ] },
{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate" : ISODate("2020-05-
14T00:00:00Z"), "spec" : { "ram" : 8, "screen" : 9.7, "cpu" : 1.66 }, "color" : [ "white",
"orange", "gold", "gray" ], "storage" : [ 128, 256, 1024 ] },
{ "_id" : 5, "name" : "SmartPhone", "price" : 599, "releaseDate" : ISODate("2022-09-
14T00:00:00Z"), "spec" : { "ram" : 4, "screen" : 9.7, "cpu" : 1.66 }, "color" : [ "white",
"orange", "gold", "gray" ], "storage" : [ 128, 256 ] }
])
select all documents where the price is less than 699 or greater than 799.
22
3. Create a collection named mycol in db and insert 3 documents like:
{
title: "MongoDB Overview",
description: "MongoDB is no SQL database",
by: "M.Sc.(CA)",
url: " http://www.dypacs.com ",
tags: ["mongodb", "database", "NoSQL"],
likes: 100
},
{
title: "NoSQL Database",
description: "NoSQL database doesn't have tables",
by: "T.Y.B.C.A (Science)",
url: "http://www.dypacs.com",
tags: ["mongodb", "database", "NoSQL"],
likes: 20,
comments: [
{
user:"user1",
message: "My first comment",
dateCreated: new Date(2021-11-10),
like: 10
}
]
}
Set B:
1. Write MongoDB query for above collection to find all the tutorials written by ‘M. Sc.
(CA)’ and whose title is 'MongoDB Overview'.
2. Write MongoDB query for above collection to show the documents that have likes greater
than 10 and whose title is either 'MongoDB Overview' or by is ‘T.Y.B.C.A (Science)’.
3. Write MongoDB query to create MongoDB posts collection. Each post document has a
title, author and a comments array field. Each element of the comments array represents a
user with some basic information like country, name, isGuest, and country. Insert at least 5
documents in it with your own data. Retrieve all posts where at least one comment is made
by a user with name John.
23
Set C:
1. Write Mongo DB query to create Employee collection which has the Field names of
“Employeeid” and “EmployeeName”. Let’ also assume that we have the following
documents in our collection.
Employee id Employee Name
22 NewMartin
2 Mohan
3 Sameer
4 MohanR
100 Saurabh
6 Gurang
i) Find all Employee Names which have the characters ‘Sa’ in it.
ii) Display all documents in reversed sorted order
2. create a collection projects with required fields and validation as below:
• name — string
• status — enum [inProgress, Completed]
• client — object
("projects", {
validator:{
$jsonSchema: {
bsonType: "object",
required: ["name", "status", "client"],
properties: {
name: {
bsonType: "string",
description: "Project name is required field"
},
status: {
enum: ["inProgress", "Completed"],
description: "Status can only be from one of the enum values"
},
client: {
bsonType: "object",
required: ["name"],
properties:{
name: {
bsonType: "string",
description: "Client name is required"
},
phone: {
bsonType: "string",
maximum: 10,
minimum: 8,
description: "Phone number maximum should be 10 digits long"
24
}
}
}
}
}
}
})
i) Try to inserts values which violates the validation
ii) Try to execute above query with valid values
Assignment Evaluation
Signature of Instructor
25
Assignment No. 3 : Update and Delete operation in MongoDB
The update operations are used to update or modify the existing document in the collection. You
can perform update operations using the following methods provided by the MongoDB:
Method Description
update() It is used to update the values in the existing document in the
collections of MongoDB
updateOne() It is used to update a single document in the collection that satisfies
the given criteria.
It is used to update multiple documents in the collection that satisfy
updateMany() the given criteria.
It is used to replace single document in the collection that satisfy the
replaceOne() given criteria.
It is used to updates the first matched document in the collection that
findOneAndUpdate() matches the selection criteria, it returns document.
It is used to find a matching element, replaces it with the provided
findOneAndReplace() element, and passes the returned doc to the callback.
update()
The update() method updates the values in the existing document in the collections of
MongoDB. When you update your document the value of the _id field remains unchanged. By
default, the db.collection.update() method updates a single document. Include the option multi:
true to update all documents that match the given query. This method can be used for a single
updating of documents as well as multi documents.
Example:
a) Update the name of the student whose name has “Maya” value to “Mayra”.
>db.student.update({stud_name:"Maya"},{$set:{stud_name:"Mayra"}})
Here, the first parameter is the document whose value to be changed {stud_name: “Maya”} and
the second parameter is set keyword means to set(update) the following matched key value with
the older key value. The value of the key must be of the same data type that was defined in the
collection.
b) Update the percentage of the document whose stud_name is “Pooja” to 60.
>db.student.update({stud_name:"Pooja"},{$set:{percentage:60}}
updateOne()
In MongoDB, updateOne() method updates a first matched document within the collection
based on the given query. This method updates one document at a time and can also add new
fields in the given document.
Example:
a) Update the percentage of the student whose name is “Pooja”
>db.student.updateOne({stud_name: "Pooja"}, {$set:{percentage:60}})
26
b) Insert a new field in the document using the updateOne method
>db.student.updateOne({stud_name: "Supriya"}, {$set:{contact:9876543201}})
Here, a new field is added, i.e., contact:9876543201 in the document of a student whose name is
“Supriya”.
updateMany()
The updateMany() method updates all the documents in MongoDB collections that match the
given query. This method can also add new fields in the document. Specify an empty
document({}) in the selection criteria to update all collection documents.
Example:
a) Update all the matched documents whose percentage is greater than 90 to remark: “Excellent”
>db.student.updateMany({percentage:{$gt:90}},{$set:{remark:"Excellent"}})
replaceOne()
The replaceOne() method replaces the first matching document in the collection that matches
the given query, using the replacement document.
Example:
a) Replace the document with stud_id as 3 to new document having stud_name: "Ramesh", class:
"TYBBA_CA", percentage:92.
>db.student.replaceOne({"stud_id":3}, {"stud_id":3, "stud_name": "Ramesh", "class":
"TYBBA_CA", "percentage":92})
findOneAndUpdate()
The findOneAndUpdate() method updates the first matched document in the collection that
matches the selection criteria. If more than one document matched the selection criteria then it
updates only the first matched document. This method will return the original document but if
we want to return the updated document then we have to set the value of the
returnNewDocument parameter to true.
Difference between findOneAndUpdate() and updateOne() is, findOneAndUpdate returns a
document whereas updateOne does not, it just returns the _id if it has created a new document.
Example:
a) Update the percentage of the student whose name is “Smita”
>db.student.findOneAndUpdate ({stud_name: "Smita"}, {$set:{percentage:95}})
b) Update the Science marks of the student whose name is “Pratibha” to 85.
>db.student.findOneAndUpdate({stud_name:"Pratibha"},{$set:{ "Marks.Science":85}})
27
findOneAndReplace()
The findOneAndReplace() method replaces the first matched document based on the given
selection criteria. By default, this method returns the original document. To return the
replacement document, set the value of the returnNewDocument option to true.
Example:
a) Replace the first matched document whose percentage is 90 and return replaced document.
>db.student.findOneAndReplace({percentage:90},{"stud_id":3, "stud_name": "Ramesh",
"class": "TYBBA_CA", "percentage":92},{returnNewDocument:true})
>db.Employee.insert({"emp_name":{"fname":"Varad", "lname":"Mane"},
"emp_details":{"age":30,"contact":11111111,"salary":40000},"dept":"Account","exp_yr":4,"doj
":ISODate(),"points":[6,8]});
>db.Employee.insert({"emp_name":{"fname":"Mahendra", "lname":"Pawar"},
"emp_details":{"age":25,"contact":22222222,"salary":30000},"dept":"HR","exp_yr":3,"doj":ISO
Date(),"points":[2,6,7]});
>db.Employee.insert({"emp_name":{"fname":"Pallavi", "lname":"Patil"},
"emp_details":{"age":29,"contact":33333333,"salary":25000},"dept":"Finance","exp_yr":3,"doj"
:ISODate(),"points":[5,7]});
>db.Employee.insert({"emp_name":{"fname":"Geeta", "lname":"Jagtap"},
"emp_details":{"age":28,"contact":44444444,"salary":30000},"dept":"Developement","exp_yr":
2,"doj":ISODate(),"points":[4,8,6]});
>db.Employee.insert({"emp_name":{"fname":"Samir", "lname":"Jadhav"},
"emp_details":{"age":30,"contact":55555555,"salary":40000},"dept":"Developement","exp_yr":
4,"doj":ISODate(),"points":[8,7]});
28
$currentDate operator:
In the example, we are updating the value of “doj” field of an employee’s document whose first
name is Pallavi.
>db.Employee.updateOne({"emp_name.fname": "Pallavi"}, {$currentDate: {doj: true}})
$inc operator:
In this example, we are updating the salary field of an employee’s document whose name is
Geeta.
>db.Employee.update({"emp_name.fname": "Geeta"}, {$inc: {"emp_details.salary": 5000}})
$max operator:
In this example, we are comparing values (or numbers) of the salary fields with the specified
value, i.e., 40000. Here, the specified value is greater than the current value. So, $max operator
updates the value of the salary field with the help of update() method to 40000.
>db.Employee.update({"emp_name.fname": "Mahendra"}, {$max: {"emp_details.salary":
40000}})
$min operator:
In this example, we are comparing values (or numbers) of the salary fields with the specified
value, i.e, 35000. Here, the specified value is less than the current value. So, $min operator
updates the value of the salary field with the help of update() method to 35000.
>db.Employee.update({"emp_name.fname": "Mahendra"}, {$min: {"emp_details.salary":
35000}})
$mul operator:
In this example, we are multiplying the value of salary field by 2 in the document who matches
the specified condition, i.e., emp_name = “Samir”.
>db.Employee.update({"emp_name.fname": "Samir"}, {$mul: {"emp_details.salary": 2}})
$rename operator:
In this example, we are renaming the name of dept field to section in the employee’s document
whose first name is “Varad”.
>db.Employee.update({"emp_name.fname": "Varad"}, {$rename: {"dept": "section"}})
$setOnInsert:
In this example, we are creating a new document in the Example collection with the help of
update() method by setting the value of an upsert field to true and using $setOneInsert operator
assign the values to embedded fields i.e., in the document.
>db.Employee.update({"emp_name.fname": "Pramod", "exp_yr": 5}, {$setOnInsert:
{"emp_details.age": 27, "emp_details.contact": 66666666}},{upsert: true})
29
MongoDB - array update operators:
MongoDB provides different types of array update operators to update the values of the array
fields in the documents.
Operator Description
$push It adds an item to an array.
$pop It removes the first or last item of an array.
$pull It removes all array elements that match a specified query.
$pullAll It removes all matching values from an array.
$ It acts as a placeholder to update the first element that matches condition.
$addToSet It adds elements to an array only if they do not already exist in the set.
Modifier Description
$each It is used to append multiple values to the array field.
$slice It is used to limit the number of array items and require the use of the $each
modifier.
$sort It is used to order items of the array and require the use of the $each modifier.
$position It is used to add items in an array by specifying position and require the use of the
$each modifier.
30
Appending a single value to an array:
In this example, we are appending a single value, i.e., “C” to an array field, i.e., Language field
in the document whose Cont_name is “Neha”.
> db.Contributor.update({Cont_name: "Neha"}, {$push: {Language: "C"}})
31
c) MongoDB – $pull Operator
$pull operator is used to remove all the instances of the value or the value that matches the
specified condition from the existing array.
32
Using $each modifier with $addToSet operator:
In this example, we are updating a contributor’s document whose Cont_name is Radha
using $each modifier with $addToSet operator. Here, this operation only adds “PHP” in the
Language field and does not add “C” because it is already exists in the Language field.
>db.Contributor.update({Cont_name: "Radha"},{$addToSet: {Language: {$each:
["C","PHP"]}}})
The delete operation is used to delete or remove the documents from a collection. You can
perform delete operations using the following methods provided by the MongoDB:
Method Description
deleteOne() It is used to delete a single document from the collection that satisfies
the given criteria.
deleteMany() It is used to delete multiple documents from the collection that satisfy
the given criteria.
findOneAndDelete() It is used to delete the first matching document in the collection that
matches the filter
remove() It can remove one or all documents that matches the filter.
deleteOne()
The deleteOne() method deletes the first document from the collection that matches the given
selection criteria. It will delete/remove a single document from the collection
Example:
a) Delete the first matched document whose percentage is less than 40.
>db.student.deleteOne({percentage:{$lt:40}})
deleteMany()
In MongoDB, you are allowed to delete the existing documents from the collection
using deleteMany() method. This method deletes multiple documents from the collection
according to the filter.
Example:
a) Delete multiple documents whose percentage is less than 40:
>db.student.deleteMany({percentage:{$lt:40}})
findOneAndDelete()
The findOneAndDelete() method deletes a single document based on the selection criteria from
the collection. It deletes the first document from the collection that matches the given filter query
expression.
33
Difference between findOneAndDelete() and deleteOne() is, findOneAndDelete() deletes single
documents from the collection on the basis of a filter as well as it returns the deleted document
whereas deleteOne() removes single document from the collection.
Example:
a) Find and Delete the first student document whose stud_name is “Maya”.
>db.student.findOneAndDelete({stud_name:"Maya"})
remove()
The remove() method removes documents from the database. It can remove one or all
documents from the collection that matches the given query expression. If you pass an empty
document({}) in this method, then it will remove all documents from the specified collection.
Example:
a) Remove all the documents whose stud_name is “Pooja”.
>db.student.remove({stud_name: "Pooja"})
DropMongoDB collection
In MongoDB, drop() method is used to drop a collection from a database. It completely removes
a collection from the database and does not leave any indexes associated with the dropped
collections.
Example:
>db.student.drop()
It will return true if student collection is deleted successfully.
34
Practice Set:
For a collection “College” created in a database containing documents with fields
{College_id, College_name, Faculty, Subjects, Salary}
With multiple documents
1. Update subject allocated to given faculty
2. Increase salary by Rs. 1000 of all faculty
3. Display all updated documents
Set A:
Consider a collection "User" which contains documents with the same structure like this
one:
{
"_id" : ObjectId("57cc58333d496dc219c09c2c"),
"firstname" : "Ninad",
"lastname" : "Nikam",
"email" : "[email protected]",
"password" : "d9729feb74992cc3482b350163a1a010",
"last_login" : "2015-01-07",
"note" : "Always pays in time, very good customer!",
"address" :
{
"country" : "India",
"street" : "Nagar Road",
"zip" : "62717"
}
}
1. Replace a single existing document entirely with other data
2. Replace the document for current firstname field that you have taken in your document
3. Insert some other similar documents in it.
Set B:
In above Collection
1. Finds the first document whose firstname field is equal "Ninad" and updates the lastname
field to "Patil".
2. Update multiple fields of a document.
3. Increase the zip code of a user by one.
Set C:
Consider the following document in the students collection whose grades element value
is an array of embedded documents:
{
_id: 4,
grades: [
35
{ grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 5 },
{ grade: 85, mean: 85, std: 8 }
]
}
1. Update the std field of the first array element that matches the grade equal to 85
2. Delete array element with grade 80
Assignment Evaluation
Signature of Instructor
36
Assignment No. 4: MongoDB Cursor
Cursor in MongoDB:
In MongoDB, when the find() method is used to find the documents present in the given
collection, then this method returned a pointer which will points to the documents of the
collection, now this pointer is known as cursor. Or in other words we can say that a cursor is a
pointer, and using this pointer we can access the document. By default, cursor iterates
automatically, but you can iterate a cursor manually also.
To display all the documents present in the student collection we use following query
>db.student.find().pretty()
This find() method return a cursor which contain all documents present in the student collection.
In MongoDB, the find() method return the cursor, now to access the document we need to iterate
the cursor. In the mongo shell, if the cursor is not assigned to a var keyword then the mongo
shell automatically iterates the cursor up to 20 documents. MongoDB also allows you to iterate
cursor manually. So, to iterate a cursor manually simply assign the cursor return by the find()
method to the var keyword Or JavaScript variable.
Example:
>var mycursor = db.student.find({stud_name: "Supriya"}).pretty()
Here, we iterate the cursor manually to find the document whose student name is “Supriya”. So,
we assigned the cursor returned by the find() method to the JavaScript variable(i.e. mycursor).
b) forEach()
We can also use forEach() method to iterate the cursor. This function applies a JavaScript
function to each document from the cursor.
Example:
>var mycursor = db.student.find({stud_name: "Supriya"})
>mycursor.forEach(printjson)
Here, first we store the cursor returned by the find() method in the mycursor variable. Now, we
use forEach() method to iterate the cursor and display the resultant document using printjson.
37
c) toArray()
In mongo shell, you are allowed to iterate the cursor and display the resultant document in the
array using toArray() method.
Example:
>var mycursor = db.student.find()
>var docs = mycursor.toArray()
>var resultdoc = docs[0]
Here, first we assign the returned cursor to the var mycursor, in the next we create an array from
the resultant cursor using toArray() method and assign the result to the var docs. Now we access
the documents according to their index e.g. var resultdoc = docs[0], here we display a document
whose index is 0.
d) count()
To know how many documents are present in a collection use the count() method, which returns
the total number of documents are present in the given collection.
Example:
>db.student.find().count()
e) limit()
The limit() method helps to fetch limited records from a collection. Suppose we have multiple
documents, but we want to have topmost or only 2 documents, then by using the limit() method,
we can achieve that.
Example:
>db.student.find().limit(2)
Here, we only display the first two documents from the student collection.
f) skip()
During the display of documents, we may require to skip few documents due to various reasons.
Method skip() helps to display results after skipping a number of documents.
>db.student.find().skip(2)
Here, it will return the result set after skipping first two documents from student collection.
g) size()
The cursor.size() method will be helpful to return a count of the number of documents which got
as the output from db.collection.find() query after applying any cursor.skip() and cursor.limit()
methods. Basically, it will filter for the given condition and find the size of the cursor.
Example:
>db.student.find({class:"TYBBA_CA"}).size()
h) sort()
Use sort() method to sort the documents. It you want to sort the documents in ascending, then set
the value of the field to 1 and in descending, then set it to -1.
Example:
>db.student.find().sort({stud_id:-1})
Here, we sort all the documents present in the student collection in descending order.
38
i) explain()
Use explain() method to report on the query execution plan for a cursor.
Example:
>db.student.find({stud_id:{$gt:3}}).explain('executionStats')
j) pretty()
Use pretty() method to display the result fetched by a cursor in well-formatted way.
Example:
>db.student.find({stud_id:{$gt:3}}).pretty()
39
Practice Set:
Insert the following data into the “Employee” collection with multiple documents containing
following fields
{
“emp_id”:
"Name" :
"City" :
"Salary" :
}
i) Count all the documents of a collection
ii) Find the details of the top 2 employees living in a particular city.
iii) Skips the first 3 documents from the result and prints the remaining documents.
Set A:
1. For created database warehouse containing a collection of products with multiple
documents having fields {“product_id” : ,"name": ,"brand":, "type": ,"price":,
"warranty_years":, "available": "true"},
i) Check if the cursor object has more documents to return or not
ii) Return the next document in a cursor
iii) Insert a new document having, name = “Cable TV Basic Service Package",
"type" : "tv", "monthly_price" : 50, "term_years" : 2, "cancel_penalty" : 25,
"sales_tax" : "true", "additional_tariffs" : [ { "kind" : "federal tariff", "amount" : {
"percent_of_service" : 0.06 } }, { "kind" : "misc. tariff", "amount" : 2.25 } ]
2. For above created database
i) sort all the documents present in the products collection in ascending &
descending order
ii) Find how many documents are present in a collection
iii) Display topmost or only 3 documents
3. For above created database
i) Display the result fetched by a cursor in well-formatted way.
ii) Report on the query execution plan for a cursor
iii) Display all document by skipping first
Set B:
1. For created database warehouse containing a collection of products display the
product_id which are not available in warehouse
2. Modify the availability of product having name phone
3. Replace the document with product_id 5 to a new document "name" : "Phone Extended
Warranty", "type" : "warranty", "price" : 38, "warranty_years" : 2, "for" : [ "ac3", "ac7",
"ac9", "qp7", "qp8", "qp9" ]
Set C:
1. For created database warehouse containing a collection of products remove the warranty
of particular product
2. Delete all documents from collection which warranty_years less than 2 years
40
Assignment Evaluation
Signature of Instructor
41
Assignment No. 5 : MongoDB Index and Aggregation
MongoDB Index
Indexes provide users with an efficient way of querying data. When querying data without
indexes, the query will have to search for all the records within a database to find data that match
the query.
In MongoDB, querying without indexes is called a collection scan. A collection scan will:
• Result in various performance bottlenecks
• Significantly slow down your application
Fortunately, using indexes fixes both these issues. By limiting the number of documents to be
queried, you’ll increases the overall performance of the application.
Indexes are special data structures that store a small part of the Collection’s data in a way that
can be queried easily. Indexes store the values of the indexed fields outside the table or
collection and keep track of their location in the disk. These values are used to order the indexed
fields, this ordering helps to perform equality matches efficiently.
Creating indexes
When creating documents in a collection, MongoDB creates a unique index using the _id field.
MongoDB refers to this as the Default _id Index. This default index cannot be dropped from the
collection.
When creating an index, you need to define the field to be indexed and the direction of the key (1
or -1) to indicate ascending or descending order. Another thing to keep in mind is the index
names. By default, MongoDB will generate index names by concatenating the indexed keys with
the direction of each key in the index using an underscore as the separator. For example:
{stud_name: 1} will be created as stud_name_1. The best option is to use the name option to
define a custom index name when creating an index.
42
Let’s create an index using the name field in the student collection and name it as student name
index.
>db.student.createIndex(
{stud_name: 1},
{name: "student name index"}
)
Finding indexes
You can find all the available indexes in a MongoDB collection by using the getIndexes method.
Following command will return all the indexes in a student collection.
>db.student.getIndexes()
The output contains the default _id index and the user-created index student name index.
Dropping indexes
To delete an index from a collection, use the dropIndex method while specifying the index
name to be dropped.
Following command will remove the user-created index with the index name student name
index.
>db.student.dropIndex("student name index")
or
>db.student.dropIndex({stud_name:1})
The dropIndexes command can also drop all the indexes excluding the default _id index.
>db.student.dropIndexes()
The above index will sort the data in ascending order using the stud_name field. You can use
the sort() method to see how the data will be represented in the index.
>db.student.find({},{_id:0}).sort({stud_name:1})
43
Compound index
You can use multiple fields in a MongoDB document to create a compound index. This type of
index will use the first field for the initial sort and then sort by the preceding fields.
>db.student.createIndex({class: 1, percentage: -1})
Multikey index
MongoDB supports indexing array fields. When you create an index for a field containing an
array, MongoDB will create separate index entries for every element in the array. These multikey
indexes enable users to query documents using the elements within the array.
MongoDB will automatically create a multikey index when encountered with an array field
without requiring the user to explicitly define the multikey type.
The above code will automatically create a Multikey index in MongoDB. When you query for a
document using the array field (Sem_Marks), MongoDB will search for the first element of the
array defined in the find() method and then search for the whole matching query.
44
Geospatial Index
MongoDB provides two types of indexes to increase the efficiency of database queries when
dealing with geospatial coordinate data:
• 2d indexes that use planar geometry which is intended for legacy coordinate pairs used in
MongoDB 2.2 and earlier.
• 2dsphere indexes that use spherical geometry.
>db.<collection_name>.createIndex( { <location Field> : "2dsphere" } )
Text index
The text index type enables you to search the string content in a collection.
>db.<collection_name>.createIndex( { <Index Field>: "text" } )
Hashed index
MongoDB Hashed index type is used to provide support for hash-based sharding functionality.
This would index the hash value of the specified field.
>db.<collection_name>.createIndex( { <Index Field> : "hashed" } )
Here, if you create an index using the remark field, it will index only three documents as the
remark field is present only in three documents.
Partial index
The partial index functionality allows users to create indexes that match a certain filter condition.
Partial indexes use the partialFilterExpression option to specify the filter condition.
>db.student.createIndex({stud_name:1},
{partialFilterExpression: {percentage: { $gte: 80}}})
Here, command will create an index for the stud_name field but will only include documents in
which the value of the percentage field is greater than or equal to 80.
Unique index
The unique property enables users to create a MongoDB index that only includes unique values.
This will:
• Reject any duplicate values in the indexed field
• Limit the index to documents containing unique values
>db.student.createIndex({stud_name:1},{unique: true})
Here, created index will limit the indexing to documents with unique values in the stud_name
field.
45
Aggregation in MongoDB
In MongoDB, aggregation operations process the data records/documents and return computed
results. It collects values from various documents and groups them together and then performs
different types of operations on that grouped data like sum, average, minimum, maximum, etc to
return a computed result.
1. Aggregation pipeline
2. Map-reduce function
3. Single-purpose aggregation
Aggregation pipeline
In MongoDB, the aggregation pipeline consists of stages and each stage transforms the
document. It is a multi-stage pipeline, so in each state, the documents taken as input and produce
the resultant set of documents now in the next stage(id available) the resultant documents taken
as input and produce output, this process is going on till the last stage.
Operator Description
$match It is used for filtering the documents can reduce the amount of documents that are
given as input to the next stage.
$project It is used to select some specific fields from a collection.
$group It is used to group documents based on some value.
$sort It is used to sort the document that is rearranging them
$skip It is used to skip ‘n’ number of documents and passes the remaining documents
$limit It is used to pass first ‘n’ number of documents thus limiting them.
$unwind It is used to unwind documents that are using arrays i.e. it deconstructs an array
field in the documents to return documents for each element.
$out It is used to write resulting documents to a new collection
Expressions: It refers to the name of the field in input documents for e.g. { $group : { _id :
“$id”, total:{$sum: “$fare”}}} here $id and $fare are expressions.
Here in $group _id is Mandatory field, $out must be the last stage in the pipeline and $sum:1 will
count the number of documents and $sum:”$fare” will give the sum of total fare generated per
id.
46
Accumulators: These are basically used in the group stage
Accumulator Description
sum It sums numeric values for the documents in each group
count It counts total numbers of documents
avg It calculates the average of all given values from all documents
min It gets the minimum value from all the documents
max It gets the maximum value from all the documents
Example:
>db.student.insert({"stud_id":1, "stud_name": "Maya", "age":25,"section": "A",
"subjects":["Python","Java"]});
>db.student.insert({"stud_id":2, "stud_name": "Pooja", "age":20,"section": "B",
"subjects":["PHP"]});
>db.student.insert({"stud_id":3, "stud_name": "Ram", "age":27,"section": "A",
"subjects":["C++","Python","Java"]});
>db.student.insert({"stud_id":4, "stud_name": "Vedant", "age":35,"section": "B",
"subjects":["PHP","Java"]});
>db.student.insert({"stud_id":5, "stud_name": "Supriya", "age":28,"section": "A",
"subjects":["Python","Java","C++","PHP"]});
Displaying the total number of students in both the sections and maximum age from both
section
>db.student.aggregate([{$group: {_id:"$section", total_st: {$sum:1}, max_age:{$max:"$age"} }
}])
In this example, we use $group to group, so that we can count for every other section in the
documents, here $sum sums up the document in each group and $max accumulator is applied on
age expression which will find the maximum age in each document.
Displaying details of students whose age is greater than 30 using match stage
>db.student.aggregate([{$match:{age:{$gt:30}}}])
In this example, we display students whose age is greater than 30. So we use
the $match operator to filter out the documents.
47
Sorting the students information on the basis of age
>db.student.aggregate([{'$sort': {'age': 1}}])
In this example, we are using the $sort operator to sort in ascending order we provide ‘age’:1 if
we want to sort in descending order we can simply change 1 to -1 i.e. ‘age’:-1.
Map Reduce
Map reduce is used for aggregating results for the large volume of data. Map reduce has two
main functions one is a map that groups all the documents and the second one is the
reduce which performs operation on the grouped data.
Syntax:
>db.collectionName.mapReduce(mappingFunction, reduceFunction, {out:'Result'});
Example:
>db.student.insert({"stud_id":1, "stud_name": "Maya", "age":25, "class": "TYBBA_CA",
"percentage":80});
>db.student.insert({"stud_id":2, "stud_name": "Pooja", "age":20, "class": "TYBBA_CA",
"percentage":50});
>db.student.insert({"stud_id":3, "stud_name": "Ram", "age":27, "class": "SYBBA_CA",
"percentage":90});
>db.student.insert({"stud_id":4, "stud_name": "Vedant", "age":35, "class": "SYBBA_CA",
"percentage":85});
>db.student.insert({"stud_id":5, "stud_name": "Supriya", "age":20, "class": "TYBBA_CA",
"percentage":40});
Here, we will create two variables first mapfun which will emit age as a key (expressed as “_id”
in the output) and percentage as value this emitted data is passed to our reducefun, which takes
key and value as grouped data, and then it performs operations over it. After performing
reduction the results are stored in a collection here in this case the collection is Result.
48
To view the output, give following command
>db.Result.find()
Example:
Displaying distinct ages
>db.student.distinct("age")
Here, we use a distinct() method that finds distinct values of the specified field i.e., age.
49
Practice Set:
For a collection, Movies created in your database with fields Movie_id, title, director, actors,
num_of_award, box_office business in crores with multiple documents
i) Find movie which made highest business
ii) Find movies which received maximum awards
iii) Find movies which received no awards
Set A:
For a collection people created in your database containing the following type of documents:
{
"_id": 1,
"person": { name: "John", surname: "Brown" },
"age": 34,
"city": "New York"
}
1. Define, a single field index on the age field and also drop created index
2. Define, a multiple field index on the age field for descending and city field for ascending
order.
3. Write mongo DB queries that will use the index both for retrieving the documents and for
sorting. Also, retrieves all the indexes in the collection.
Set B:
In the collection created in your database you have the following data:
{
_id:
book_title: ,
description: ,
author:,
url:,
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
}
with multiple documents.
1. Display a list stating how many books are written by each author.
2. Gets the maximum likes of the corresponding values from all documents in the
collection for each author.
3. Calculates the average likes of all given values from all documents in the
collection for each author.
Set C:
1. For above collection created in database use map reduce function to
i) Find total likes received to each author.
ii) Calculate total likes received to authors except “Mongo DB” book.
50
Assignment Evaluation
Signature of Instructor
51
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
Step - 3 Installations in Process
Immediate/Interactive mode:
Typing python in the command line will invoke the interpreter in immediate mode. We can directly type in
Python expressions and press enter to get the output.
>>> is the Python prompt. It tells us that the interpreter is ready for our input. Try typing in 1 + 1 and press
enter. We get 2 as the output. This prompt can be used as a calculator. To exit this mode type exit() or
quit() and press enter.
Type the following text at the Python prompt and press the Enter
>>> print "Hello World"
3
2. Script Mode Programming
Invoking the interpreter with a script parameter begins execution of the script and continues until the script
is finished. When the script is finished, the interpreter is no longer active.
Let us write a simple Python program in a script. Python files have extension .py. Type the
following source code in a test.py file −
print"Hello World"
We assume that you have Python interpreter set in PATH variable. Now, try to run this program as follows
$ python test.py
This produces the following result −
Hello, Python!
Python Comments:
In Python, there are two ways to annotate your code.
Single-line comment – Comments are created simply by beginning a line with the hash (#) character, and
they are automatically terminated by the end of line.
For example:
#This would be a comment in Python
Multi-line comment:
Multi lined comment can be given inside triple quotes.
‘’’This is
example of
multiline comments ‘’’
Indentation:
Most of the programming languages like C, C++, Java use braces { } to define a block of code. Python
uses indentation. A code block (body of a function, loop etc.) starts with indentation and ends with the first
unindented line. The amount of indentation is up to you, but it must be consistent throughout that block.
The enforcement of indentation in Python makes the code look neat and clean. This results into Python
programs that look similar and consistent. In Python, indentation is used to declare a block. If two
statements are at the same indentation level, then they are the part of the same block.
Python Numbers: Integers, floating point numbers and complex numbers falls under Python numbers
category. They are defined as int, float and complex class in Python.
Python supports four different numerical types
int (signed integers)
long (long integers, they can also be represented in octal and hexadecimal)
float (floating point real values)
complex (complex numbers)
Python Strings: Strings in Python are identified as a contiguous set of characters represented in the
quotation marks. Python allows for either pairs of single or double quotes.
Example: str=’Hello all’
Python Lists:
Lists are the most versatile of Python's compound data types. A list contains items can be of
different data types separated by commas and enclosed within square brackets ([]).
list_obj=['table', 59 ,2.69,“chair”]
Python Tuples:
A tuple is another sequence immutable data type that is similar to the list. A tuple consists of a number of
values separated by commas and enclosed in parentheses ( ( ) ).
Example:
tuple_obj=(786,2.23, “college” )
Python Dictionary
Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl
and consist of key-value pairs.
Dictionaries are enclosed by curly braces ({ })
Example:dict_obj={'roll_no': 15,'name':’xyz’,'per': 69.88}
Python Operators:
Python language supports the following types of operators.
Arithmetic Operators
Comparison (Relational) Operators
Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Arithmetic, logical, Relational operators supported by Python language are same as other languages like
C,C++.
i. Arithmetic Operators:
The new arithmetic operators in python are,
5
a) ** (Exponent) - Performs exponential (power) calculation on operators
Example: a**b =10 to the power 20
b) // (Floor Division) - The division of operands where the result is the quotient in which
the digits after the decimal point are removed. But if one of the operands is negative, the
result is floored, i.e., rounded away from zero (towards negative infinity)
Example: 9//2 = 4 and 9.0//2.0 = 4.0, -11//3 = -4, -11.0//3 = -4.0
v. Bitwise Operators: The following are bitwise operators in python which are same as in
C,C++. &(bitwise AND), |(bitwise OR) ,^ (bitwise XOR),~ (bitwise NOT ),<<( bitwise left
shift ), >>( bitwise right shift )
Python Loops:
i. while loop:
A while loop statement in Python programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
while expression:
statement(s)
Example:
count=0
while(count <3):
print('The count is:', count)
count= count +1
7
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 or loss 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
Assignment 2: Working with String and List
Python String:
In python string is sequence of characters enclosed either in single, double or triple quotes
Ex. str1=“Python”; str2=‘Hi’; str3=‘‘‘Hi’’’;
String “Python” will be stored from index 0 as shown in following figure
0 1 2 3 4 5
P y t h o n
Types of Strings:
There are two types of Strings supported in Python:
a) Single line String- Strings that are terminated within a single line are known as Single line Strings.
Eg:>>> text1=‘hello’
b) Multi line String: A piece of text that is spread along multiple lines is Multiple line String.
There are two ways to create Multiline Strings:
1. Adding black slash at the end of each line.
Eg: >>> text1='hello\
user'
>>> text1 #output: hellouser
2. Using triple quotation marks:
Eg: >>> str2='''welcome
to
SSSIT'''
>>> print str2
# output: welcome
to
SSSIT
String Operators:
1. + : It is concatenation operator used to connect two strings
Ex: str1=“Hi”; str2=“Hello”;
print(str1+str2) #output: HiHello
print(str2+str1) #output: HelloHi
2. * : It is repetition operator used to connect multiple copies of the same string with itself
Ex: str=“Python”
print(str*3) #output: PythonPythonPython
3. [ ] : It is slice operator used to access character of a string from specific index
Ex: print(str[4]) #output: o
4. [:] :It is called as rang slice operator used to access substring of string from the specific range
10
Ex: print(str[2:4]) #output: th
5. in: It is membership operator which return True if substring is available in specified string, False
otherwise
Ex. str=“Python”;
print(“th” in str) #output: True
print(“a” in str) #output: False
6. not in: it is also membership operator which return true if a substring does not available in
specified string, True otherwise
Ex. print(“Py” not in str) #output: False
print(“xyz” not in str) #output: True
7. r/R: It is used to specify raw string. Raw string are string which treat backslash(\) as a string literal.
Ex. Print(“Hi\nHello”) #output: Hi
Hello
print(r”Hi\nHello”) #output: Hi\nHello
Escape Characters:
Following table is a list of escape or non-printable characters that can be represented with
backslash notation.
An escape character gets interpreted; in a single quoted as well as double quoted strings.
Backslash Notation
\a Bell or alert
\b Backspace
\cx or \C-x Control-x
\f Formfeed
\M-\C-x Meta-Control-x
\n Newline
\r Carriage return
\s Space
\t tab
\nnn Octal notation, where n is in the range 0.7
\v Vertical tab
\x Character x
11
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
12
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Python List:
A list can be defined as a collection of values or items of different types.
The items in the list are separated with the comma (,) and enclosed with the square brackets [].
Ex. >>> List=[10,20,"Hi","Hello",4.5]
>>> print(List) #output: [10, 20, 'Hi', 'Hello', 4.5]
>>> for i in List:
print(i,end=" “) #output: 10 20 Hi Hello 4.5
>>> for i in range(len(List)):
print(List[i],end=" “) #output: 10 20 Hi Hello 4.5
>>>print("%d,%d,%s,%s,%f"%(List[0], List[1], List[2], List[3], List[4]))
#output: 10,20,Hi,Hello,4.500000
List indexing and splitting:
The elements of the list can be accessed using the slice operator [].
The index starts from 0 and goes to length - 1. The first element of the list is stored at the 0th index, the
second element of the list is stored at the 1st index, and so on.
Consider the following example.
13
The negative indices are counted from the right.
The last element (right most) of the list has the index -1,
1, its adjacent left element is present at the index -2
and soo on until the left most element is encountered.
Updating List Values: List values can be updated by using the slice and operator.
Ex. >>>list=[1,2,3,4]
>>>print(list) #: [1,2,3,4]
>>>list[2]=45
>>>print(list) #:[1,2,45,4]
>>>list[1:3]=[55,56]
>>>print(list) #:[1,55,56,4]
14
>>> L1.remove(20)
>>>print(L1) #[10,30]
Python List Built-in functions:
1. cmp(list1, list2): used to compare two list. The function return 0 if both the list are same,-1
otherwise
Ex. >>>L1=[10,20]; L2=[20,30]; L3=[10,20]
>>>cmp(L1,L2) # -1
>>>cmp(L1,L3) #0
2. len(list): It is used to calculate the length of the list.
>>>print(len(L1)) #2
3. max(list): It returns the maximum element of the list.
4. min(list): It returns the minimum element of the list.
Ex. >>>L1=[16,3,24,12]
>>>print(max(L1)) #24
>>>print(min(L1)) #3
5. list(seq): It converts any sequence to the list.
Ex. >>>str=“Python”
>>>L1=list(str)
>>>print(L1) #[‘P’,’y’,’t’,’h’,’o’,’n’]
6. list.count(obj.): It returns the number of occurrences of the specified object in the list.
Ex. >>>L1=[10,20,40,10,20]
>>>print(L1.count(20)) #2
7. list.extend(seq): The sequence represented by the object seq is extended to the list.
Ex. >>> L1=[10,20]; str=“abc”
>>>print(L1) #[10,20]
>>>print(L1.extend(str)) #[10,20,’a’,’b’,’c’]
8. list.index(obj): It returns the lowest index in the list that object appears.
Ex. >>>L1=[10,20,30,20]
>>> print(L1.index(20)) #1
9. list.insert(index, obj): The object is inserted into the list at the specified index.
Ex >>>L1=[10,20,30]
>>>L1.insert(2,40)
>>>print(L1) #[10,20,40,30]
10. list.pop(): It removes and returns the last object of the list.
Ex >>>L1=[10,20,30]
>>print(L1.pop()) #30
11. list.reverse(): It reverses the list.
Ex. >>>print(L1.reverse()) # [30 20 10]
12. list.sort(): It sorts the list
Indexing, Slicing:
we will focus on indexing and slicing operations over Python’s lists.
Indexing:
In Python, list is just like arrays in other scripting languages. It allows you to store set of items in one place
and access an item by its index. In python list, index starts form 0
Ex. City=[‘Pune’, ’Mumbai’, ‘Nasik’, ‘Nagpur’]
Each item in the list have value and index. First value of the list city is ‘Pune’ having index 0, second item
in the list is ‘Mumbai’ having index 1 and so on
15
To accsess the element by index we use square brackets
>>> print(city[0], city[2]) #’Pune’ ‘Nasik’
Negative indexing:
Python list also support negative indexing system.
In negative indexing system last element of the list corresponds to index -1, second last element
correspond to -2 and so on
>>> print(city[-1],city[-2]) # ‘Nagpur’ ‘Nasik’
Indexing not only used for accessing the content of a list but also it is possible to change list content using
an operation
Ex. >>> print(city) #[‘Pune’, ’Mumbai’, ‘Nasik’, ‘Nagpur’]
>>> city[0]=“Pimpri’
>>>print(city) #[‘Pimpri’, ’Mumbai’, ‘Nasik’, ‘Nagpur’]
>>> city[-1]=‘Jalgaon’
>>> print(city) #[‘Pimpri’, ’Mumbai’, ‘Nasik’, ‘Jalgaon’]
Deletion:
We can also easily delete any element from the list by using indexing and del statement
Ex. >>>print(city) #[‘Pune’, ’Mumbai’, ‘Nasik’, ‘Nagpur’]
>>> del city[0]
>>> print(city)#[’Mumbai’, ‘Nasik’, ‘Nagpur’]
>>> del city(-2)
>>> print(city) #[’Mumbai’,‘Nagpur’]
Slice Notation:
As it was shown, indexing allows you to access/change/delete only a single cell of a list.
Using slice notation we can access/change/delete sublist of the list.
The full slice syntax is [start: stop: step]
Start refers to the index of the element which is used as a start of our slice.
Stop refers to the index of the element we should stop just before to finish our slice.
Step allows you to take each nth-element within a start: stop range.
Ex. >>>L=[10,20,30,40,50,60,70,80]
>>>print(L[2:6]) # [30,40,50,60]
>>>print(L[:4]) #[10,20,30,40]
>>>print(L[0:]) #[10,20,30,40,50,60,70,80]
>>>print(L[:]) #[10,20,30,40,50,60,70,80]
>>>print(L[-6:4]) #[30,40]
>>>print(L[-3:]) #[60,70,80]
>>>print(L[1:-1]) #[20,30,40,50,60,70]
>>>print(L[-5:-2]) #[40,50,60]
>>>print(L[1:8:2]) #[20,40,60]
>>>print(L[: :3]) #[10,30,60]
>>>print(L[-2:1:-3]) #[70,40]
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
Assignment 3: Working With Tuples, Sets and Dictionaries
Python Tuple:
A Tuple is a collection of Python objects separated by commas or written in round brackets.
Ex >>>T1=“Hi”, “Hello”
>>>print(T1) #output: ( ‘Hi’, ‘Hello’)
>>>T2=(10,20,4.5,”Monday”)
>>>print(T2) #output: (10,20,4.5,’Mondy’)
Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be
changed unlike lists and tuples use parentheses, whereas lists use square brackets.
>>>print(T1[0]) #’Hi’
>>>print(T1[-1]) #’Hello’
>>>T1[0]=“Bye” #Error
19
Membership operator in and not in can also be used to perform operation on list
Ex. >>>T1=[10,20,30]
>>> print (20 in T1) #True
>>>print (40 in T1) #False
>>>print(50 not in T1) #True
>>>print(30 not in T1) #False
Add Items:
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Remove Items:
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
The del keyword can delete the tuple completely
Ex. >>>T1=(10,20)
>>>del T1
In-Built Tuple Functions:
1. cmp(): Python tuple method cmp() compares elements of two tuples.
syntax: cmp(tuple1, tuple2)
cmp function return 0 if two tuples are same, 1 if elements of first tuple is greater than elements of
second tuple, otherwise -1
2. len(tuple): It is used to calculate the length of the tuple
>>>T1=(10,20,30)
>>>print(len(T1)) #3
3. max(Tuple): It returns the maximum element of the tuple.
4. min(Tuple): It returns the minimum element of the tuple.
>>>print(max(T1) #30
>>>print(min(T1)) #10
5. sum(tuple): Return sum of all elements within tuple
>>> print(sum(T1)) #60
6. all(tuple): it returns True if all the items in the tuple are true, otherwise it returns false. If the tuple is
empty, the function also returns true.
>>>T1=(10,20,30) T2=(10,0,20)
>>>print(all(T1)) #True
>>>print(all(T2)) #False
7. any(): Python any() function accepts iterable (list, tuple, dictionary etc.) as an argument and return true
if any of the element in iterable is true, else it returns false. If iterable is empty then any() method
returns false.
>>>print(any(T1)) #True
8. tuple(seq): It converts any sequence to the tuple.
>>>str=“Python”
>>>T1=tuple(str)
>>>print(T1) #(‘P’,’y’,’t’,’h’,’o’,’n’)
9. tuple.count(obj.): It returns the number of occurrences of the specified object in the tuple.
>>>L1=(10,20,40,10,20)
>>>print(L1.count(20)) #2
10. tuple.index(obj): It retuurns the lowest index in the tuple that object appears.
>>>T1=(10,20,30,20)
>>> print(T1.index(20)) #1
20
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.
The difference_update():
The set difference_update() method modifies the existing set.
If (A – B) is performed, then A gets modified into (A – B), and if (B – A) is performed, then B gets
modified into ( B – A).
Ex. >>>a={1,2,3,4,5}; b={3,4,5,6}
>>>a.difference_update(b)
>>>print(a) #{1,2}
The symmetric_difference():
This in-built function of Python Set helps us to get the symmetric difference between two sets, which is
equal to the elements present in either of the two sets, but not common to both the sets.
>>>print(a.symmetirc_difference(b)) #{1,2,6}
issuperset() in Python:
The issuperset() method returns True if all elements of a set A occupies set B which is passed as an
argument and returns false if all elements of B not present in A.
This means if A is a superset of B then it returns true; else False
Syntax: A.issuperset(B) checks whether A is a superset of B or not. True if A is a superset of B; otherwise
false.
Ex >>>A={1,2,3,4,5}; B={2,3,4}
>>>A.issuperset(B) #True
>>>B.issuperset(A) #False
issubset() in python:
returns true if first set is a subset of seconds set otherwise false
>>> A.issubset(B) #False
>>>B.issubset(A) #True
Python Dictionary:
Dictionary in Python is an unordered collection of items in the form of key-value pair.
Dictionary holds key : value pair.
Each key-value pair in a Dictionary is separated by a colon :, whereas each item is separated by a
‘comma’.
Keys of a Dictionary must be unique and of immutable data type such as Strings, Integers and tuples, but
the values associated with key can be repeated and be of any type.
In Python, a Dictionary can be created by placing sequence of elements within curly {} braces, separated
by ‘comma’.
Ex >>> d={1 : ‘Hi’, 2 : ‘Hello’, 3: ‘Hello’}
>>>print(d) #{1 : ‘Hi’, 2 : ‘Hello’, 3: ‘Hello’}
Updating Dictionary:
You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or
deleting an existing entry
Ex. >>> d={1: “One”, 2: “Two”}
>>>print(d) #{1: 'One', 2: 'Two‘}
>>>d[2]=“Twelve”
>>>print(d) #{1: 'One', 2: 'Tweleve'}
>>>d[3]=“Three”
>>>print(d) #{1: 'One', 2: 'Tweleve', 3: 'Three'}
Properties of Dictionary:
1. In the dictionary, we can not store multiple values for the same keys.
If we pass more than one values for a single key, then the value which is last assigned is
considered as the value of the key.
>>>d={"RN":101,"Name":"Suresh","Marks":80,"Name":"Rajesh"}
25
>>> print(d) #{'Name': 'Rajesh', 'RN': 101, 'Marks': 80}
2. In python, the key cannot be any mutable object.
We can use numbers, strings, or tuple as the key but we can not use any mutable object like the list
as the key in the dictionary.
3. Dictionary keys are case sensitive- Same key name but with the different case are treated as
different keys in Python dictionaries.
Assignments:
Practice Set:
1. Write a Python program to add and remove operation on set.
2. Write a Python program to do iteration over sets.
3. Write a Python program to find the length of a set.
4. Write a Python program to create a tuple with numbers and print one item.
5. Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
26
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
27
Assignment 4: Working with Functions, Modules and Packages
Functions in Python:
Function is named, independent block of statements that perform a specific task and may return a value to
the calling program.
Function is block of reusable code which can be called whenever required
Creating a function:
In python, we can use def keyword to define the function. Syntax is as follows
def my_function():
function-code
return <expression>
The function block is started with the colon (:) and all the same level block statements remain at the same
indentation.
A function can accept any number of parameters that must be the same in the definition and function
calling.
Function calling
In python, a function must be defined before the function calling otherwise the python interpreter gives an
error.
Once the function is defined, we can call it from another function or the python prompt.
To call the function, use the function name followed by the parentheses.
def my_function(): #function code
print(“Python is very esasy”)
my_function() #calling function
#output: Python is very easy
Function Arguments:
You can call a function by using the following types of arguments −
1. Required arguments
2. Keyword arguments
3. Default arguments
4. Variable-length arguments
Recursion:
Recursion is the process of defining something in terms of itself.
The function which calls itself is called as recursion.
A function can call other functions. It is even possible for the function to call itself. These type of construct
are termed as recursive functions.
following is recursive function to calculate sum of digits of a input number
def sumofd(n):
if n==0:
return 0
else
29
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}
Python Modules:
A python module can be defined as a python program file which contains a python code including python
functions, class, or variables. In other words, we can say that our python code file saved with the extension
(.py) is treated as the module. We may have a runnable code inside the python module. Modules in Python
provides us the flexibility to organize the code in a logical way. To use the functionality of one module
into another, we must have to import the specific module.
Example
#displayMsg prints a message to the name being passed.
def displayMsg(name):
print("Hi "+name)
Loading the module in our python code. We need to load the module in our python code to use its
functionality. Python provides two types of statements as defined below.
1. The import statement
2. The from-import statement
Example:
import file;
name = input("Enter the name?")
file.displayMsg(name)
calculation.py:
#place the below code in the calculation.py
def summation(a,b):
return a+b
def multiplication(a,b):
return a*b;
def divide(a,b):
return a/b;
Main.py:
from calculation import summation
#it will import only the summation() from calculation.py
a = int(input("Enter the first number"))
b = int(input("Enter the second number"))
print("Sum=",summation(a,b)) #we do not need to specify the module name while accessing
summation()
31
The datetime Module:
The datetime module enables us to create the custom date objects, perform various operations on dates like
the comparison, etc. To work with dates as date objects, we have to import the datetime module into the
python source code.
Example
import datetime
#returns the current datetime object
print(datetime.datetime.now())
Example
import calendar;
cal = calendar.month(2020,3)
#printing the calendar of December 2018
print(cal)
Packages:
The packages in python facilitate the developer with the application development environment by
providing a hierarchical directory structure where a package contains sub-packages, modules, and sub-
modules. The packages are used to categorize the application level code efficiently.
Let's create a package named Employees in your home directory.
Consider the following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name ITEmployees.py on the path /home/Employees.
ITEmployees.py
def getITNames():
List = ["John", "David", "Nick", "Martin"]
return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a function
getBPONames().
4. Now, the directory Employees which we have created in the first step contains two python modules. To
make this directory a package, we need to include one more file here, that is __init__.py which contains
the import statements of the modules defined in this directory.
__init__.py
from ITEmployees import getITNames
from BPOEmployees import getBPONames
5. Now, the directory Employees has become the package containing two python modules. Here we must
notice that we must have to create __init__.py inside a directory to convert this directory to a package.
32
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
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
Assignment 5: Python Classes and Objects
Python Constructor:
A constructor is a special type of method (function) which is used to initialize the instance members of the
class. Constructors can be of two types.
1. Parameterized Constructor
2. Non-parameterized Constructor
Constructor definition is executed when we create the object of this class.
>>> c1=computer("i5",6)
>>> c1.display()
i5 6
>>> c2=computer("i7",8)
>>> c2.display()
i7 8
36
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 tw
twoo 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
Assignment 6: Inheritance
Introduction:
A language feature would not be worthy of the name “class” without supporting inheritance. The
syntax for a derived class definition looks like this:
The name BaseClassName must be defined in a scope containing the derived class definition. In
place of a base class name, other arbitrary expressions are also allowed. This can be useful, for
example, when the base class is defined in another module:
Execution of a derived class definition proceeds the same as for a base class. When the class
object is constructed, the base class is remembered. This is used for resolving attribute
references: if a requested attribute is not found in the class, the search proceeds to look in the
base class. This rule is applied recursively if the base class itself is derived from some other
class.
Derived classes may override methods of their base classes. Because methods have no special
privileges when calling other methods of the same object, a method of a base class that calls
another method defined in the same base class may end up calling a method of a derived class
that overrides it. (For C++ programmers: all methods in Python are effectively virtual.)
An overriding method in a derived class may in fact want to extend rather than simply replace
the base class method of the same name. There is a simple way to call the base class method
directly: just call BaseClassName.methodname(self, arguments). This is occasionally useful to
clients as well. (Note that this only works if the base class is accessible as BaseClassName in the
global scope.)
40
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
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
object-oriented
oriented paradigm. Inheritance
Inheritanc provides code
reusability to the program because we can use an existing class to create a new 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 cla
class name. Consider the followingsyntaxsyntax 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
class Mohan(Human):
def sleep(self):
print("Mohan sleeping")
m = Mohan()
m.sleep()
m.speak()
Multi-Level inheritance:
Multi-Level inheritance is possible in python like other object
object-oriented
oriented languages. Multi-level
Multi
inheritance is archived when a derived class inherits another derived class. There is no limit on
the number of levels up to which, the multi
multi-level
level inheritance is archived in python.
class class1:
<class-suite>
suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example:
class Human:
def speak(self):
print("Human Speaking")
#The child class Mohan inherits the base class Human
class Mohan(Human):
42
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
of its parents). Taken together, these properties make it possible to design reliable and extensible
classes with multiple inheritances
inheritances.
Syntax:
class Base1:
<class-suite>
class Base2:
<class-suite>
.
class BaseN:
<class-suite>
Example:
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Summation(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
44
Hierarchical Inheritance:
When more than one derived classes are created from a single base this type of inheritance is
called hierarchical inheritance. In this program, we have a parent (base) class and two child
(derived) classes.
Example:
# Base class
class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derived class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()
45
Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.
Example:
# Python program to demonstrate
# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
# Driver's code
object = Student3()
object.func1()
object.func2()
1) IS-A Relationship :
In object-oriented programming, the concept of IS-A is a totally based on Inheritance, which can
be of two types Class Inheritance or Interface Inheritance. It is just like saying "A is a B type of
thing". For example, Apple is a Fruit, Car is a Vehicle etc. Inheritance is uni-directional. For
example, House is a Building. But Building is not a House.
It is a key point to note that you can easily identify the IS-A relationship. Wherever you see an
extends keyword or implements keyword in a class declaration, then this class is said to have IS-A
relationship.
IS-A relationship based on Inheritance, which can be of two types Class Inheritance or
Interface Inheritance.
46
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
We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.
The syntax to use the else statement with the try-except statement is given below.
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed
Python provides the flexibility not to specify the name of exception with the except statement.
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")
Points to remember:
Python facilitates us not to specify the exception with the except statement.
We can declare multiple exceptions in the except statement since the try block may contain the
statements which throw the different type of exceptions.
We can also specify an else block along with the try-except statement which will be executed if
no exception is raised in the try block.
50
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
Assignment 8:: Python GUI Programming using Tkinter
Introduction:
Python provides the standard library Tkinter for creating the graphical user interface for desktop
based applications. Developing desktop based applications with python Tkinter is not a complex
task. An empty Tkinter top-level
level window can be created by usin
using
g the following steps.
1. import the Tkinter module.
2. Create the main application window.
3. Add the widgets like labels, buttons, frames, etc. to the window.
4. Call the main event loop so that the actions can take place on the user's computer screen.
Example
# !/usr/bin/python3
from tkinter import *
#creating the application main window.
top = Tk()
#Entering the event main loop
top.mainloop()
Output:
Tkinter widgets:
There are various widgets like button, label,entry, canvas, checkbutton,Radio button, frame etc. that
are used to build the python GUI applications.
54
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 extrextra 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
Sticky- If the cell is larger than a widget, then sticky is used to specify the position of the
widget
et inside the cell. It may be the concatenation of the sticky letters representing the
position of the widget. It may be N, E, W, S, NE, NW, NS, EW, ES.
Example
# !/usr/bin/python3
from tkinter import *
parent = Tk()
name = Label(parent,text = "Name").grid(row = 0, column = 0)
e1 = Entry(parent).grid(row = 0, column = 1)
password = Label(parent,text = "Password").grid(row = 1, column = 0)
e2 = Entry(parent).grid(row = 1, column = 1)
submit = Button(parent, text = "Submit").grid(row = 4, column = 0)
parent.mainloop()
Output:
56
Output:
Tkinter widgets:
1. Python Tkinter Button:
The button widget is used to add various types of buttons to the python application. Python
allows us to configure the look of the button according to our requirements. Various options
can be set or reset depending upon the requirements. We can also associate a method or
function with a button which is called when the button is pressed. The syntax to use the
button widget is given below
below.
Syntax: W = Button(parent, options)
A list of possible options is given below.
SN Option Description
1 activebackground It represents the background of the button when the mouse hover the
button.
2 activeforeground It represents the font color of the button when the mouse hover the
button.
3 Bd It represents the border width in pixels.
4 Bg It represents the background color of the button.
5 Command It is set to the function call which is scheduled when the function is
called.
6 Fg Foreground color of the button.
7 Font The font of the button text.
8 Height The height of the button. The height is represented in the number of
text lines for the textual lines or the number of pixels for the images.
10 Highlightcolor The color of the highlight when the but button
ton has the focus.
11 Image It is set to the image displayed on the button.
12 justify It illustrates the way by which the multiple text lines are represented. It
is set to LEFT for left justification, RIGHT for the right justification,
and CENTER for the center.
13 Padx Additional padding to the button in the horizontal direction.
14 pady Additional padding to the button in the vertical direction.
15 Relief It represents the type of the border. It can be SUNKEN, RAISED,
GROOVE, and RIDGE.
17 State This option is set to DISABLED to make the button unresponsive. The
ACTIVE represents the active state of the button.
18 Underline Set this option to make the button text underlined.
19 Width The width of the button. It exists as a number of letters for textual
57
buttons or pixels for image buttons.
20 Wraplength If the value is set to a positive number, the text lines will be wrapped
to fit within this length.
Example:
def fun():
messagebox.showinfo("Hello", "Red Button clicked")
b1 = Button(top,text = "Red",command
,command = fun,activeforeground = "red",activebackground
,activebackground = "pink",p
ady=10)
b2 = Button(top, text = "Blue",activeforeground
,activeforeground = "blue",activebackground = "pink",pady=10)
"pink"
b3 = Button(top, text = "Green",activeforeground
,activeforeground = "green",activebackground = "pink",pady
"pink" = 10)
b4 = Button(top, text = "Yellow",activeforeground
,activeforeground = "yellow",activebackground = "pink",pady
"pink" = 10
)
b1.pack(side = LEFT)
b2.pack(side = RIGHT)
b3.pack(side = TOP)
b4.pack(side = BOTTOM)
top.mainloop()
Output:
58
arrow, dot, etc.
4 exportselection The text written inside the entry box will be automatically copied to
the clipboard by default. We can set the exportselection to 0 to not
copy this.
5 fg It represents the color of the text.
6 font It represents the font type of the text.
7 highlightbackground It represents the color to display in the traversal highlight region
when the widget does not have the input focus.
8 highlightcolor It represents the color to use for the traversal highlight rectangle that
is drawn around the widget when it has the input focus.
9 highlightthickness It represents a non-negative value indicating the width of the
highlight rectangle to draw around the outside of the widget when it
has the input focus.
10 insertbackground It represents the color to use as background in the area covered by
the insertion cursor. This color will normally override either the
normal background for the widget.
11 insertborderwidth It represents a non-negative value indicating the width of the 3-D
border to draw around the insertion cursor. The value may have any
of the forms acceptable to Tk_GetPixels.
12 insertofftime It represents a non-negative integer value indicating the number of
milliseconds the insertion cursor should remain "off" in each blink
cycle. If this option is zero, then the cursor doesn't blink: it is on all
the time.
13 insertontime Specifies a non-negative integer value indicating the number of
milliseconds the insertion cursor should remain "on" in each blink
cycle.
14 insertwidth It represents the value indicating the total width of the insertion
cursor. The value may have any of the forms acceptable to
Tk_GetPixels.
15 justify It specifies how the text is organized if the text contains multiple
lines.
16 relief It specifies the type of the border. Its default value is FLAT.
17 selectbackground The background color of the selected text.
18 selectborderwidth The width of the border to display around the selected task.
19 selectforeground The font color of the selected task.
20 show It is used to show the entry text of some other type instead of the
string. For example, the password is typed using stars (*).
21 textvariable It is set to the instance of the StringVar to retrieve the text from the
entry.
22 width The width of the displayed text or image.
23 xscrollcommand The entry widget can be linked to the horizontal scrollbar if we want
the user to enter more text then the actual width of the widget.
59
Example:
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x
).place(x = 30,y = 50)
email = Label(top, text = "Email").place(x
).place(x = 30, y = 90)
password = Label(top, text = "Password"
"Password").place(x = 30, y = 130)
sbmitbtn = Button(top, text = "Submit"
"Submit",activebackground = "pink", activeforeground = "blue").place
(x = 30, y = 170)
e1 = Entry(top).place(x = 80, y = 50))
e2 = Entry(top).place(x = 80, y = 90))
e3 = Entry(top).place(x = 95, y = 130
130)
top.mainloop()
Output:
60
12 xview(index) It is used to link the entry widget to a horizontal scrollbar.
13 xview_scroll(number,what) It is used to make the entry scrollable horizontally.
Example:
# !/usr/bin/python3
from tkinter import *
top = Tk()
61
top.geometry("400x250")
#creating label
uname = Label(top, text = "Username"
"Username").place(x = 30,y = 50)
#creating label
password = Label(top, text = "Password"
"Password").place(x = 30, y = 90)
sbmitbtn = Button(top, text = "Submit"
"Submit",activebackground = "pink", activeforeground = "blue").place
(x = 30, y = 120)
e1 = Entry(top,width = 20).place(x = 100, y = 50)
e2 = Entry(top, width = 20).place(x = 100, y = 90)
top.mainloop()
Output:
62
13 image The image used to represent the checkbutton.
14 justify This specifies the justification of the text if the text contains multiple
lines.
15 offvalue The associated control variable is set to 0 by default if the button is
unchecked. We can change the state of an unchecked variable to some
other one.
16 onvalue The associated control variable is set to 1 by default if the button is
checked. We can change the state of the checked variable to some other
one.
17 padx The horizontal padding of the checkbutton
18 pady The vertical padding of the checkbutton.
19 relief The type of the border of the checkbutton. By default, it is set to FLAT.
20 selectcolor The color of the checkbutton when it is set. By default, it is red.
21 selectimage The image is shown on the checkbutton when it is set.
22 state It represents the state of the checkbutton. By default, it is set to normal.
We can change it to DISABLED to make the checkbutton unresponsive.
The state of the checkbutton is ACTIVE when it is under focus.
24 underline It represents the index of the character in the text which is to be
underlined. The indexing starts with zero in the text.
25 variable It represents the associated variable that tracks the state of the
checkbutton.
26 width It represents the width of the checkbutton. It is represented in the
number of characters that are represented in the form of texts.
27 wraplength If this option is set to an integer number, the text will be broken into the
number of pieces.
Methods:
The methods that can be called with the Checkbuttons are described in the following table.
SN Method Description
1 deselect() It is called to turn off the checkbutton.
2 flash() The checkbutton is flashed between the active and normal colors.
3 invoke() This will invoke the method associated with the checkbutton.
4 select() It is called to turn on the checkbutton.
5 toggle() It is used to toggle between the different Checkbuttons.
Example:
from tkinter import *
top = Tk()
top.geometry("200x200")
checkvar1 = IntVar()
checkvar2 = IntVar()
checkvar3 = IntVar()
chkbtn1 = Checkbutton(top, text = "C", variable = checkvar1, onvalue = 1, offvalue = 0, height = 2,
width = 10)
63
chkbtn2 = Checkbutton(top, text = "C++", variable = checkvar2, onvalue = 1, offvalue = 0, height
= 2, width = 10)
chkbtn3 = Checkbutton(top, text = "Java", variable = checkvar3, onvalue = 1, offvalue = 0, height =
2, width = 10)
chkbtn1.pack()
chkbtn2.pack()
chkbtn3.pack()
top.mainloop()
Output:
SN Option Description
1 activebackground The background color of the widget when it has the focus.
2 activeforeground The font color of the widget text when it has the focus.
3 anchor It represents the exact position of the text within the widget if the
widget contains more space than the requirement of the text. The
default value is CENTER.
4 bg The background color of the widget.
5 bitmap It is used to display the graphics on the widget. It can be set to any
graphical or image object.
6 borderwidth It represents the size of the border.
7 command This option is set to the procedure which must be called every-time
every
when the state of the radiobutton is changed.
8 cursor The mouse pointer is changed to the specified cursor type. It can be
set to the arrow, dot, etc.
9 font It represents the font type of the widget text.
10 fg The normal foreground color of the widge
widget text.
11 height The vertical dimension of the widget. It is specified as the number
of lines (not pixel).
12 highlightcolor It represents the color of the focus highlight when the widget has
the focus.
64
13 highlightbackground The color of the focus highlight when the widget is not having the
focus.
14 image It can be set to an image object if we want to display an image on
the radiobutton instead the text.
15 justify It represents the justification of the multi-line text. It can be set to
CENTER(default), LEFT, or RIGHT.
16 padx The horizontal padding of the widget.
17 pady The vertical padding of the widget.
18 relief The type of the border. The default value is FLAT.
19 selectcolor The color of the radio button when it is selected.
20 selectimage The image to be displayed on the radiobutton when it is selected.
21 state It represents the state of the radio button. The default state of the
Radiobutton is NORMAL. However, we can set this to
DISABLED to make the radiobutton unresponsive.
22 text The text to be displayed on the radiobutton.
23 textvariable It is of String type that represents the text displayed by the widget.
24 underline The default value of this option is -1, however, we can set this
option to the number of character which is to be underlined.
25 value The value of each radiobutton is assigned to the control variable
when it is turned on by the user.
26 variable It is the control variable which is used to keep track of the user's
choices. It is shared among all the radiobuttons.
27 width The horizontal dimension of the widget. It is represented as the
number of characters.
28 wraplength We can wrap the text to the number of lines by setting this option
to the desired number so that each line contains only that number
of characters.
SN Method Description
1 deselect() It is used to turn of the radiobutton.
2 flash() It is used to flash the radiobutton between its active and normal colors few
times.
3 invoke() It is used to call any procedure associated when the state of a Radiobutton is
changed.
4 select() It is used to select the radiobutton.
Example:
from tkinter import *
def selection():
selection = "You selected the option " + str(radio.get())
label.config(text = selection)
top = Tk()
65
top.geometry("300x150")
radio = IntVar()
lbl = Label(text = "Favourite programming language:")
lbl.pack()
R1 = Radiobutton(top, text="C", variable=radio, value=1,command=selection)
R1.pack( anchor = W )
label = Label(top)
label.pack()
top.mainloop()
Output:
66
Example:
from tkinter import *
top = Tk()
top.geometry("140x100")
frame = Frame(top)
frame.pack()
leftframe = Frame(top)
leftframe.pack(side = LEFT)
rightframe = Frame(top)
rightframe.pack(side = RIGHT)
btn1 = Button(frame, text="Submit",, fg="red",activebackground = "red")
btn1.pack(side = LEFT)
btn2 = Button(frame, text="Remove"
"Remove", fg="brown", activebackground = "brown")
btn2.pack(side = RIGHT)
btn3 = Button(rightframe, text="Add"
"Add", fg="blue", activebackground = "blue")
btn3.pack(side = LEFT)
btn4 = Button(leftframe, text="Modify"
"Modify", fg="black", activebackground = "white")
btn4.pack(side = RIGHT)
top.mainloop()
Output:
67
11 selectmode It is used to determine the number of items that can be selected from
the list. It can set to BROWSE, SINGLE, MULTIPLE, EXTENDED.
12 width It represents the width of the widget in characters.
13 xscrollcommand It is used to let the user scroll the Listbox horizontally.
14 yscrollcommand It is used to let the user scroll the Listbox vertically.
Methods: There are the following methods associated with the Listbox.
SN Method Description
1 activate(index) It is used to select the lines at the specified index.
2 curselection() It returns a tuple containing the line numbers of the selected
element or elements, counting from 0. If nothing is selected,
returns an empty tuple.
3 delete(first, last = It is used to delete the lines which exist in the given range.
None)
4 get(first, last = None) It is used to get the list items that exist in the given range.
5 index(i) It is used to place the line with the specified index at the top of
the widget.
6 insert(index, *elements) It is used to insert the new lines with the specified number of
elements before the specified index.
7 nearest(y) It returns the index of the nearest line to the y coordinate of the
Listbox widget.
8 see(index) It is used to adjust the position of the listbox to make the lines
specified by the index visible.
9 size() It returns the number of lines that are present in the Listbox
widget.
10 xview() This is used to make the widget horizontally scrollable.
11 xview_moveto(fraction) It is used to make the listbox horizontally scrollable by the
fraction of width of the longest line present in the listbox.
12 xview_scroll(number, It is used to make the listbox horizontally scrollable by the
what) number of characters specified.
13 yview() It allows the Listbox to be vertically scrollable.
14 yview_moveto(fraction) It is used to make the listbox vertically scrollable by the
fraction of width of the longest line present in the listbox.
15 yview_scroll (number, It is used to make the listbox vertically scrollable by the
what) number of characters specified.
Example:
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("200x250")
lbl = Label(top,text = "A list of favourite countries...")
listbox = Listbox(top)
listbox.insert(1,"India")
listbox.insert(2, "USA")
listbox.insert(3, "Japan")
68
listbox.insert(4, "Austrelia")
lbl.pack()
listbox.pack()
top.mainloop()
Output:
69
set this option to an existing number to specify that nth letter of the string
will be underlined.
17 width It specifies the horizontal dimension of the widget in the number of
characters (not pixel).
18 wraplength We can wrap the text to the number of lines by setting this option to the
desired number so that each line contains only that number of characters.
Example:
from tkinter import *
top = Tk()
top.geometry("100x100")
var = StringVar()
msg = Message( top, text = "Welcome to Javatpoint")
msg.pack()
top.mainloop()
Output:
70
place the widget accordingly.
9 disabledforeground The text color of the widget when the widget is disabled.
10 fg The normal foreground color of the widget.
11 height The vertical dimension of the Menubutton. It is specified as the
number of lines.
12 highlightcolor The highlight color shown to the widget under focus.
13 image The image displayed on the widget.
14 justify This specified the exact position of the text under the widget when the
text is unable to fill the width of the widget. We can use the LEFT for
the left justification, RIGHT for the right justification, CENTER for
the centre justification.
15 menu It represents the menu specified with the Menubutton.
16 padx The horizontal padding of the widget.
17 pady The vertical padding of the widget.
18 relief This option specifies the type of the border. The default value is
RAISED.
19 state The normal state of the Mousebutton is enabled. We can set it to
DISABLED to make it unresponsive.
20 text The text shown with the widget.
21 textvariable We can set the control variable of string type to the text variable so
that we can control the text of the widget at runtime.
22 underline The text of the widget is not underlined by default but we can set this
option to make the text of the widget underlined.
23 width It represents the width of the widget in characters. The default value is
20.
24 wraplength We can break the text of the widget in the number of lines so that the
text contains the number of lines not greater than the specified value.
Example
# !/usr/bin/python3
from tkinter import *
top = Tk()
top.geometry("200x250")
menubutton = Menubutton(top, text = "Language", relief = FLAT)
menubutton.grid()
menubutton.menu = Menu(menubutton)
menubutton["menu"]=menubutton.menu
menubutton.menu.add_checkbutton(label = "Hindi", variable=IntVar())
menubutton.menu.add_checkbutton(label = "English", variable = IntVar())
menubutton.pack()
top.mainloop()
Output:
71
10. Python Tkinter Menu:
The Menu widget is used to create various types of menus (top level, pull down, and pop up) in
the python application. The top--level
level menus are the one which is displayed just under the title
bar of the parent window. We need to create a new instance of the Menu widget and add various
commands to it by using the add() method. The syntax to use the Menu widget is given below.
Syntax: w = Menu(top, options)
A list of possible options is given below.
SN Option Description
1 activebackground The background color of the widget when the widget is under the
focus.
2 activeborderwidth The width of the border of the widget when it is under the mouse. The
default is 1 pixel.
3 activeforeground The font color of the widget when the widget has the focus.
4 bg The background color of the widget.
5 bd The border width of the widget.
6 cursor The mouse pointer is changed to the cursor type when it hovers the
widget. The cursor type can be set to arrow or dot.
7 disabledforeground The font color of the widget when it is disabled.
8 font The font type of the text of the widget.
9 fg The foreground color of the widget.
10 postcommand The postcommand can be set to any of the function which is called
when the mourse hovers the menu.
11 relief The typ
typee of the border of the widget. The default type is RAISED.
12 image It is used to display an image on the menu.
13 selectcolor The color used to display the checkbutton or radiobutton when they
are selected.
14 tearoff By default, the choices in the menu start taking place from position 1.
If we set the tearoff = 1, then it will start taking place from 0th
position.
15 title Set this option to the title of the window if you want to change the
title of the window.
SN Option Description
1 add_command(options) It is used to add the Menu items to the menu.
2 add_radiobutton(options) This method adds the radiobutton to the menu.
3 add_checkbutton(options) This method is used to add the checkbuttons to the menu.
4 add_cascade(options) It is used to create a hierarchical menu to the parent menu by
72
associating the given menu to the parent menu.
5 add_seperator() It is used to add the seperator line to the menu.
6 add(type, options) It is used to add the specific menu item to the menu.
7 delete(startindex, It is used to delete the menu items exist in the specified range.
endindex)
8 entryconfig(index, It is used to configure a menu item identified by the given
options) index.
9 index(item) It is used to get the index of the specified menu item.
10 insert_seperator(index) It is used to insert a seperator at the specified index.
11 invoke(index) It is used to invoke the associated with the choice given at the
specified index.
12 type(index) It is used to get the type of the choice specified by the index.
Example:
top = Tk()
menubar = Menu(top)
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=top.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
top.config(menu=menubar)
top.mainloop()
Output:
73
11. Python Tkinter Text:
The Text widget is used to show the text data on the Python application. However, Tkinter
provides us the Entry widget which is used to implement the single line text box. The Text
widget is used to display the multi-line formatted text with various styles and attributes. The Text
widget is mostly used to provide the text editor to the user. The Text widget also facilitates us to
use the marks and tabs to locate the specific sections of the Text. We can also use the windows
and images with the Text as it can also be used to display the formatted text. The syntax to use
the Text widget is given below.
Syntax: w = Text(top, options)
A list of possible options that can be used with the Text widget is given below.
SN Option Description
1 bg The background color of the widget.
2 bd It represents the border width of the widget.
3 cursor The mouse pointer is changed to the specified cursor type, i.e.
arrow, dot, etc.
4 exportselection The selected text is exported to the selection in the window
manager. We can set this to 0 if we don't want the text to be
exported.
5 font The font type of the text.
6 fg The text color of the widget.
7 height The vertical dimension of the widget in lines.
8 highlightbackground The highlightcolor when the widget doesn't has the focus.
9 highlightthickness The thickness of the focus highlight. The default value is 1.
10 highlighcolor The color of the focus highlight when the widget has the focus.
11 insertbackground It represents the color of the insertion cursor.
12 insertborderwidth It represents the width of the border around the cursor. The default
is 0.
13 insertofftime The time amount in Milliseconds during which the insertion cursor
is off in the blink cycle.
14 insertontime The time amount in Milliseconds during which the insertion cursor
is on in the blink cycle.
15 insertwidth It represents the width of the insertion cursor.
16 padx The horizontal padding of the widget.
17 pady The vertical padding of the widget.
74
18 relief The type of the border. The default is SUNKEN.
19 selectbackground The background color of the selected text.
20 selectborderwidth The width of the border around the selected text.
21 spacing1 It specifies the amount of vertical space given above each line of
the text. The default is 0.
22 spacing2 This option specifies how much extra vertical space to add
between displayed lines of text when a logical line wraps. The
default is 0.
23 spacing3 It specifies the amount of vertical space to insert below each line of
the text.
24 state It the state is set to DISABLED, the widget becomes unresponsive
to the mouse and keyboard unresponsive.
25 tabs This option controls how the tab character is used to position the
text.
26 width It represents the width of the widget in characters.
27 wrap This option is used to wrap the wider lines into multiple lines. Set
this option to the WORD to wrap the lines after the word that fit
into the available space. The default value is CHAR which breaks
the line which gets too wider at any character.
28 xscrollcommand To make the Text widget horizontally scrollable, we can set this
option to the set() method of Scrollbar widget.
29 yscrollcommand To make the Text widget vertically scrollable, we can set this
option to the set() method of Scrollbar widget.
Methods: We can use the following methods with the Text widget.
SN Method Description
1 delete(startindex, This method is used to delete the characters of the specified range.
endindex)
2 get(startindex, It returns the characters present in the specified range.
endindex)
3 index(index) It is used to get the absolute index of the specified index.
4 insert(index, It is used to insert the specified string at the given index.
string)
5 see(index) It returns a boolean value true or false depending upon whether the
text at the specified index is visible or not.
75
o title: It is a string which is shown as a title of a message box.
o message: It is the string to be displayed as a message on the message box.
o options: There are various options which can be used to configure the message dialog
box.
The two options that can be used are default and parent.
1. default
The default option is used to mention the types of the default button, i.e. ABORT, RETRY, or
IGNORE in the message box.
2. parent
The parent option specifies the parent window on top of which, the message box is to be
displayed.
There is one of the following functions used to show the appropriate message boxes. All the
functions are used with the same syntax but have the specific functionalities.
1. showinfo(): The showinfo() messagebox is used where we need to show some relevant
information to the user.
Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showinfo("information","Information")
top.mainloop()
Output:
2. showwarning(): This method is used to display the warning to the user. Consider the
following example.
Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showwarning("warning","Warning")
top.mainloop()
Output:
76
3. showerror(): This method is used to display the error message to the user.
Consider the following example.
Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.showerror("error","Error")
top.mainloop()
Output:
4. askquestion(): This method is used to ask some question to the user which can be
answered in yes or no. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askquestion("Confirm","Are you sure?")
top.mainloop()
Output:
77
5. askokcancel(): This method is used to confirm the user's action regarding some
application activity. Consider the following example.
Example:
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askokcancel("Redirect","Redirecting you to www.javatpoint.com")
top.mainloop()
Output:
6. askyesno(): This method is used to ask the user about some action to which, the user
can answer in yes or no. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askyesno("Application","Got It?")
top.mainloop()
Output:
7. askretrycancel(): This method is used to ask the user about doing a particular task
again or not. Consider the following example.
Example
# !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
top = Tk()
top.geometry("100x100")
messagebox.askretrycancel("Application","try again?")
top.mainloop()
Output:
78
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