0% found this document useful (0 votes)
15 views161 pages

Class 12 - Cs - Full Notes

Uploaded by

study.buddy1269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views161 pages

Class 12 - Cs - Full Notes

Uploaded by

study.buddy1269
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 161



DATABASE MANAGEMENT SYSTEM

Database Management System


MYSQL Concepts

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

WORLD OF SOFTWARE DEVELOPMENT


With the rapid technological changes every day, Application Softwares or Apps have become the part our daily
life. As users we work on the softwares which is the end result of development process. But to develop the
softwares, the process is divided into two parts; FRONT END and BACK END.
The front end is the part of the website users can see and interact with such as the graphical user interface
(GUI) and the command line including the design, navigating menus, texts, images, videos, etc. But the data
becomes equally important as the world of software revolves around the data. So this data which the user
enters using front end needs to be stored somewhere permanently for future retrieval.
Backend, is the part of the Software which the users cannot see and interact with. Backend is the whole
process backend strategies like operation on database, and processing user requests to access the data as
required. Database is the strategy to store, update or delete the data on Database Server.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

DBMS BASICS
WHAT IS A DATABASE?
A Database is a collection of DATA/INFORMATION that is organized so that it can be easily accessed, managed
and updated.
In Database, Data is organized into rows, columns and tables, and it is indexed to make it easier to find
relevant information. It works like a container which contains the various object like Tables, Queries, and
Reports etc. in organized way.
WHY DO WE NEED DATABASE?
 To manage large chunks of data: if size of data increases into thousands of records, it will simply create
a problem to manage. Database can manage large amount of data.
 Accuracy: Through validation rule in database, data accuracy can be maintained.
 Ease of updating data: With the database, we can flexibly update the data according to our convenience.
Moreover, multiple people can also edit data at same time.
 Security of data: With databases we have security groups and privileges to restrict access.
 Data integrity: In databases, we can be assured of accuracy and consistency of data due to the built in
integrity checks and access
DATABASE MANAGEMENT SYSTEM (DBMS)
A DBMS refers to a software that is responsible for storing, maintaining and utilizing database in an efficient
way.
 A Database along with DBMS software is called Database System.
o Example of DBMS software are Oracle, MS SQL Server, MS Access, Paradox, DB2 and MySQL etc.
 MySQL is open source and freeware DBMS.
ADVANTAGES OF DATABASE MANAGEMENT SYSTEM

 Databases reduces Redundancy: It removes duplication of data because data are kept at one place and
all the application refers to the centrally maintained database.
 Database controls Inconsistency: When two copies of the same data do not agree to each other, then
it is called Inconsistency. By controlling redundancy, the inconsistency is also controlled.
 Database facilitate Sharing of Data: Data stored in the database can be shared among several users.
 Database ensures Security: Data are protected against accidental or intentional disclosure to
unauthorized person or unauthorized modification.
 Database maintains Integrity: It enforces certain integrity rules to insure the validity or correctness of
data. For ex. A date can’t be like 31/31/2000.
DATA MODELS: WAY OF DATA REPRESENTATION
Data model is a model or presentation which shows how data is organized or stored in the database. A data is
modelled by one of the following given examples.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Relational Data Model


In this model data is organized into Relations or Tables (i.e. Rows and Columns). A row in a table represents a
relationship of data to each other and also called a Tuple or Record. A column is called Attribute or Field.

Network Data Model


In this model, data is represented by collection of records and relationship among data is shown by Links.

Hierarchical Data Model


In this model, Records are organized as Trees. Records at top level is called Root record and this may contains
multiple directly linked children records.

RELATIONAL DATABASE
A relational database is a collective set of multiple data sets organized by tables, records and columns. Relational
database establish a well-defined relationship between database tables. Tables communicate and share
information, which facilitates data search ability, organization and reporting.
A Relational database use Structured Query Language (SQL), which is a standard user application that provides
an easy programming interface for database interaction.
RELATIONAL DATABASE TERMINOLOGIES
Relation (Table): A Relation or Table is Matrix like structure arranged in Rows and Columns. It is the collection
of logically related records. It has the following properties-
 Atomicity: Each column assigned a unique name and must have atomic (indivisible) value i.e. a value
that cannot be further subdivided.
 No duplicity: No two rows of relation will be identical i.e. in any two rows value in at least one column
must be different.
 All items in a column are homogeneous i.e. same data type.
 Ordering of rows and column is immaterial.
Tuple / Entity / Record: Rows of a table is called Tuple or Record.
Attribute/ Field: Column of a table is called Attribute or Field.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Degree: Number of columns (attributes) in a table.


Cardinality: Number of rows (Records) in a table.
Domain: It is collection of values from which the value is derived for a column.

KEYS IN A DATABASE
Key plays an important role in relational database; it is used for identifying unique rows from table & establishes
relationship among tables on need.
Types of keys in DBMS
 Primary Key: A primary is a column or set of columns in a table that uniquely identifies tuples (rows)
in that table.
 Candidate Key: It is an attribute or a set of attributes or keys participating for Primary Key, to uniquely
identify each record in that table.
 Alternate Key: Out of all candidate keys, only one gets selected as primary key, remaining keys are
known as alternate or secondary keys.
 Foreign Key: Foreign keys are the columns of a table that points to the primary key of another table.
They act as a cross-reference between tables.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Structured Query Language


STRUCTURED QUERY LANGUAGE
SQL is an acronym of Structured Query Language. It is a standard language developed and used for accessing
and modifying relational databases.
The SQL language was originally developed at the IBM research laboratory in San José, in connection with a
project developing a prototype for a relational database management system called System R in the early 70s.
SQL is being used by many database management systems. Some of them are: MySQL, PostgreSQL, Oracle,
SQLite, Microsoft SQL Server etc
ADVANTAGES OF USING SQL
 Interactive Language: This language can be used for communicating with the databases and receive
answers to the complex questions in seconds.
 Multiple data views: The users can make different views of database structure and databases for the
different users.
 Portability: SQL can be used in the program in PCs, servers, laptops, and even some of the mobile phones
and even on different DBMS softwares.
 No coding needed: It is very easy to manage the database systems without any need to write the
substantial amount of code by using the standard SQL.
 Well defined standards: Long established are used by the SQL databases that is being used by ISO and
ANSI. There are no standards adhered by the non-SQL databases.
WHAT IS MySQL
MySQL is currently the most popular open source database management software which can be easily
downloaded from mysql.org. It is a fast, reliable, free, customisable and multi-user database management
system. MySQL is especially popular on the web.
MySQL AB was founded by Michael Widenius (Monty), David Axmark and Allan Larsson in Sweden in year 1995.
MySQL is a non – case sensitive language which means small and capital case letters are same.

MySQL FEATURES
Open Source & Free of Cost: It is Open Source and available at free of cost.
Portability: Small enough in size to install and run it on any types of Hardware and OS like Linux, MS Windows
or Mac etc.
Security: Its Databases are secured & protected with password.
Connectivity: Various APIs (Application Programming Interfaces) are developed to connect it with many
programming languages.
Query Language: It supports SQL (Structured Query Language) for handling database.
TYPES OF SQL COMMANDS
DDL (Data Definition Language): The DDL section of mysql deals with the commands related to database and
table structure. Ex: CREATE, ALTER, DROP etc.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

DML (Data Manipulation Language): The commands in DML are used to insert, delete and update the data
of the table. Ex: INSERT, DELETE, UPDATE.... etc.
DCL (Data Control Language)
It is used to manipulate permissions or access rights to the tables. Ex: GRANT, REVOKE etc.
Transactional control Language.
Used to control the transactions. Ex: COMMIT, ROLLBACK, SAVEPOINT etc.
MYSQL WORKING SCREEN
When we start MySQL, it asks for the password to open. After providing the right password it shows you the
MYSQL PROMPT, where we can start typing our commands.

MYSQL
PROMPT

DATABASE COMMANDS IN MYSQL


1. CREATE DATABASE COMMAND: It is used to create a new database in MYSQL.
mysql> CREATE database nhgws;
2. USE COMMAND: After database creation we have to open the database to start working in it.
mysql> USE nhgws;
3. SHOW DATABASES COMMAND: It displays the listings of available databases in MYSQL.
mysql> SHOW DATABASES;
4. SHOW TABLES COMMAND: It is used to show list of tables in opened database
mysql> SHOW TABLES;
5. DROP DATABASE COMMAND: It is used to delete a database along with all its contents.
mysql> DROP database nhgws;
DATA TYPES IN MYSQL
The data types are given for all the columns of the table and these decide the type of value that will exist in that
column. These are divided into following categories.
Numeric Data Types:
 Integer types: Allow to store only non-fractional numbers in a column. For example: INTEGER or INT (up
to 11 digits), TINYINT, SMALLINT, MEDIUMINT, BIGINT
 Real types: Allow to Store Real / Fractional numbers upto M digits length (including .) with D decimal
places.
FLOAT (M,D) or DECIMAL(M,D) or NUMERIC(M,D) e.g. Float (10,2) can store 1234567.89
String or Text Data Type: It allows to store one or more characters in a column. Its size must be specified.
Ex: CHAR, VARCHAR, TIMYTEXT, SMALLTEXT, MEDIUMTEXT, BLOB etc.
Difference between char and varchar data types: CHAR data type is a fixed length data type whereas VARCHAR
is a variable length data type. Both can store string up to 255 characters. VARCHAR occupies the original length
of the entered value and the display width is according to the largest value of the column whereas CHAR

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

occupies the specified length given at the time of declaring the column. If the value is less than the specified
length then it fills the display width with blank spaces.
Date & Time Data Types: It allow to store date and time type values in a column.
Ex: DATE - Stores date in YYYY-MM-DD format. TIME - Stores time in HH:MM:SS format.
NOTE: String values must be enclosed with single (‘ ‘) or double ( “”) quotes in MySQL. Date and Tiem values
must be enclosed with single (‘ ‘) quotes with ‘YYYY-MM-DD’ and ‘’HH:MM:SS’ format.

MYSQL COMMANDS
CREATE TABLE COMMAND
This command is used to create the structure of a table. While creating the structure, we have to specify the
number of columns with data type, name, size (if required) for each column.
SYNTAX: CREATE TABLE TABLENAME (COLUMN1, DATA TYPE, SIZE CONSTRAINT, ……….);
Ex: mysql> CREATE TABLE student (rno int, name varchar (15), marks decimal (6,2), DOB date);
It will create a blank structure for table student in MYSQL
Rno Name Marks DOB

Constraints: Constraints are the rules or conditions that restrict the values in one or more columns of a table.
The following constraints are commonly used in SQL:
NOT NULL: It ensures that a column cannot have a NULL value.
UNIQUE: It ensures that all values in a column are different.
PRIMARY KEY: A combination of a NOT NULL and UNIQUE. It uniquely identifies each row in a table
CHECK: It Ensures that all values in a column satisfies a specific condition,
DEFAULT: It sets a default value for a column when no value is specified.
NULL VALUES: NULL values is a special marker in SQL to indicate that a data value does not exist in the
database and it is expected in future. NUL value isn't the same as a blank string or a zero integer.
Ex: mysql> CREATE TABLE Persons (ID int PRIMARY KEY, Name varchar(255) NOT NULL, Age int, City
varchar(15) DEFAULT ‘Jaipur', address varchar(20) unique, CONSTRAINT CHK_Person CHECK (Age>=18));
INSERT COMMAND: This insert new rows / records into an existing table. The values must be given in the
same order in which columns in the table have been created.
SYNTAX: INSERT INTO TABLENAME VALUES (VALUE1, VALUE2, ………)
mysql> INSERT INTO student values(1, “Sumit Awasthi”, 89.50, ‘2003-11-05’);
Rno Name Marks DOB
1 Sumit Awasthi 89.5 2003-11-05
We can insert record with specific column only
mysql>INSERT INTO student (RN, MARKS) values(2, 76);
SELECT COMMAND
Select command is used to display the records from table(s) conforming to a certain criteria or condition. With
the SELECT command we can retrieve previously inserted rows.
SYNTAX: SELECT * / col1, col2, …. FROM table name where condition;
* is used to display all the columns from the table. (Display all / Display Report / Display Record / Display Details)
Example 1: Select * from STUDENTS; It will display all the columns with all records.
Example 2: Select Rno, Marks from STUDENTS; It will display only Rno and Marks columns for all records.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

WHERE Clause with select command: It is used to provide the condition with Select command with the help
of Relational (comparison) and Logical operators.
• Comparison operators:
Greater Than > Lesser Than < Greater than or Equals >=
Lesser Than or Equals <= Not Equal < > != Equals =
• Logical operators: These are used to combine two or more conditions.
AND (&&) Gives records when all conditions are TRUE simultaneously.
OR (||) Gives records when for every true condition

SELECT COMMAND / CLAUSES AND EXAMPLES


Create the structure of both the tables and insert the records given.
TABLE: STUDENTS
RN FNAME LNAME SECTION STREAM DOB SEX FEE
1 Sunil Gupta A SCIENCE 2002-11-02 M 26000
2 Ajay Sharma B COMMERCE 2003-06-01 M 28000
3 Shipra Joshi C HUMANITIES 2002-06-25 F 32000
4 Meenal Badola A SCIENCE 2001-08-12 F 29000
5 Rohan Singhal D SCIENCE 2002-04-16 M 38000
6 Rajeev Saini C HUMANITIES 2003-01-27 M 34000
7 Aman Sewlani B COMMERCE 2002-10-17 M 42000
8 Ayush Mishra A SCIENCE 2001-12-05 M 45000
9 Sahil Bhatia A COMMERCE 2002-01-31 M 24000
10 Kamal Singh B HUMANITIES 2003-01-01 M 36000
11 Mukti Garg C SCIENCE 2001-10-19 F 22000
12 Swati Goel D COMMERCE 2003-02-13 F 41000
TABLE: RECORD
RN OPTIONAL THEORY PRACTICAL GRADE
1 IP 360 80 A1
2 VA 410 70 B1
3 FASHION 280 60 B2
4 CS 440 55 A1
5 IP 460 30 A1
6 CS 320 80 B1
7 VA 340 70 B2
8 FASHION 455 40 A1
9 FMM 390 65 A2
10 IP 430 50 A1
11 LEGAL 270 80 B1
12 CS 370 70 A2

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Example 1: Display the record of all the students belonging to Commerce.


Ans: Select * from students where stream=”Commerce”;
O RN FNAME LNAME SECTION STREAM DOB SEX FEE
U 2 Ajay Sharma B COMMERCE 2003-06-01 M 28000
T
7 Aman Sewlani B COMMERCE 2002-10-17 M 42000
P
U 9 Sahil Bhatia A COMMERCE 2002-01-31 M 24000
T 12 Swati Goel D COMMERCE 2003-02-13 F 41000
Example 2: Display the First name, Stream, fee of all students whose date of birth is before 1st February 2002.
Ans: Select FNAME, FEE from students where DOB<’2002-02-01’;
O FNAME STREAM FEE
U Meenal SCIENCE 29000
T
P Ayush SCIENCE 45000
U Sahil COMMERCE 24000
T Mukti SCIENCE 22000
Example 3: Display the First name, Section, Sex and fee of all students whose fee is below Rs. 30000
Ans: Select FNAME, SECTION, SEX, FEE from students where FEE<30000;
FNAME SECTION SEX FEE
O
Sunil A M 26000
U
T Ajay B M 28000
P Meenal A F 29000
U
Sahil A M 24000
T
Mukti C F 22000
Example 4: Display the Records of all students whose Fee is from 3500 to 45000
Ans: Select * from students where FEE> =35000 and FEE<=45000;
Example 5: Display the Records of all male students of Commerce.
Ans: Select * from students where Sex = “M” and Stream = “Commerce”; (&& can be used in place of AND)
Example 6: Display the Records of all students who are either in ‘A’ Section or ‘C’ Section.
Ans: Select * from students where Section = “A” OR Section = “C”; (|| can be used in place of OR)
Example 7: Display the Records of all students of Science and Commerce Stream
Ans: Select * from students where Stream=“Commerce” OR Stream=“Science”;
BETWEEN CLAUSE: This clause is used to display the records which fall in the specified range of values in a
column. It also includes specified values in the range.
Example 8: Display the Records of all students whose Fee is from 3500 to 45000
Ans: Select * from students where FEE BETWEEN 35000 and 45000; OR FEE> =35000 and FEE<=45000;
IN CLAUSE: This clause is used to display the records from a column that matches the data in the specified list.
Example 9: Display the Records of all students who are either in ‘A’ Section or ‘C’ Section.
Ans: Select * from students where Section IN (“A”, “C”); OR Section = “A” OR Section = “C”;
NOT IN CLAUSE: This clause is used to display the records from a column that do not match the data in the
specified list.
Example 10: Display the Records of all students who do not belong to ‘A’ Section or ‘C’ Section.
Ans: Select * from students where Section NOT IN (“A”, “C”);

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

ORDER BY CLAUSE: This clause is used to arrange the records of a table either in ascending or in descending
order on the basis of values of a column. By default it arranges in ascending order; use DESC to arrange in
descending order.
Example 11: Display the Records of all students according to their first names.
Ans: Select * from students order by fname;
Example 12: Display the Records of all Female students of in ascending order of their fees.
Ans: Select * from students where Sex = “F” order by fees;
Example 13: Display the Records of all Male students of in descending order of their DOB.
Ans: Select * from students where Sex = “M” order by DOB DESC;
GROUP FUNCTIONS: SQL provides number of in-built functions which work on aggregate of records and return
single value as answer. These are also known as aggregate functions.
a. SUM (): Returns the sum of values of a column.
Example 14: Display total fee from students table.
Ans: Select SUM (FEE) from STUDENTS;
SUM(FEE)
OUTPUT
397000
Example 15: Display total fee paid by students of Humanities.
Ans: Select SUM (FEE) from STUDENTS where STREAM = “Humanities”;
SUM(FEE)
OUTPUT
102000
b. AVG (): Returns the Average of values of a column.
Example 16: Display average fee paid by students of HUMANITIES.
Ans: Select AVG (FEE) from STUDENTS where STREAM = “Humanities”;
AVG(FEE)
OUTPUT
34000
c. MIN (): Returns the minimum value from the column.
Example 17: Display minimum fee paid by students of HUMANITIES.
Ans: Select MIN (FEE) from STUDENTS where STREAM = “Humanities”;
MIN(FEE)
OUTPUT
32000
d. MAX (): Returns the minimum value from the column.
Example 18: Display maximum fee paid by students of HUMANITIES.
Ans: Select MAX (FEE) from STUDENTS where STREAM = “Humanities”;
MAX(FEE)
OUTPUT
36000
e. COUNT (): The count function counts the no. of records from a table. It has three forms.
i. COUNT (*): Counts the records based on some condition.
Example 19: Count no. of male students.
Ans: Select count (*) from STUDENTS where SEX = “M”;
COUNT (*)
OUTPUT
8
ii. COUNT (DISTINCT COLUMN NAME): Counts the no. of distinct / unique values in a column.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Example 20: How many sections are there in Students table?


Ans: Select COUNT (DISTINCT SECTION) from STUDENTS;
COUNT (DISTINCT SECTION)
OUTPUT
4
iii. COUNT (COLUMN NAME): Counts the no. of NON NULL values in a column.
Example 21: Suppose salary column of employee table has following values and the following
command is given: Select COUNT (Salary) from employee;
Salary
26000
NULL
32000 COUNT (Salary)
OUTPUT
29000 4
NULL It will not count NULL Values
34000

GROUP BY CLAUSE: This clause makes the groups of records on the bases of similar values in a column and
then works with GROUP FUNCTIONS to be applied on each group.
Example 22: Count the number of students in each stream.
Ans: Select STREAM, COUNT (*) from students GROUP BY STREAM;
O STREAM COUNT (*)
U
T SCIENCE 5
P COMMERCE 4
U
T HUMANITIES 3
Example 23: Display the minimum and maximum fees in each stream.
Ans: Select STREAM, COUNT (*) from students GROUP BY STREAM;
O STREAM MIN (FEE) MAX (FEE)
U
T SCIENCE 22000 45000
P COMMERCE 24000 42000
U
T HUMANITIES 32000 36000
HAVING CLAUSE WITH GROUP BY: The HAVING clause filters the records provided by GROUP BY clause: It
provides condition in GROUP BY clause with the help of GROUP FUNCTIONS.
Example 24: Count the number of students in each stream where no. of students are more than 3.
Ans: Select STREAM, COUNT (*) from students GROUP BY STREAM HAVING COUNT (*)>3;
O STREAM COUNT (*)
U
T SCIENCE 5
P
U COMMERCE 4
T
LIKE OPERATOR: LIKE is a String pattern matching operator which helps in extracting the records where a
String Pattern has been given. It uses two wildcard characters.
 ( % ) Percent: It replaces a Substring or part of a String.
 ( _ ) Underscore: It replaces single character or position in a String.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Example 25: Display the records of all students whose first name starts with alphabet ‘M’.
Ans: Select * from students where fname like “M%”;
RN FNAME LNAME SECTION STREAM DOB SEX FEE
OUTPUT 4 Meenal Badola A SCIENCE 2001-08-12 F 29000
11 Mukti Garg C SCIENCE 2001-10-19 F 22000
Example 26: Display the first name, last name and Fee of all students last name ends with alphabet ‘L’.
Ans: Select fname, lname, FEE from students where lname like “%L”;
FNAME LNAME FEE
OUTPUT Rohan Singhal 38000
Swati Goel 41000
Example 27: Display the first name, last name and Fee of all students last name starts with alphabet ‘S’ and
ends with alphabet ‘i’.
Ans: Select fname, lname, FEE from students where lname like “S % i”;
FNAME LNAME FEE
OUTPUT Rajeev Saini 34000
Aman Sewlani 42000
Example 28: Display the first name and last name of all students whose second alphabet in lname is ‘i’.
Ans: Select fname, lname, FEE from students where lname like “_i%”;
FNAME LNAME
OUTPUT Rohan Singhal
Kamal Singh
Example 29: Display the first name and last name of all students whose second alphabet in lname is ‘i’ and
second last alphabet is “a”.
Ans: Select fname, lname, FEE from students where lname like “_ i % a _”;
FNAME LNAME
OUTPUT
Rohan Singhal
Example 30: Display the records of all students whose first name is of maximum 6 characters length.
Ans: Select fname, lname, FEE from students where lname like “_ _ _ _ _ _”;
DISTINCT CLAUSE: It is used to display only unique values from a column.
Example 31: Display the names of all the available STREAMS.
Ans: Select DISTINCT STREAM from students;
O DISTINCT STREAM
U
T SCIENCE
P COMMERCE
U
T HUMANITIES
“AS” CLAUSE: This clause is used to change the column headings while displaying the data.
Example 32: change the headings to “FIRSTNAME” and “DATE OF BIRTH” in place of fname and DOB.
Ans: Select fname as “FIRSTNAME”, DOB as “DATE OF BIRTH” from students;
FIRSTNAME DATE OF BIRTH
OUTPUT
-------- ----------

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

PERFORMING CALCULATIONS IN MYSQL: MYSQL allows to perform calculation on table data as well as
without table data. For example: SELECT 13+9; will result in 22, in which no table is required. Similarly we can
perform calculations and formulations on table data as given in the example ahead.
Example 33: Display Roll Number, First Name and Discount of students of section “B” where discount can be
calculated as 10% of FEE.
Ans: Select RN, FNAME, FEE*10/100 as “DISCOUNT” from students where SECTION = “B”;
O RN FNAME DISCOUNT
U
T 2 Ajay 2800
P 7 Aman 4200
U
T 10 Kamal 3600
ESTABLISHING RELATIONSHIP BETWEEN TWO TABLES: When there is a need of accessing the data from
two tables then a relationship between both the tables is mandatory. The relationship is created on the basis
of values of a common column between the tables. The records are fetched corresponding to common values
of common column.
Example 34: Display First Name, Stream and optional subject of all the students.
Ans: Select FNAME, STREAM, OPTIONAL from STUDENTS, RECORD where STUDENT.RN=RECORD.RN;
FNAME STREAM OPTIONAL
Sunil SCIENCE IP
Ajay COMMERCE VA
O Shipra HUMANITIES FASHION
U Meenal SCIENCE CS
Rohan SCIENCE IP
T
Rajeev HUMANITIES CS
P Aman COMMERCE VA
U Ayush SCIENCE FASHION
T Sahil COMMERCE FMM
Kamal HUMANITIES IP
Mukti SCIENCE LEGAL
Swati COMMERCE CS
*NOTE that there is no condition given in the question, still we have to write a condition comparing values of
common column. If name of common column is same in both the tables then we should specify the column
name with its tablename followed by a dot. It is known as fully qualified name for a column.
Another method for the above question is to use ALIAS NAMES for specified tables as shown below.
Example 35: Display First Name, Stream and optional subject of all the students.
Ans: Select FNAME, STREAM, OPTIONAL from STUDENTS S, RECORD R where S.RN=R.RN;
In the above answer, ‘S’ and ‘R’ are alias (alternate) names for tables STUDENT and RECORD respectively. It
would give same output as shown in previous example.
Example 36: Display First Name and Grades of all students of SECTION ‘D’.
Ans: Select FNAME, GRADE, from STUDENTS S, RECORD R where S.RN=R.RN AND SECTION = “D”;
FNAME GRADE
OUTPUT Rohan A1
Swati A2

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Example 37: Display First Name, Fee and total marks of all students of Commerce section where Total Marks
are the sum of THEORY and PRACTICAL
Ans: Select FNAME, FEE, THEORY + PRACTICAL as “TOTAL MARKS” from STUDENTS S, RECORD R
Where S.RN=R.RN AND STREAM = “COMMERCE”;
FNAME FEE TOTAL MARKS
Ajay 28000 480
OUTPUT Aman 42000 410
Sahil 24000 455
Swati 41000 440

UPDATE COMMAND: This command is used to modify / change the data / records present in the table
permanently. After applying update command, use SELECT command to see the updated records.
SYNTAX: UPDATE TABLENAME SET COLUM NAME = NEW VALUE WHERE CONDITION;
Example 38: Increase the fee of all students by Rs. 500
Ans: Update Students set FEE = FEE + 500;
Select RN, FEE from Students;
RN FEE
O 1
2
26500
28500
U 3
4
32500
29500
T 5
6
38500
34500
P 7
8
42500
45500
U 9
10
24500
36500
T 11
12
22500
41500
Example 39: Decrease the fee of all students of Science by 15%.
Ans: Update Students set FEE = FEE – FEE*0.15 where STREAM=”SCIENCE”;
Select RN, FEE from Students;
RN FEE
1 22525
4 25075
OUTPUT
5 32725
8 38675
11 19125
DELETE COMMAND: This command is used to remove the records from the table permanently.
SYNTAX: DELETE FROM TABLENAME WHERE CONDITION;
Example 40: Remove the records of all students of ‘B’ Section
Ans: Delete from Students where SECTION = ‘B’;
Example 41: Remove all the records of Students table
Ans: DELETE FROM STUDENTS; (Records will be removed but the structure will be unaffected)

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

ALTER TABLE COMMAND: This command is used to modify / change the structure of a table. There are 4
ways / situations where the structure can be changed.
SYNTAX: ALTER TABLE TABLENAME (ADD/MODIFY/CHANGE/DROP) COLUMN NAME;
a. Adding new column
Example 42: Add a new column in Students table to store city of each student.
Ans: Alter Table Students ADD CITY VARCHAR (15);
b. Modifying an existing column:
Example 43: Change the length of FNAME column from existing to 20 characters.
Ans: Alter Table Students MODIFY FNAME VARCHAR (15);
c. Renaming a column:
Example 44: Change the name of FNAME column to FIRSTNAME.
Ans: Alter Table Students CHANGE FNAME FIRSTNAME VARCHAR (15);
d. Removing a column:
Example 45: Remove CITY column from the table Students..
Ans: Alter Table Students DROP CITY;
DROP TABLE COMMAND: This command is used to remove / delete the table from the database
permanently.
Example 46: Remove the table Students.
Ans: Drop Table Students;
 Delete command removes the records but does not affect the structure whereas when we drop a
table, it removes all records as well as structure of the table from MYSQL.
VIEWING THE STRUCTURE OF THE TABLE
a. Explain Students;
b. Describe Students;
c. Show Create Table Students;

IS NULL / IS NOT NULL operator: This is used with SELECT COMMAND when we want to see the records
which contain NULL VALUES. IS NOT NULL is opposite of IS NULL.
Example 47: Display the records of all the students whose first name has NULL value / whose first name has
not been entered.
Ans: Select * from Students where FNAME IS NULL;

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

MYSQL LIBRARY / BUILT – IN FUNCTIONS


MySQL has many built-in functions which are also known as library functions. They can be categorized according
to the data types that they operate on i.e. strings, date and numeric. Some work without table data and some
can work in both ways that is with or without table data. They are divided into following categories.
A. STRING / CHARACTER FUNCTIONS:
1. LENGTH ( ): It is used to find the length of the String.
Example 48: SELECT LENGTH (“CS AND IP”);
LENGTH(“CS AND IP”)
OUTPUT
9
Example 49: Display the FIRST NAME and its length of students of section “C”.
Ans: Select FNAME, length (FNAME) from Students where SECTION=”C”;
FNAME LENGTH(FNAME)
Shipra 6
OUTPUT
Rajeev 6
Mukti 5

2. CONCAT (): It is used to combine two or more Strings.


Example 50: SELECT CONCAT (“INFORMATICS”, “PRACTICES);
CONCAT(“INFORMATICS”, “PRACTICES”)
OUTPUT
INFORMATICSPRACTICES
Example 51: Display the full name of every student of SECTION “C”
Ans: Select CONCAT (FNAME, “ “, LNAME) as “FULL NAME” from Students where SECTION=”C”;
FULL NAME
Shipra Joshi
OUTPUT
Rajeev Singhal
Mukti Garg
3. LOWER ( ) OR LCASE (): It is used to print strings in Lower Case (Small Letters).
Example 52: SELECT LOWER (“COMputer”);
LOWER(“COMputer”)
OUTPUT
computer
4. UPPER () OR UCASE (): It is used to print strings in Upper Case (Capital Letters).
Example 53: SELECT UPPER (“COMputer”);
UPPER(“COMputer”)
OUTPUT
COMPUTER
5. INSTR (): It is used to return the first occurrence of a character / substring in a string
Example 54: SELECT INSTR (“This is a pen”, “i”);
INSTR (“This is a pen”, “i”)
OUTPUT
3
6. LEFT (): It is used to return number of specified characters from the left of a string.
Example 55: SELECT LEFT (“COMPUTER SCIENCE”, 4);

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

LEFT (“COMPUTER SCIENCE”, 4)


OUTPUT
COMP
7. RIGHT: It is used to return number of specified characters from the right of a string.
Example 56: SELECT RIGHT (“COMPUTER SCIENCE”, 4);
RIGHT (“COMPUTER SCIENCE”, 4)
OUTPUT
ENCE
8. RIGHT: It is used to return number of specified characters from the right of a string.
Example 57: SELECT RIGHT (“COMPUTER SCIENCE”, 4);
RIGHT (“COMPUTER SCIENCE”, 4)
OUTPUT
ENCE
9. MID () OR SUBSTRING () OR SUBSTR (): It is used to return number of specified characters
from the specified position from a string.
Example 58: SELECT MID (“COMPUTER SCIENCE”, 4, 8);
MID (“COMPUTER SCIENCE”, 4,8)
OUTPUT
PUTER SC
10. LTRIM (): It is used to remove all blank spaces (Trailing Spaces) from the left of a string.
11. RTRIM (): It is used to remove all blank spaces (Leading Spaces) from the right of a string.
12. TRIM (): It is used to remove all leading and trailing blank spaces from both sides of a string.
Example 59: SELECT LTRIM (“….COMPUTER”);
LTRIM (“….COMPUTER”)
OUTPUT
COMPUTER
Example 60: SELECT RTRIM (“COMPUTER….”);
RTRIM (“COMPUTER….”)
OUTPUT
COMPUTER
Example 61: SELECT TRIM (“….COMPUTER….”);
TRIM (“….COMPUTER….”)
OUTPUT
COMPUTER
Example 62: SELECT CONCAT (RTRIM (“COMPUTER….”), LTRIM (“….SCIENCE”));
CONCAT (RTRIM (“COMPUTER….”), LTRIM (“….SCIENCE”))
OUTPUT
COMPUTERSCIENCE
13. REVERSE (): It is used to reverse a String
Example 63: SELECT REVERSE (“COMPUTER”);
REVERSE (“COMPUTER”)
OUTPUT
RETUPMOC
B. MATHEMATICAL / NUMERIC FUNCTIONS
1. POW () OR POWER (): It is used to return a raised to the power b (a b).
Example 64: SELECT POW (3,4);
POW(3, 4)
OUTPUT
81
2. SQRT (): It is used to return the square root of a number.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Example 65: SELECT SQRT (25);


SQRT (25)
OUTPUT
5
3. MOD: It is used to return remainder after dividing one number from another.
Example 66: SELECT MOD (23, 3);
MOD (23, 3)
OUTPUT
2
4. CEIL () OR CEILING (): It is used to change a number to nearest next Integer.
Example 67: SELECT CEIL (23.2);
CEIL (23.2)
OUTPUT
24
5. FLOOR: It is used to change a number to nearest previous Integer.
Example 68: SELECT FLOOR (23.99);
FLOOR (23.99)
OUTPUT
23
6. ROUND: It is used to round a number to a specified number of decimal places. If no specified
number of decimal places is provided for round off, it rounds off the number to the nearest
integer.
Syntax: ROUND(X, D), where X is the number which to be rounded and D specifies number of
decimal places up to which the given number is to be rounded. It is optional. If not given it
round off the number to the closest integer. If it is negative, then the number is rounded to
the left side of the decimal point.
Example 69:
a. SELECT ROUND (323.3436, 3); Ans: 323.344
b. SELECT ROUND (323.3432, 3); Ans: 323.343
c. SELECT ROUND (323.3436, 2); Ans: 323.34
d. SELECT ROUND (323.3476, 2); Ans: 323.35
e. SELECT ROUND (323.3436, 1); Ans: 323.3
f. SELECT ROUND (323.3736, 1); Ans: 323.4
g. SELECT ROUND (323.3436,0 ); Ans: 323 [We can skip 0 and answer will be same]
h. SELECT ROUND (323.7436,0 ); Ans: 323
i. SELECT ROUND (323.3436, –1); Ans: 320
j. SELECT ROUND (326.3436, –1); Ans: 330
k. SELECT ROUND (326.3436, –2); Ans: 300
l. SELECT ROUND (386.3436, –2); Ans: 400
m. SELECT ROUND (626.3436, –3); Ans: 1000
n. SELECT ROUND (326.3436, –3); Ans: 0
C. DATE AND TIME FUNCTIONS
1. CURDATE (): It is used to display Current System Date.
Example 70: SELECT CURDATE ();
SELECT CURDATE ();
OUTPUT
2021-06-17

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

2. SYSDATE () OR NOW (): It is used to display Current System Date along with Current System
Time.
Example 71: SELECT SYSDATE ();
SELECT SYSDATE ();
OUTPUT
2021-06-17 10:15:25
3. DATE (): It is used to extract date part from a date time expression
Example 72: SELECT DATE (CURDATE ());
SELECT DATE (CURDATE ());
OUTPUT
2021-06-17
4. DAY () OR DAYOFMONTH (): It is used to extract Day’s date from a date value.
Example 73: SELECT DAY (CURDATE ());
SELECT DAY (CURDATE ());
OUTPUT
06
5. DAYNAME (): It is used to return the name of the day from a date value. (Monday, Tuesday….
And so on)
Example 74: SELECT DAYNAME (CURDATE ());
SELECT DAYNAME (CURDATE ());
OUTPUT
THURSDAY
6. DAYOFWEEK (): It is used to return the no. of weekday from a date value. (1 for Sunday, 2 for
Monday…. And so on)
Example 75: SELECT DAYOFWEEK (CURDATE ());
SELECT DAYNAME (CURDATE ());
OUTPUT
05
7. MONTH (): It is used to return the month from date value.
Example 76: SELECT MONTH (CURDATE ());
MONTH (CURDATE ())
OUTPUT
06
8. MONTHNAME (): It is used to return the name of the month from date value.
Example 77: SELECT MONTHNAME (CURDATE ());
MONTHNAME (CURDATE ())
OUTPUT
JUNE
9. YEAR (): It is used to return the year from a date value.
Example 78: SELECT YEAR (CURDATE ());
YEAR (CURDATE ())
OUTPUT
2021
Example 79: Display the FIRST NAMES and birth year of all the students of Humanities.
Ans: SELECT YEAR (DOB) from STUDENTS where STREAM=”HUMANITIES”;
FNAME YEAR (DOB)
Shipra 2002
OUTPUT
Rajeev 2003
Kamal 2003

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

10. WEEK () / WEEKOFYEAR (): It is used to return the week number of the year from a date value.
Example 80: SELECT WEEK (CURDATE ());
WEEK (CURDATE ())
OUTPUT
24

RELATIONAL ALGEBRA
It means operations on relations. DBMS provides some operators which perform operations on tables and give
occurrences of relations as output. The output of these operations is a new relation, which might be formed
from one or more input relations.
Basic Relational Algebra Operations:
Relational Algebra divided in various groups
SELECT (symbol: σ) PROJECT (symbol: π) UNION (υ) INTERSECTION ( ),
DIFFERENCE (-) CARTESIAN PRODUCT ( x ) JOIN
SELECT Operator (σ): It is used to select rows from a table based on some condition.
PROJECT Operator (π): It is used to select columns from a table.

Union Operator (U)


Union operator is denoted by (U) symbol and it is used to select all unique records from two tables.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

Intersection Operator (∩)


Intersection operator is denoted by ∩ symbol and it is used to select only the common rows records i.e. only
those rows that are present in both the tables will appear in the result set.

Minus / Difference (-)


Difference operators gives records of first table which are not present in second table.

Cartesian product (X)/cross joint


Cartesian product means product or records of both the tables. It would combine each record of first table with
each record of second table. Degree is always added and cardinality is multiplied

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

JOIN – Join is used to fetch data from two or more tables, which is joined to appear as single set of data. It is
used for combining column from two or more tables by using values common to both tables.
Types of JOIN:
INNER Join or EQUI Join: This is a simple JOIN in which the result is based on matched data as per the equality
condition specified in the SQL query.

NATURAL JOIN: Natural Join is a type of Inner join which is based on column having same name and same data
type present in both the tables to be joined. E.g. Select * from a natural join b;

LEFT Outer Join: The left outer join returns a result set table with the matched data from the two tables and
then the remaining rows of the left table and null from the right table's columns. E.g.

By Amit Kumar Bhatia


DATABASE MANAGEMENT SYSTEM

RIGHT Outer Join: The right outer join returns a result set table with the matched data from the two tables
being joined, then the remaining rows of the right table and null for the remaining left table's columns. E.g.

Full Outer Join: The full outer join returns a result set table with the matched data of two table then remaining
rows of both left table and then the right table. E.g.

By Amit Kumar Bhatia


PROGRAMMING IN PYTHON
INTRODUCTION TO PYTHON
Python is a general purpose, dynamic, high level, and interpreted programming language. It supports Object
Oriented programming approach to develop applications. It is simple and easy to learn and provides lots of high-
level data structures.
Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for Application
Development.
Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting and rapid
application development.
Python is not intended to work in a particular area, such as web programming. That is why it is known
as multipurpose programming language because it can be used with web, enterprise, 3D CAD, etc.
We don't need to use data types to declare variable because it is dynamically typed so we can write a=10 to assign
an integer value in an integer variable.
Python makes the development and debugging fast because there is no compilation step included in Python
development, and edit-test-debug cycle is very fast.
Python Features
Python provides lots of features that are listed below.
1) Easy to Learn and Use
Python is easy to learn and use. It is developer-friendly and high level programming language.
2) Expressive Language
Python language is more expressive means that it is more understandable and readable.
3) Interpreted Language
Python is an interpreted language i.e. interpreter executes the code line by line at a time. This makes debugging
easy and thus suitable for beginners.
4) Cross-platform Language
Python can run equally on different platforms such as Windows, Linux, Unix and Macintosh etc. So, we can say that
Python is a portable language.
5) Free and Open Source
Python language is freely available at official web address. The source-code is also available. So it is open source.
6) Large Standard Library
Python has a large and broad library and provides rich set of module and functions for rapid application
development.
Python History and Versions
o Python laid its foundation in the late 1980s.
o The implementation of Python was started in the December 1989 by Guido Van Rossum at CWI in
Netherland.
o In February 1991, van Rossum published the code (labeled version 0.9.0) to alt.sources.
o In 1994, Python 1.0 was released with new features like: lambda, map, filter, and reduce.
o Python is influenced by following programming languages:
o ABC language. Modula-3
Python Versions
Programming in Python

Python programming language is being updated regularly with new features and supports. There are lots of
updations in python versions, started from 1994 to current release.
Python 1.0 January 1994

Python 3.9.6 last released on 28th June 2021.

Python Applications
Python is known for its general purpose nature that makes it applicable in almost each domain of software
development. Python as a whole can be used in any sphere of development.
1) Web Applications
We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML
and XML, JSON, Email processing, request, beautiful Soup, Feed parser etc. It also provides Frameworks such as
Django, Pyramid, Flask etc to design and develop web based applications. Some important developments are:
Python Wiki Engines, Pocoo, Python Blog Software etc.
2) Desktop GUI Applications
Python provides Tk GUI library to develop user interface in python based application. Some other useful toolkits
wxWidgets, Kivy, pyqt that are useable on several platforms. The Kivy is popular for writing multitouch applications.
3) Software Development
Python is helpful for software development process. It works as a support language and can be used for build
control and management, testing etc.
4) Scientific and Numeric
Python is popular and widely used in scientific and numeric computing. Some useful library and package are SciPy,
Pandas, IPython etc. SciPy is group of packages of engineering, science and mathematics.
5) Business Applications
Python is used to build Business applications like ERP and e-commerce systems. Tryton is a high level application
platform.
6) Console Based Application
We can use Python to develop console based applications. For example: IPython.
7) Audio or Video based Applications
Python is awesome to perform multiple tasks and can be used to develop multimedia applications. Some of real
applications are: TimPlayer, cplay etc.
8) 3D CAD Applications
To create CAD application Fandango is a real application which provides full features of CAD.
9) Enterprise Applications
Python can be used to create applications which can be used within an Enterprise or an Organization. Some real
time applications are: OpenErp, Tryton, Picalo etc.
10) Applications for Images
Using Python several application can be developed for image. Applications developed are: VPython, Gogh, imgSeek
etc. There are several such applications which can be developed using Python
First Python Program

By Amit Kumar Bhatia


Programming in Python

In this Section, we will discuss the basic syntax of python by using which, we will run a simple program to print
hello world on the console. Python provides us the two ways to run a program:
o Using Interactive interpreter prompt
o Using a script file

Interactive interpreter prompt


Python provides us the feature to execute the python statement one by one at the interactive prompt. It is preferable in the
case where we are concerned about the output of each line of our python program.
Following is the prompt where we can execute the python statement and check their impact on the console.

Using a script file


For making the programs, We need to write our code into a file which can be executed later. For this purpose, open python
idle, an editor like notepad, create a file, give name to it and the extension .py will be added

PYTHON COMMAND PROMPT

Working in Script mode


Steps for creating a program How to run the program
Start IDLE (Python) Click Open command from IDLE’s File menu and select the file you have already saved
Now click File->New in IDLE Python Click Run-> Run Module OR press F5 Key.
Shell.
Write statements for you program. It will execute all the commands of program file and display output in separate python
shell window
Save file with filename and .py
extension

By Amit Kumar Bhatia


Programming in Python

Python Fundamentals
Python Character Set
It is a valid set of characters that a language can recognize. Python has following character set.
o Alphabets: A – Z and a - z
o Digits: 0 – 9
o Special Characters: !, @ # + - * & ^ ( ) { } [ ] ……etc.
o White Space Characters: space, Tab and new line
Python supports total 256 ASCII Characters (AMERICAN STANDARD CODE FOR INFORMATION INTERCHANGE)
Characters ASCII Codes
A–Z 65 – 90
a–z 97 – 122
0–9 48 – 57

Python Keywords
Python Keywords are special reserved words which convey a special meaning to the
compiler/interpreter/Language. Each keyword have a special meaning and a specific operation. These keywords
can't be used as variable. Following is the List of Python Keywords.
True False None and as
asset def class continue break
else finally elif del except
global for If from import
raise try Or return pass
nonlocal in not is lambda

By Amit Kumar Bhatia


Programming in Python

Python Identifiers
An Identifier is used to identify the values used in the program. It is a name given to recognize a particular value in
the program. The rules to name an identifier are given below.
o The identifier name must contain only alphabets, digits and underscore.
o The first character of the variable must be an alphabet or underscore. It should not start with a digit.
o It should not be a keyword.
o Identifier name should be kept in such a way that it should clearly indicate the value it holds.
o Some Valid Identifiers: a123, _n, n_9, etc. Some Invalid identifiers: 1a, n%4, n 9, etc.
Python Literals
Literals can be defined as a data that is given in a variable or constant. Python support the following literals:
I. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double quotes for
a String. Eg: "Aman" , '12345'
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 known as Multiple line String. It is used
using triple quotation marks:
Example: >>> str2='''''welcome
to
INDIA'''
>>> print(str2)
welcome
to
INDIA
II. Numeric literals:
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
Int( signed integers) Long(long integers) Float (floating point) Complex(complex)
Numbers( can be both positive and Integers of unlimited Real numbers with both In the form of a+bj
negative) with no fractional part.eg: 100 size followed by l integer and fractional where a forms the
lowercase or part eg: -26.2 real part and b forms
uppercase L eg: the imaginary part of
87032845L complex number. eg:
3.14j
III. Boolean literals: A Boolean literal can have any of the two values: True or False.
IV. Special literals. Python contains one special literal i.e., None. None is used to specify to that field that is not
created. It is also used for end of lists in Python.
Eg: >>> val1=10
>>> val2=None
>>> val1

By Amit Kumar Bhatia


Programming in Python

10
>>> val2
>>> print val2
None
Punctuators
These are the symbols which improve the readability of the program.

Python Variables
Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value.
In Python, we don't need to specify the type of variable because Python is a type infer language and smart enough
to get variable type.
Variable names can be a group of both letters and digits, but they have to begin with a letter or an underscore. It
is recommended to use lowercase letters for variable name. Rahul and rahul both are two different variables.
Declaring Variable and Assigning Values
Python does not bound us to declare variable before using in the application. It allows us to create variable at
required time. We don't need to declare explicitly variable in Python. When we assign any value to the variable
that variable is declared automatically.
The equal (=) operator or assignment operator is used to assign value to a variable.
Example:

Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement which is also known as multiple
assignment.
We can apply multiple assignments in two ways either by assigning a single value to multiple variables or assigning
multiple values to multiple variables.
1. Assigning single value to multiple variables
Example: x=y=z=50 Output:
print(x, y, z) 50 50 50

By Amit Kumar Bhatia


Programming in Python

2. Assigning multiple values to multiple variables:


Example: a,b,c=5,10,15 Output:
print(a, b, c) 5 10 15
The values will be assigned in the order in which variables appears.
Example: a,b,c=5,10,15
c,a,b=a+b,b*c,c/a Output:
print (a,b,c) 150 3 15

INPUT / OUTPUT IN PYTHON


input() Function
Python input() function is used to get an input from the user. It prompts for the user input and reads a line / String
/ Text. After reading data, it converts it into a string and returns it.
Example:
val = input("Enter a value: ")
# Displaying result
print("You entered:",val)
Output: Enter a value: 45
You entered: 45
NOTE: If we want data of any other type as input then we should convert the string provided by input function to
the required numbered data type using int() or float().
Example 2: age = int(input(‘enter your age’))
C = age+2 #will not produce any error
print() Function
The python print() function is used to print the messages, values of variables/expressions and both in single
statement on to the screen or other standard output devices. The print() always prints in new line.
Example:
Ex1: print("Python is programming language.") Output: Python is programming language.
Ex2: x = 7
print(x) Output: 7
Ex3: x=7
print("The Number is”, x) Output: The number is 7
Ex4: x, y = 7, 2
print(x,y) Output: 7 2
Ex5: x, y = 7, 2
print(“The Sum is “,x+y) Output: The Sum is 9
Ex6: x, y = 7, 2
print(“The Sum of “, x, “and”, y, “is”, x+y) Output: The Sum of 7 and 2 is 9

By Amit Kumar Bhatia


Programming in Python

Escape Sequences
An Escape sequence is a single predefined character with a prefixed backslash sign(‘\’) which is used to represent
non graphic character in python.
Escape Description
Sequence
\a ASCII Bell (BEL)
\n ASCII Linefeed (LF)
\t ASCII Horizontal Tab (TAB – Ideally 8 spaces)
Example print("This is \n Python programming language.")
print("This is \t Python \t programming language.")
Output: This is
Python programming language.
This is Python programming language.
Python Comments
Comments in Python can be used to explain any program code. It can also be used to hide the code as well. It
enables us to understand the way, a program works. In python, any statement written along with # symbol is known
as a comment. The interpreter does not interpret the comment. Comment is not a part of the program, but it
enhances interactivity of the program and makes the program readable. Python supports two types of comments:
1) Single Line Comment: In case user wants to specify a single line comment, then comment must start with #
Eg: # This is single line comment.
print "Hello Python" Output: Hello Python
2) Multi Line Comment:
Multi lined comment can be given inside triple quotes.
eg: ''' This
Is
Multi line comment'''
eg: #single line comment
print ("Hello Python")
'''''This is
multiline comment''' Output: Hello Python

Python Data Types


Variables can hold values of different data types. Python is a dynamically typed language hence we need not define
the type of the variable while declaring it. The interpreter implicitly binds the value with its type.
Python enables us to check the type of the variable used in the program. Python provides us the type() function
which returns the type of the variable passed.
Ex: A=10
b="Hi Python"
c = 10.5

By Amit Kumar Bhatia


Programming in Python

print(type(a)); Output:
<type 'int'>
print(type(b));
<type 'str'>
print(type(c)); <type 'float'>
Standard data types
A variable can hold different types of values. For example, a person's name must be stored as a string whereas its
id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them. The data types
defined in Python are given below.
Numbers, String, List, Tuple and Dictionary (List Tuple and Dictionary will be discussed in details later)
Numbers
Number stores numeric values. Python creates Number objects when a number is assigned to a variable. For
example; a = 3,
b = 5 #a and b are number objects
Python supports 4 types of numeric data.
1. int (signed integers like 10, 2, 29, etc.)
2. long (long integers used for a higher range of values like 908090800L, -0x1929292L, etc.)
3. float (float is used to store floating point numbers like 1.9, 9.902, 15.2, etc.)
4. complex (complex numbers like 2.14j, 2.0 + 2.3j, etc.) [NOT IN SYLLABUS]
A complex number contains an ordered pair, i.e., x + iy where x and y denote the real and imaginary parts
respectively).
Strings
The string can be defined as the sequence of characters represented in the quotation marks. In python, we can use
single, double, or triple quotes to define a string.
String handling in python is a straightforward task since there are various inbuilt functions and operators provided.
In the case of string handling, the operator + is used to concatenate two strings as the operation "hello"+"
python" returns "hello python".
The operator * is known as repetition operator as the operation "Python” *2 returns "Python Python ".
The following example illustrates the string handling in python.
str1 = 'hello friends' #string str1 Output:
str2 = ' how are you' #string str2 hello friends
print (str1) #printing the str1 how are you
print (str2) #printing the str2 hello friendshello friends
print (str1*2) #printing the string twice hello friends how are you
print (str1 + str2) #printing the concatenation of str1 and str2

Type Conversion
Type Conversion of Integer: int() function converts any data type to integer.
a = "101" # string
b=int(a) # converts string data type to integer. Output:
101 122

By Amit Kumar Bhatia


Programming in Python

c=int(122.4) # converts float data type to integer.


print(b, c)
Type Conversion of Floating point numbers: float() function converts any data type to floating point number.
Example: a='301.4' #string
Output:
b=float(a) #converts string data type to floating point number.
c=float(121) #converts integer data type to floating point number. 301.4 121.0
print(b, c)

Python Operators
The operator can be defined as a symbol which is responsible for a particular operation between two operands. Operators
are the pillars of a program on which the logic is built in a particular programming language. Python provides a variety of
operators described as follows.
Arithmetic operators Comparison operators Assignment Operators
Logical Operators Bitwise Operators Membership Operators

Arithmetic operators
Arithmetic operators are used to perform arithmetic operations between two operands.
OPERATOR DESCRIPTION
+ (Addition) It is used to add two operands. For example, if a = 20, b = 10 => a+b = 30
- (Subtraction) It is used to subtract the second operand from the first operand. If the first operand is less
than the second operand, the value results negative. Example, if a = 20, b = 10 => a – b = 10
/ (divide) It returns the actual mathematical result after dividing the first operand by the second
operand. For example, if a = 23, b = 4 => a/b = 5.75
* (Multiplication) It is used to multiply one operand with the other. For example, if a = 20, b = 10 => a * b = 200
% (remainder) It returns the remainder after dividing the first operand by the second operand. For example,
if a = 20, b = 10 => a%b = 0
** (Exponent) It is an exponent operator represented as it calculates the first operand power to second
operand. For example, if a = 2, b = 6 => a**b = 64
// (Floor division) It gives the floor value of the quotient produced by dividing the two operands. For example,
if a = 23, b = 4 => a//b = 5
Relational / Comparison operator
Comparison operators are used to comparing the value of the two operands and returns Boolean True or False
accordingly. Any expression containing relational operators is known as Relational Expression.
OPERATOR DESCRIPTION
> If the first operand is greater than the second operand, then the condition becomes true.
< If the first operand is less than the second operand, then the condition becomes true.
<= If the first operand is less than or equal to the second operand, then the condition becomes true.
>= If the first operand is greater than or equal to the second operand, then condition becomes true.
!= If the value of two operands is not equal, then the condition becomes true.
== If the value of two operands is equal, then the condition becomes true. (Comparison Operator)

By Amit Kumar Bhatia


Programming in Python

Logical Operators
The logical operators are used to combine two or more relational expressions.
OPERATOR DESCRIPTION
And(&) If both the expression are true, then the condition will be true. If a and b are the
two expressions, a → true, b → true => a and b → true.
Or(|) If one of the expressions is true, then the condition will be true. If a and b are
the two expressions, a → true, b → false => a or b → true.
Not(!) If an expression a is true then not (a) will be false and vice versa.

Python assignment operators


The assignment operators are used to assign the value of the right expression to the left operand.

OPERATOR DESCRIPTION
= It assigns the value of the right expression to the left operand.
+= It increases the value of the left operand by the value of the right operand and assign the
modified value back to left operand. For example,
if a = 10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.
-= It decreases the value of the left operand by the value of the right operand and assign the
modified value back to left operand. For example,
if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore, a = 10.
*= It multiplies the value of the left operand by the value of the right operand and assign the
modified value back to left operand. For example,
if a = 10, b = 20 => a* = b will be equal to a = a* b and therefore, a = 200.
%= It divides the value of the left operand by the value of the right operand and assign the
reminder back to left operand. For example,
if a = 20, b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.
**= a**=b will be equal to a=a**b, for example,
if a = 4, b =2, a**=b will assign 4**2 = 16 to a.
//= a//=b will be equal to a = a// b, for example,
if a = 4, b = 3, a//=b will assign 4//3 = 1 to a.

Membership Operators
Python membership operators are used to check the membership of value inside a data structure. If the value is
present in the data structure, then the resulting value is true otherwise it returns false.

OPERATOR DESCRIPTION
in It is evaluated to be true if the first operand is found in the second operand (Any Sequence).
not in It is evaluated to be true if the first operand is not found in the second operand (Any Sequence)

By Amit Kumar Bhatia


Programming in Python

Operator Precedence
The precedence of the operators is important to find out since it enables us to know which operator should be evaluated first.
OPERATOR DESCRIPTION
() Brackets are evaluated at first instance
** The exponent operator is evaluated first as it has highest priority.
* / % // The multiplication, divide, modules, reminder, and floor division.
+ - Binary plus and minus
<= < > >= Comparison operators (less then, less then equal to, greater then,
greater then equal to).
<> == != Equality operators.
= %= /= //= -= += *= **= Assignment operators
in / not in Membership operators
not / or / and Logical operators
NOTE: Operators having same preference are evaluated from left to right

Errors in Programming Language:


Errors in a program are also known as BUGS and the process of removing these errors is known as DEBUGGING.
These are of 3 types.
1. Syntax Errors: These errors occur in the program when the rules of the language are not followed. These are
also known as COMPILE TIME ERRORS. The program will not run successfully if there is any error in the program.
Ex: variable not found, wrong use of indentation, data type mismatch, function not found, too few arguments, too
many arguments.
2. Run Time Error: These errors occur when the program is running.
Ex: Data type mismatch, index out of bounds, negative list size, divide overflow error (WHEN A NUMBER IS DIVIDED
BY ZERO)
3. Logical Errors: These errors are very difficult to detect and these occur due to the wrong logic applied. The
program runs correctly but shows wrong or unwanted results.
For example the formula to find Simple Interest is (PXRXT)/100 and by mistake we write PXRXTX100. The program
will run correctly but will provide wrong and undesired result.

By Amit Kumar Bhatia


Programming in Python

Assignments (Python Fundamentals)


1. What will be the output of the following code
print(5/2)
print(5//2)
2. What will the output of following codes
print (8*2 - 2*4)
print (3 + 18/9 - 3**2+1)
print ((4 + 24)/8 - (2**3+3))
3. What will the output of following code snippet
x=5
y = -1
print ((x+y)*1./x)
print (3*x )
print (x )
4. Write the equivalent Boolean value
o 7+3*4<3*3+4
o b. 4+3*4==3*3+7
5. What is the problem with following code fragments
a. x="marks"+100
print(x)
b. a=5
b=a+500
a="marks"
c=a/2
print(c)
6. What will be the output of following code fragments
a,b=5,6
a,b,c=10,b,a
a,b,c=c/2,a+4,b*6+2
print(a, b, c)
7. What will be the output of following code fragments
a,b,c=10, 20, 30
print(“a is : “, a ,”\n b is : “, b , “and \t c is : ”,c)
8. What will be the output of following python statements
print(type(100))
print(type(100/2))
print(type('0'))
print(type(5.2))
9. Write Python Program to Add Two Variables

By Amit Kumar Bhatia


Programming in Python

10. Write Python Program to Subtract Two Variables


11. Write Python Program to Multiply Two Variables
12. Write Python Program to Divide Two Variables
13. Write Python Program to Convert Kilometers to Miles
14. Write Python Program to Convert Celsius to Fahrenheit
15. Write Python Program to find the square root of a number.
16. Write Python Program to find Simple Interest.
17. Write Python Program to input marks of 5 subjects (each out of 100). Calculate and print total marks and
percentage
18. Write Python Program to do the following.

By Amit Kumar Bhatia


Programming in Python

FLOW OF CONTROL
It means the order of execution of statements in a program. The default flow of the program is that the statements
in a program are executed from top to bottom and every statement is executed only once. Python provide some
control structures to change the default flow of the program. These are:
1. Decision Making (Selection Statements)
2. Iterative (Looping Statements)
3. Jump Statements

Python If-else statements


Decision making is the most important aspect of almost all the programming languages. As the name implies,
decision making allows us to run a particular block of code for a particular decision. Here, the decisions are made
on the validity of the particular conditions. Condition checking is the backbone of decision making.
In python, decision making is performed by the following statements.

Statement Description

If If statement is used to test a specific condition. If the condition is true, a block of code
Statement (if-block) will be executed.

If - else The if-else statement is similar to if statement but it also provides the block of the
Statement code for the false case of the condition to be checked. If the condition provided in if
statement is false, then the else statement will be executed.

Nested if Nested if statements enable us to use if – else statement inside an outer if statement.
Statement

Multiple if It means a ladder of if… elif …. elif ….else, where multiple conditions can be checked.
Statement

Indentation in Python
For the ease of programming and to achieve simplicity, python doesn't allow the use of parentheses for the block
level code. 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. Generally, four spaces are given to indent the statements which are a
typical amount of indentation in python.
Indentation is the most used part of the python language since it declares the block of code. All the statements of
one block are intended at the same level indentation. We will see how the actual indentation takes place in decision
making and other stuff in python.
The if statement
If statement is used to test a particular condition and if the condition is true, it executes a block of code following
if statement and known as if-block. The condition of if statement can be any valid logical expression which can be
either evaluated to true or false. The syntax of the if-statement is given below.
if expression:
statement

By Amit Kumar Bhatia


Programming in Python

Example 1
Output:
num = int(input("Enter the number?"))
Enter the number?10
if num%2 == 0: Number is even
print("Number is even")
Example 2 : Program to print the largest of the three numbers.
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b and a>c: Output:
print(a, “is largest"); Enter a? 100
if b>a and b>c: Enter b? 120
print(b, “is largest"); Enter c? 130
if c>a and c>b: 130 is largest
print(c, “is largest");
The if-else statement
The if-else statement provides an else block combined with if statement which is executed in the false case of the
condition. If the condition is true, then the if-block is executed. Otherwise, the else-block is executed. Though else
part is optional.
The syntax of the if-else statement is given below.
if condition:
#block of statements
else:
#another block of statements (else-block)
Example 1 : Program to check whether a person is eligible to vote or not.
age = int (input("Enter your age? "))
if age>=18: Output:
print("You are eligible to vote !!"); Enter your age? 90
else: You are eligible to vote !!
print("Sorry! you have to wait !!");
Example 2: Program to check whether a number is even or not.
num = int(input("Enter the number?"))
if num%2 == 0: Output:
print("Number is even...") Enter the number?10
else: Number is even
print("Number is odd...")
Nested if statement:
It means an if else statement within another if statement or within an else statement. It is generally used when
multiple conditions are to be compared simultaneously. Its syntax is:
if expression 1:
if expression 2:

By Amit Kumar Bhatia


Programming in Python

# block of statements
else :
# block of statements
else:
# block of statements
Example: Program to print the largest of the three numbers.
a = int(input("Enter a? "));
b = int(input("Enter b? "));
c = int(input("Enter c? "));
if a>b: Output:
if a>c: Enter a? 100
print(a, “is largest"); Enter b? 120
else: Enter c? 130
print(c, “is largest"); 130 is largest
else:
if b>c:
print(b, “is largest");
else:
print(c, “is largest");
Multiple if statement (if…elif…elif….else)
The multiple if statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional. The syntax of the elif statement is given below.
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Example 1: number = int(input("Enter the number?"))
if number==10:
print("number is equals to 10") Output:
elif number==50: Enter the number?15
print("number is equal to 50"); number is not equal to 10, 50 or 100
elif number==100:
print("number is equal to 100");
else:
print("number is not equal to 10, 50 or 100");

By Amit Kumar Bhatia


Programming in Python

Example 2: marks = int(input("Enter the marks? "))


if marks > 85 and marks <= 100:
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
print("You scored grade C ...")
else:
print("Sorry you are fail ?")

Assignments (Selection Statement)


1. Write python code to input two numbers and print the larger number.
2. Write python code to input a number and check whether it is even or odd.
3. Write python code to input a number and check whether it is negative or positive.
4. Write python code to input a number and check whether it is divisible by 5 or not.
5. Write python code to input a number. If the number I odd and positive then print its square otherwise cube.
6. Write python code to input principal amount and time. If Time is more than 10 years the find the Simple
Interest @ 9.75% PA otherwise find Simple Interest @ 8.25% PA.
7. Write python code to input 3 numbers and print the largest number.
8. Write python code to input 3 numbers and print them in following manner. For example if numbers are 55,
61, 52 then the program should print the following output.
Largest number is 61 Next is 55 and smallest is 52.
9. Write python code to input day number and print the name of day (1 for Monday…)
10. Write python code to input month number and print the name of month (1 for Jan…)
11. Write the code to input total number of telephone calls made in particular month. The program will calculate
and print the payable amount as per the given call rate:
 First 200 phones calls are free in every month
 Next 300 calls are charged at the rate of Rs.1/minute
 And rest calls (after 500 calls or minutes) are charged at the rate of Rs.2/minute
12. Write the code to input total shopping amount purchased in the shop, and then apply the discount as per the
following discount criteria, then find and print the final amount that has to be paid by the customer after
subtracting the discount amount:
 If user has purchased something that costs from Rs.101 to Rs.200, the discount will be 5%
 If user has purchased something that costs from Rs.201 to Rs.400, the discount will be 10%
 If user has purchased something that costs from Rs.401 to Rs.800, the discount will be 20%
 And if user has purchased something that costs above Rs.800, the total discount that will be applied on the
whole purchase amount is 25%

By Amit Kumar Bhatia


Programming in Python

13. Write python code to input marks of 5 subjects of a student (out of 100). Calculate and print his total marks,
percentage and grades as per the given criteria. Grades are ‘A’, ‘B’, ‘C’, #‘D’ or ‘F’, where the percentage
cutoffs for ‘A’, ‘B’, ‘C’, and ‘D’ are 90-100, 80-89, 70-79, 60-69 and below 60.
14. Write the python code to find the roots of quadratic equation. Whether Imaginary, real unequal or real
equal.
15. A company pays the salary to its workers on hourly work basis as per the following criteria.
First 8 hours Rs. 20 per hour
Next 4 hours Rs. 30 per hour
First 6 hours Rs. 50 per hour
For more than 18 hours Rs. 100 per hour
Write the code to input number of hours worked in a day by a worker. Calculate and print his monthly salary
considering that he works for same no. of hours daily
16. Write the python code to input the monthly basic salary of a person. He gets DA as 75% of basic, HRA as 60%
of basic, TA as 45% of basic. Gross salary is the sum of basic, DA, TA and HRA. His net salary is calculated by
deducting PF(18% of basic salary) from Gross Salary. Calculate the income tax to be paid on the basis of the
given criteria
Annual Net Salary Tax Rate
Up to Rs. 400000 0
>Rs. 4, 00, 000 and up to Rs. 6, 00, 000 6% of the amount exceeding Rs. 4, 00, 000
>Rs. 6, 00, 000 and up to Rs. 8, 00, 000 8% of the amount exceeding Rs. 6, 00, 000
>Rs. 8, 00, 000 10% of the amount exceeding Rs. 8, 00, 000
NOTE: If a person invests up to Rs. 100000 then it is exempted from tax.
For example: If annual net salary is Rs.5, 50, 000 and investment is 60, 000 then the taxable income would be
5, 50, 000 – (4, 00, 000 + 60, 000) i.e. Rs. 90, 000

By Amit Kumar Bhatia


Programming in Python

PYTHON LOOPING STATEMENTS


The flow of the programs written in any programming language is sequential by default. Sometimes we may need
to alter the flow of the program. The execution of a specific code may need to be repeated several numbers of
times. For this purpose, the programming languages provide various types of loops which are capable of repeating
some specific code several numbers of times.
LOOPING means repetition of execution of a group of statements on the basis of some condition being TRUE.
Why we use loops in python?
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the program so
that instead of writing the same code again and again, we can repeat the same code for a finite number of times.
For example, if we need to print the first 10 natural numbers then, instead of using the print statement 10 times,
we can print inside a loop which runs up to 10 iterations.
Advantages of loops
There are the following advantages of loops in Python.
1. It provides code re-usability.
2. Using loops, we do not need to write the same code again and again.
3. Using loops, we can traverse over the elements of data structures (array or linked lists).
There are the following loop statements in Python.

Loop Description
Statement

for loop The for loop is used in the case where we need to execute some part of the code
until the given condition is satisfied. It is better to use for loop if the number of
iteration is known in advance.

while The while loop is to be used even in the scenario where we don't know the number
loop of iterations in advance. The block of statements is executed in the while loop until
the condition specified in the while loop is satisfied.

Python for loop


The for loop in Python is used to iterate the statements or a part of the program several times. It is frequently
used to traverse the data structures like list, tuple, or dictionary.
The syntax of for loop in python is given below.
for control variable in sequence:
statement(s)
Example
i=1
n=int(input("Enter the number up to which you want to print the natural numbers?"))
for i in range(0,10):
print(i,end = ' ')
Output: 0123456789

By Amit Kumar Bhatia


Programming in Python

Python for loop example: printing the table of the given number
i=1;
num = int(input("Enter a number:"));
for i in range(1,11):
print(num, “x”, i , “ = “, num*i);
Output: Enter a number:10
10 X 1 = 10
10 X 2 = 20
10 X 3 = 30
10 X 4 = 40
10 X 5 = 50
10 X 6 = 60
10 X 7 = 70
10 X 8 = 80
10 X 9 = 90
10 X 10 = 100
Nested for loop in python
Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times
for every iteration of the outer loop. The syntax of the nested for loop in python is given below.
for iterating_var1 in sequence:
for iterating_var2 in sequence:
#block of statements
#Other statements
Using else statement with for loop
Unlike other languages like C, C++, or Java, python allows us to use the else statement with the for loop which
can be executed only when all the iterations are exhausted. Here, we must notice that if the loop contains any of
the break statement then the else statement will not be executed.
Example 1
for i in range(0,4):
print(i)
else:
print("for loop completely exhausted, since there is no break.");
In the above example, for loop is executed completely since there is no break statement in the loop. The control
comes out of the loop and hence the else block is executed.
Output:
0
1
2
3

By Amit Kumar Bhatia


Programming in Python

for loop completely exhausted, since there is no break.


Example 2
for i in range(0,5):
print(i)
break;
else:
print("for loop is exhausted");
print("The loop is broken due to break statement...came out of loop")
In the above example, the loop is broken due to break statement therefore the else statement will not be
executed. The statement present immediate next to else block will be executed.
Output: 0
The loop is broken due to break statement...came out of loop
Python while loop
The while loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be
executed as long as the given condition is true.
It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of
iterations is not known in advance.
The syntax is given below.
while expression:
statements
Here, the statements can be a single statement or the group of statements. The expression should be any valid
python expression resulting into true or false. The true is any non-zero value.
Example 1
i=1;
while i<=10:
print(i);
i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10

By Amit Kumar Bhatia


Programming in Python

PYTHON JUMP STATEMENTS


The break statement
The break is a keyword in python which is used to bring the program control out of the loop. The break statement
breaks the loops one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to
outer loops. In other words, we can say that break is used to abort the current execution of the program and the
control goes to the next line after the loop.
The break is commonly used in the cases where we need to break the loop for a given condition.

The syntax of the break is given below.


#loop statements
break;
Example 1
list =[1,2,3,4]
count = 1;
for i in list: Output:
if i == 4: item matched
print("item matched") found at 2 location
count = count + 1;
break
print("found at",count,"location");

By Amit Kumar Bhatia


Programming in Python

The continue Statement


The continue statement in python is used to bring the program control to the beginning of the loop. The continue
statement skips the remaining lines of code inside the loop and start with the next iteration. It is mainly used for
a particular condition inside the loop so that we can skip some specific code for a particular condition.

The syntax of Python continue statement is given below.


#loop statements
continue;
#the code to be skipped
Example 1 Output:
i=1; #initializing a local variable 1
#starting a loop from 1 to 10 2
for i in range(1,11): 4
if i%3==0: 5
continue; 7
print("%d"%i); 8
10
Pass Statement
The pass statement is a null operation since nothing happens when it is executed. It is used in the cases where a
statement is syntactically needed but we don't want to use any executable statement at its place.
Pass is also used where the code will be written somewhere but not yet written in the program file.

By Amit Kumar Bhatia


Programming in Python

Assignments (Loops)
1. Write the python code to print the sum of all the numbers from 1 to 50.
2. Write the python code to print the all the even numbers from 1 to 100.
3. Write the python code to input a number and print all the numbers divisible by 5 from 1 to the entered
number.
4. Write the python code to input a number and print its factorial.
For example Factorial of 5 is 5 X 4 X 3 X 2 X 1 = 120
Factorial of 5 is 1X2X3X4X5 = 120
5. Write the python code to input a number and print its Table in following manner.
For example if the number is 5 then the program should print
Table of 5 is
5X1=5
5 X 2 = 10
………………
5 X 10 = 50
6. Write the python code to print the Fibonacci series up to n terms.
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34 55 ……………………………………
7. Write the python code to input a number and print its factors.
8. Write the python code to input a number and check whether the number is perfect or not.
Perfect number = sum of its factors. For Ex: 6 = 1 + 2 + 3 28 = 1 + 2 + 4 + 7 + 14
9. Write the code to print the following patterns.
* 1 1 1
** 12 22 2 3
*** 1 2 3 3 3 3 4 5 6
**** 1234 4444 7 8 9 10
* * * * * 1 2 3 4 5 5 5 5 5 5 11 12 13 14 15
A A ***** *****
AB BB **** ****
ABC C C C *** ***
ABCD DDDD
** **
ABCDE EEEEE *
*
10. Write the python code to input a number and print the table of all the numbers from 1 to the entered
number.
11. Write the python code to input a number and print the factorials of all the numbers from 1 to the entered
number.
12. Write the python code to input a number and print the reverse of the number.
13. Write the python code to input a number and count the number of digits.
14. Write the python code to input a number and print the sum of all its digits.
15. Write the python code to input a number and check whether the number is palindrome or not.
Palindrome number means number=its reverse. For example 121

By Amit Kumar Bhatia


Programming in Python

16. Write the python code to input a number and check whether the number is Armstrong or not.
Armstrong number means number=sum of cube of its digits. For example 153=13+33+53
17. Write the python code to input a number and a digit and find the frequency of the digit in the number.
18. Write the python code to input a number and a digit and check whether the digit is present in the number
or not.
19. Write the python code to input a number and check whether the number is prime or not.
20. What is the output of the following?
i=1
while True:
if i%3 == 0:
break
print(i)
21. What is the output of the following?
i=0
while i < 3:
print(i)
i += 1
else:
print(0)
22. What is the output of the following?
x=2
for i in range(x):
x += 1
print (x)
23. Rewrite following program using for loop
t = 115
while t > 112:
print(t)
t=t-1
24. Rewrite following program using for loop
i=4
while i < 9:
print(i)
i = i+2
25. How many times will the following code print "Welcome to Python"?
count = 0
while count < 10:
print("Welcome to Python")
count += 1
26. What is the output of the following code?
x=0
while x < 4:
x=x+1
print("x is", x)

By Amit Kumar Bhatia


Programming in Python

SEQUENCES IN PYTHON
The most basic data structure in Python is the Sequence. Each element of a sequence is assigned a number - its
position or index. The first index is zero, the second index is one, and so forth. Python has six built-in types of
sequences, Strings, Unicode strings, lists, tuples, buffers, and xrange objects but the most common ones are lists
and tuples.
There are certain things you can do with all sequence types. These operations include indexing, slicing, adding,
multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a
sequence and for finding its largest and smallest elements.

ARRAYS / SEQUENCES

LISTS STRINGS TUPLES DICTIONARY

Arrays in Python
An Array is the collection of logically related homogeneous values under one name into a single unit. All the
elements are stored in contiguous locations by which the accessibility of elements becomes faster.
TYPES OF ARRAYS
1. One dimensional arrays (1 – D Arrays): A 1 – D array is in the form of a row of elements. They are stored in
contiguous memory locations. Index numbers are used to access a particular element. Index numbers range from
0 to n – 1 if the array has ‘n’ elements.
The name of array is “A” having 6 integer elements A=[44,55,66,77,88,99]

VALUES of a 44 55 66 77 88 99
INDEX 0 1 2 3 4 5
Accessing values A[0] A[1] A[2] A[3] A[4] A[5]
2. Multi – Dimensional Arrays (2 – D Arrays): A 2 – D array can be considered as the collection of several 1 – D
arrays of same type. It is in the form of a table or MATRIX. It has two subscripts; one for rows and other for column.
Any element can be accessed by specifying row and column index
The given array has 4 rows and 5 columns
Column 0 Column 1 Column 2 Column 3 Column 4
ROW0 A[0][0] A[0][1] A[0][2] A[0][3] A[0][4]
ROW1 A[1][0] A[1][1] A[1][2] A[1][3] A[1][4]
ROW 2 A[2][0] A[2][1] A[2][2] A[2][3] A[2][4]
ROW3 A[3][0] A[3][1] A[3][2] A[3][3] A[3][4]

By Amit Kumar Bhatia


Programming in Python

Python Lists
The list is a most versatile data type available in Python which can be written as a list of comma-separated values
(items) between square brackets. Important thing about a list is that items in a list need not be of the same type.
List in python is implemented to store the sequence of various type of data. However, python contains six data
types that are capable to store the sequences but the most common and reliable type is list.
A list can be defined as a collection of values or items of different data types. The items in the list are separated
with the comma (,) and enclosed with the square brackets [].
A list can be defined as follows.
L1 = ["John", 102, "USA"]
L2 = [1, 2, 3, 4, 5, 6]
L3 = [1, "Ryan"]
If we try to print the type of L1, L2, and L3 then it will come out to be a list.
Lets consider a proper example to define a list and printing its values.
emp = ["John", 102, "USA"]
print("Name :”, emp[0], “ID: ”, emp[1], “Country: ", ,emp[2])
Name : John, ID: 102, Country: USA
List indexing and splitting
The indexing are processed in the same way as it happens with the strings. The elements of the list can be accessed
by 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.

Unlike other languages, python provides us the flexibility to use the negative indexing also. The negative indices
are counted from the right. The last element (right most) of the list has the index -1, its adjacent left element is
present at the index -2 and so on until the left most element is encountered.

By Amit Kumar Bhatia


Programming in Python

Adding elements to the list


Python provides append() function by using which we can add an element to the list. However, the append()
method can only add the value to the end of the list.
**Consider the following example in which, we are taking the elements of the list from the user and printing
the list on the console. This is the universal method for user input in a list
L =[ ];
OUTPUT
n = int(input("Enter the number of elements in the list"));
Enter the number of elements in the list 4
for i in range(0,n): Enter the item? 33
L.append(input("Enter the item?")); Enter the item? 43
print("Printing the list items...."); Enter the item? 13
Enter the item? 78
for i in L: # traversal loop to print the list items
Printing the list items....
print(i, end = " "); 33 43 13 78
Addition of elements using insert() method
The append () method only works for addition of elements at the end of the List, for addition of element at the
desired position, insert () method is used. Unlike append () which takes only one argument, insert () method
requires two arguments(position, value).
List = [1,2,3,4]
OUTPUT
print("Initial List: ")
Initial List:
print(List) [1, 2, 3, 4]
List.insert(3, 12) List after performing Insert Operation:
['NHGWS', 1, 2, 3, 12, 4]
List.insert(0, 'NHGWS')
print("\nList after performing Insert Operation: ")
print(List)

Using extend() method


Other than append() and insert() methods, there’s one more method for Addition of elements, extend(), this
method is used to add multiple elements at the same time at the end of the list.
Note – append() and extend() methods can only add elements at the end.

By Amit Kumar Bhatia


Programming in Python

# Python program to demonstrate Addition of elements in a List


List = [1,2,3,4]
print("Initial List: ") OUTPUT
Initial List:
print(List) [1, 2, 3, 4]
List.extend([8, 'NHGWS', 'Raipur']) List after performing Extend Operation:
[1, 2, 3, 4, 8, 'NHGWS', 'Raipur']
print("\n List after performing Extend Operation: ")
print(List)

Updating List values


Lists are the most versatile data structures in python since they are immutable and their values can be updated by
using the slice and assignment operator.
Consider the following example to update the values inside the list.
List = [1, 2, 3, 4, 5, 6]
print(List) OUTPUT
[1, 2, 3, 4, 5, 6]
List[2] = 10;
[1, 2, 10, 4, 5, 6]
print(List) [1, 89, 78, 4, 5, 6]
List[1:3] = [89, 78]
print(List)
Removing Elements from the List
Using remove() method :
Elements can be removed from the List by using built-in remove() function but an Error arises if element doesn’t
exist in the set. remove() method only removes one element at a time, to remove range of elements, iterator is
used. The remove() method removes the specified item.
Note – Remove method in List will only remove the first occurrence of the searched element.
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Initial List: ")
print(List) OUTPUT
List.remove(5) Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List.remove(6) List after Removal of two elements:
print("\nList after Removal of two elements: ") [1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
print(List)

Using pop() method


The pop() function can also be used to remove and return an element from the set, but by default it removes only
the last element of the set, to remove element from a specific position of the List, index of the element is passed
as an argument to the pop() method.

By Amit Kumar Bhatia


Programming in Python

List = [1,2,3,4,5]
# Removing element from the list using the pop() method
List.pop()
OUTPUT
print("\nList after popping an element: ") List after popping an element:
print(List) [1, 2, 3, 4]
List after popping a specific element:
List.pop(2) [1, 2, 4]
print("\nList after popping a specific element: ")
print(List)

The list elements can also be deleted by using the del keyword.
List = [0,1,2,3,4]
print(List) OUTPUT
del List[0] [0, 1, 2, 3, 4]
print(List) [1, 2, 3, 4]
del List[3] [1, 2, 3]

print(List)
Negative indexing
In Python, negative sequence indexes represent positions from the end of the array. Instead of having to compute
the offset as in List[len(List)-3], it is enough to just write List[-3]. Negative indexing means beginning from the end,
-1 refers to the last item, -2 refers to the second-last item, etc.

L=[15, 28, 37, 43, 29, 45, 75, 82] Size=8


Values 15 28 37 43 29 45 75 82
Forward Indexing 0 1 2 3 4 5 6 7
Way of Accessing elements L[0] L[1] L[2] L[3] L[4] L[5] L[6] L[7]
Negative Indexing -8 -7 -6 -5 -4 -3 -2 -1
Way of Accessing elements L[-8] L[-7] L[-6] L[-5] L[-4] L[-3] L[-2] L[-1]
Example:
List = [1, 2, 'Computer', 4, 'For', 6, 'Science'] OUTPUT
Accessing element using negative indexing
print("Accessing element using negative indexing")
Science
print(List[-1])
For
print(List[-3])

By Amit Kumar Bhatia


Programming in Python

Slicing of a List
In Python List, there are multiple ways to print the whole List with all the elements, but to print a specific range of
elements from the list, we use Slice operation. Slice operation is performed on Lists with the use of a colon(:). To
print elements from beginning to a range use [: Index], to print elements from end-use [:-Index], to print elements
from specific Index till the end use [Index:], to print elements within a range, use [Start Index: End Index] and to
print the whole List with the use of slicing operation, use [:]. Further, to print the whole List in reverse order, use
[::-1].
Note – To print elements of List from rear end, use Negative Indexes.
List = ['S','U','P','E','R','C', 'O','M','P','U','T','E','R']
print("Initial List: ") OUTPUT
print(List) Initial List:
Sliced_List = List[3:8] ['S','U','P','E','R','C', 'O','M','P','U','T','E','R']
Slicing elements in a range 3-8:
print("\nSlicing elements in a range 3-8: ")
['E', 'R', 'C', 'O', 'M']
print(Sliced_List) Elements sliced from 5th element till the end:
Sliced_List = List[5:] ['C', 'O','M','P','U','T','E','R']
print("\nElements sliced from 5th element till the end: ") Printing all elements using slice operation:
['S','U','P','E','R','C', 'O','M','P','U','T','E','R']
print(Sliced_List)
Sliced_List = List[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_List)

Negative index List slicing


List = ['S','U','P','E','R','C', 'O','M','P','U','T','E','R'] OUTPUT
print("Initial List: ") Initial List:
['S','U','P','E','R','C', 'O','M','P','U','T','E','R']
print(List)
Elements sliced till 6th element from last:
Sliced_List = List[:-6] ['S','U','P','E','R','C', 'O']
Elements sliced from index -6 to -1
print("\nElements sliced till 6th element from last: ")
['M','P','U','T','E']
print(Sliced_List) Printing List in reverse:
Sliced_List = List[-6:-1] ['R', 'E', 'T', 'U', 'P', 'M', 'O', 'C', 'R', 'E', 'P', 'U', 'S']

print("\nElements sliced from index -6 to -1")


print(Sliced_List)
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)

By Amit Kumar Bhatia


Programming in Python

Python List Operations


The concatenation (+) and repetition (*) operator work in the same way as they were working with the strings.
Lets see how the list responds to various operators.
Consider a List l1 = [1, 2, 3, 4], and l2 = [5, 6, 7, 8]

Operator Description Example

Repetition The repetition operator enables the list elements l1*2 = [1, 2, 3, 4, 1, 2, 3,
to be repeated multiple times. 4]

Concatenation It concatenates the list mentioned on either side l1+l2 = [1, 2, 3, 4, 5, 6,


of the operator. 7, 8]

Membership It returns true if a particular item exists in a print(2 in l1) prints


particular list otherwise false. True.

Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
4

Length It is used to get the length of the list len(l1) = 4

Iterating a List
A list can be iterated by using a for - in loop. A simple list containing four strings can be iterated as follows.
List = ["John", "David", "James", "Jonathan"]
for i in List: #i will iterate over the elements of the List and contains each element in each iteration.
print(i);

OUTPUT
John
David
James
Jonathan

By Amit Kumar Bhatia


Programming in Python

Python List Built-in functions


Python provides the following built-in functions which can be used with the lists.

SN Function Description

1 cmp(list1, list2) It compares the elements of both the lists.

2 len(list) It is used to calculate the length of the list.

3 max(list) It returns the maximum element of the list.

4 min(list) It returns the minimum element of the list.

5 list(seq) It converts any sequence to the list.

Python List built-in methods

SN Function Description

1 list.append(obj) The element represented by the object obj is added to the list.

2 list.clear() It removes all the elements from the list.

3 List.copy() It returns a shallow copy of the list.

4 list.count(obj) It returns the number of occurrences of the specified object in


the list.

5 list.extend(seq) The sequence represented by the object seq is extended to the


list.

6 list.index(obj) It returns the lowest index in the list that object appears.

7 list.insert(index, obj) The object is inserted into the list at the specified index.

8 list.pop(obj=list[-1]) It removes and returns the last object of the list.

9 list.remove(obj) It removes the specified object from the list.

10 list.reverse() It reverses the list.

11 list.sort([func]) It sorts the list by using the specified compare function if given.

By Amit Kumar Bhatia


Programming in Python

Assignments (Lists)
1. Write the code to input a list and double each element.
Ex.: if the list is 5, 8, 7, 3, 9, 5, 1, 8
then new list should be 10, 16, 14, 6, 18, 10, 2, 16
2. Write the code to input a list and print all those elements which are divisible by 5.
Ex.: if the list is 5, 8, 7, 20, 9, 5, 25, 8
then program should print 5, 20, 5, 25
3. Write the code to input a list and reverse it.
Ex.: if the list is 5, 8, 7, 20, 9, 5, 25, 8
then new list should be 8, 25, 5, 9, 20, 7, 8, 5
4. Write the code to input a list and then half all even elements and double all odd elements.
Ex.: if the list is 5, 8, 7, 20, 9, 5, 25, 8
then new list should be 10, 4, 14, 10, 18, 10, 50, 4
5. Write the code to input a list and replace all elements with successive element(in pairs).
Ex.: if the list is 5, 8, 7, 20, 9, 5, 25, 8
then new list should be 8, 5, 20,7, 5, 9, 8, 25
6. Write the code to input a list and shift every element to its next position. The last element should be
replaced with first element.
Ex.: if the list is 5, 8, 7, 20, 9, 5, 25, 8
then new list should be 8, 5, 8, 7, 20, 9, 5, 25
7. Write the code to input a list and replace all first half element with its second half element.
Ex. 1: if the list is 5, 8, 7, 20, 9, 5, 25, 8
then new list should be 9, 5, 25, 8, 5, 8, 7, 20
SHORT / OUTPUT BASED QUESTIONS
8. Suppose list1 is [9, 1, 3, 2], What is list1 * 2 ? else:
9. Suppose list1 is [1, 3, 5, 12, 5], what is print(2)
list1.index(5) ?
14. What will be the output?
10. Suppose list1 is [13, 14, 15, 20, 15, 25, 11, 13],
what is list1.count(15) ? numbers = [11, 12, 13, 14]
11. What is the output when the following code is numbers.append([15,16,17,18])
executed ? print(len(numbers))
"Welcome to Computer Science".split() 15. What will be the output?
12. What is the output when following code is m = [[x, x + 1, x + 2] for x in range(1, 4)]
executed ?
print(m)
names = ['Freya', 'Mohak', 'Mahesh',
'Dwivedi'] 16. What will be the output?

print(names[-1][-1]) values = [[13, 41, 15, 11 ], [313, 16, 11, 12]]

13. What will be the output? for r in values:


names1 = ['Freya', 'Mohak', 'Mahesh', r.sort()
'Dwivedi'] for element in r:
if 'freya' in names1: print(element, end = " ")
print(1) print()

By Amit Kumar Bhatia


Programming in Python

17. What will be the output? names2 = names1


points = [[1, 20.5], [2, 1.5], [0.5, 0.5]] names3 = names1[:]
points.sort() names2[0] = 'Vishal'
print(points) names3[1] = 'Jay'
18. What is the output of the following code? sum = 0
a=[101,123,561,[178]] for ls in (names1, names2, names3):
b=list(a) if ls[0] == ' Vishal ':
a[3][0]=915 sum += 2
a[1]=134 if ls[1] == ' Jay ':
print(b) sum += 5
19. What is the output of the following code? print sum
a=[[]]*2 22. What is the output when following code is
a[1].append(9) executed ?
print(a) List = [1, 5, 5, 15, 5, 1]
20. What is the output of the following code? max = List[0]
a=[132,526,127] indexOfMax = 0
a.append([827]) for i in range(1, len(List)):
a.extend([425,627]) if List[i] > max:
print(a) max = List[i]
21. What is the output when following code is indexOfMax = i
executed ? print(indexOfMax)
names1 = ['Freya', 'Mohak', 'Mahesh',
'Dwivedi']

By Amit Kumar Bhatia


Programming in Python

Python Strings
String is the combination of different characters. Strings are amongst the most popular types in Python. In python,
strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows us to
use single quotes, double quotes, or triple quotes to create the string. Python does not have a character data type,
a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.
Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
# Creating a String with single Quotes
String1 = 'Welcome to INDIA'
OUTPUT
String with the use of Single Quotes:
print("String with the use of Single Quotes: ")
Welcome to INDIA
print(String1)
String with the use of Double Quotes:
# Creating a String with double Quotes I'm a Learner
String1 = "I'm a Learner" String with the use of Triple Quotes:
print("\nString with the use of Double Quotes: ") I'm an Indian and I live in "Best Country"
print(String1) Creating a multiline String:
# Creating a String with triple Quotes Computers
String1 = '''I'm an Indian and I live in "Best Country"''' For
Life
print("\nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple Quotes allows multiple lines
String1 = '''Computers
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Strings indexing and splitting


Like other languages, the indexing of the python strings starts from 0. For example, The string "HELLO" is indexed
as given in the below figure.

By Amit Kumar Bhatia


Programming in Python

As shown in python, the slice operator [] is used to access the individual characters of the string. However, we
can use the : (colon) operator in python to access the substring. Consider the following example.

Here, we must notice that the upper range given in the slice operator is always exclusive i.e., if str = 'python' is
given, then str[1:3] will always include str[1] = 'p', str[2] = 'y', str[3] = 't' and nothing else.

Str= “MY INTELLIGENCE” (LENGTH=15)


Str M Y I N T E L L I G E N C E
Forward indexing 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Reverse indexing -15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

String Slicing
To access a range of characters in the String, method of slicing is used. Slicing in a String is done by using a Slicing
operator (colon).
String1 = "MY INTELLIGENCE" OUTPUT
Initial String:
print("Initial String: ")
MY INTELLIGENCE
print(String1)
Slicing characters from 3-12:
# Printing 3rd to 9th character INTELL
print("\nSlicing characters from 3-9: ") Slicing characters between 3rd and 2nd last
print(String1[3:9]) character:
# Printing characters between 3rd and 2nd last character INTELLIGEN
print("\nSlicing characters between 3rd and 2nd last character: ")
print(String1[3:-2])

Deleting/Updating from a String


STRINGS IN PYTHON ARE IMMUTABLE THAT MEANS THEIR VALUE CAN NOT BE CHANGED WHILE LISTS IN PYTHON
ARE MUTABLE.
In Python, Updation or deletion of characters from a String is not allowed. This will cause an error because item
assignment or item deletion from a String is not supported. Although deletion of entire String is possible with the

By Amit Kumar Bhatia


Programming in Python

use of a built-in del keyword. This is because Strings are immutable, hence elements of a String cannot be changed
once it has been assigned. Only new strings can be reassigned to the same name.
Updation of a character:
String1 = "Hello, I'm a Good" OUTPUT: ERROR
print("Initial String: ") Traceback (most recent call last):
print(String1) File “/home/360bb1830c83a918fc78aa8979195653.py”,
line 10, in
# Updating a character of the String
String1[2] = ‘p’
String1[2] = 'p' TypeError: ‘str’ object does not support item assignment
print("\nUpdating character at 2nd Index: ")
print(String1)

Updating Entire String:


String1 = "Hello, I'm a Good"
OUTPUT
Initial String:
print("Initial String: ")
Hello, I'm a Good
print(String1)
Updated String:
# Updating a String Welcome to the World of Computers
String1 = "Welcome to the World of Computers"
print("\n Updated String: ")
print(String1)

Deletion of a character:
# Python Program to Delete OUTPUT: ERROR
Traceback (most recent call last):
# characters from a String
File “/home/499e96a61e19944e7e45b7a6e1276742.py”, line 10, in
String1 = "Hello, I'm a Good" del String1[2]
print("Initial String: ") TypeError: ‘str’ object doesn’t support item deletion
print(String1)
# Deleting a character of the String
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)

Deleting Entire String:


Deletion of entire string is possible with the use of del keyword. Further, if we try to print the string, this will
produce an error because String is deleted and is unavailable to be printed.
String1 = "Hello, I'm a Good" OUTPUT: ERROR
print("Initial String: ") Traceback (most recent call last):
File “/home/e4b8f2170f140da99d2fe57d9d8c6a94.py”, line 12, in
print(String1)
print(String1)
NameError: name ‘String1’ is not defined

By Amit Kumar Bhatia


Programming in Python

# Deleting a String with the use of del


del String1
print("\nDeleting entire String: ")
print(String1)

String Operators
Operator Description

+ It is known as concatenation operator and joins strings given either side of operator.

* It is known as repetition operator. It concatenates the multiple copies of the same string.

[] It is known as slice operator. It is used to access the sub-strings of a particular string.

[:] It is known as range slice operator. It is used to access the characters from the specified
range.

In It is known as membership operator. It returns if a particular sub-string is present in


specified string.

not in It is also a membership operator and does the exact reverse of in. It returns true if a
particular substring is not present in the specified string.

Consider the following example to understand the real use of Python operators.
str = "Hello"
str1 = " world" OUTPUT
print(str*3) # prints HelloHelloHello HelloHelloHello
print(str+str1)# prints Hello world Hello world
o
print(str[4]) # prints o
ll
print(str[2:4]); # prints ll
False
print('w' in str) # prints false as w is not present in str False
print('wo' not in str1) # prints false as wo is present in str1.
Built-in String functions

Method Description

len(string) It returns the length of a string.

islower() It returns true if the characters of a string are in lower case, otherwise false.

isupper() It returns true if characters of a string are in Upper case, otherwise False.

By Amit Kumar Bhatia


Programming in Python

It returns true if the characters in the string are alphanumeric i.e., alphabets
isalnum() or numbers and there is at least 1 character. Otherwise, it returns false.

It returns true if all the characters are alphabets and there is at least one
isalpha() character, otherwise False.

It returns true if all the characters are digits and there is at least one
isdigit() character, otherwise False.

isdecimal() It returns true if all the characters of the string are decimals.

isidentifier() It returns true if the string is the valid identifier.

isnumeric() It returns true if the string contains only numeric characters.

isspace() It returns true if the characters of a string are white-space, otherwise false.

It returns true if the string is titled properly and false otherwise. A title string
istitle() is the one in which the first character is upper-case whereas the other
characters are lower-case.

lower() It converts all the characters of a string to Lower case.

upper() It converts all the characters of a string to Upper Case.

It is used to convert the string into the title-case i.e., The string meEruT will
title() be converted to Meerut.

capitalize() It capitalizes the first character of the String.

swapcase() It inverts case of all characters in a string.

It counts the number of occurrences of a substring in a String between


count(string,begin,end) begin and end index.

It removes all leading whitespaces of a string and can also be used to


lstrip() remove particular character from leading.

strip([chars]) It is used to perform lstrip() and rstrip() on the string.

find(substring ,beginIndex, endIndex) It returns the index value of the string where substring is found between
index(subsring, beginIndex, endIndex) begin index and end index.

It replaces the old sequence of characters with the new sequence. The max
replace(old,new[,count]) characters are replaced if max is given.

Splits the string according to the delimiter str. The string splits according to
split(str,num=string.count(str)) the space if the delimiter is not provided. It returns the list of substring
concatenated with the delimiter.

By Amit Kumar Bhatia


Programming in Python

Assignments (Strings)
1. Write the code to input a string and count the number of alphabets, digits and special characters.
2. Write the code to input a string and count the number of Uppercase and lowercase alphabets.
3. Write the code to input a string and count the number of Spaces.
4. Write a Python program to Check Whether a String is Palindrome or Not.
5. Write the code to input a string and print the string with each alphabet in opposite case.
6. Write the code to input a string and count the number of words.
7. Write the code to input a string and count the number of words starting with alphabet ‘A’.
8. Write the code to input a string and print the length of each word.
9. Write the code to input a string and print only those word whose length is 6
10. Write the code to input a string and reverse it.
11. Write the code to input a string and reverse each word of the string
12. Write the code to input a string and print the longest word.
13. Write a program that asks the user to enter their name in lowercase and then capitalizes the first letter of
each word of their name
14. Write the code to input a string and create a new string in sorted order of length of words.
15. Write a program in python to check if a Substring is Present in a Given String.
16. Write a program that asks the user to enter a string. The program should then print the following:
a. The total number of characters in the string
b. The string repeated 10 times
c. The first character of the string (remember that string indices start at 0)
d. The first three characters of the string e. The last three characters of the string
f. The string backwards g. The string with its first and last characters removed
h. The string in all caps i. The string with every a replaced with an e
j. The string with every letter replaced by a space

By Amit Kumar Bhatia


Programming in Python

WRITE THE OUTPUT OF FOLLOWING PYTHON CODES.


1. What is the output of the following Python program section?
st='Computer Science'
x=st.lower()
y=x.replace('computer','Computer')
print(y)
2. txt='computer science and informatics practices'
words=txt.split(' ')
l=len(words)
print (l)
3. my_string = "python"
i = "i"
while i in my_string:
print(i, end =" ")
4. my_string = "python"
for i in range(my_string):
print(i)
5. my_string = 'python'
for i in range(len(my_string)):
my_string[i].upper()
print (my_string)
6. my_string = 'python'
for i in range(len(my_string)):
print (my_string)
my_string = 'a'
7. word = ‘aeioubcd’
print (word [:3] + word [3:])
8. print("xyz DEF".capitalize())
9. print('*', "python".center(7), '*')
10. print("ayybcyzxcxyy".count('yy'))
11. print("Hello {0} and {1}".format('python', 'java'))
12. print('while'.isidentifier())
13. print('5.1'.isnumeric())

By Amit Kumar Bhatia


Programming in Python

Dictionary in Python
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with
curly brackets, and they have keys and values.
Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is
enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}.
Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the
keys must be of an immutable data type such as strings, numbers, or tuples.
Create and print Dictionary
thisdict = {
"brand": "Ford", OUTPUT
"model": "Mustang", {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
"year": 1964
}
print(thisdict)
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value.
Following is a simple example −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} OUTPUT
print "dict['Name']: ", dict['Name'] dict['Name']: Zara
print "dict['Age']: ", dict['Age'] dict['Age']: 7

If we attempt to access a data item with a key, which is not part of the dictionary, we get an error as follows −
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Alice']: ", dict['Alice']

OUTPUT
dict['Alice']:
Traceback (most recent call last):
File "test.py", line 4, in <module>
print "dict['Alice']: ", dict['Alice'];
KeyError: 'Alice'

There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key: OUTPUT
x = dict.get('Name') Zara
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 as shown below in the simple example −

By Amit Kumar Bhatia


Programming in Python

dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'} OUTPUT


dict['Age'] = 8; # update existing entry dict['Age']: 8
dict['School'] = "N H Goel World School"; # Add new entry dict['School']: N H Goel World School
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() function.
Example: Print the number of items in the dictionary:
print(len(thisdict))
Adding Items in Dictionary Adding an item to the dictionary is done by using a new index key and assigning a
value to it:
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and
changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example: Make a copy of a dictionary with the copy() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = thisdict.copy()
print(mydict)
Another way to make a copy is to use the built-in function dict().
Example: Make a copy of a dictionary with the dict() function:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
mydict = dict(thisdict)
print(mydict)

By Amit Kumar Bhatia


Programming in Python

Deleting Dictionary elements


Removing Items
There are several methods to remove items from a dictionary:
Example: The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.pop("model")
print(thisdict)
Example: The popitem() method removes the last inserted item
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
Example: The del keyword removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Example: The del keyword can also delete the dictionary completely:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.
Example: The clear() method empties the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

By Amit Kumar Bhatia


Programming in Python

thisdict.clear()
print(thisdict)
Properties of Dictionary Keys
Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-
defined objects. However, same is not true for the keys.
There are two important points to remember about dictionary keys −
(a) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys
encountered during assignment, the last assignment wins. For example −
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
OUTPUT: dict['Name']: Manni
(b) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but
something like ['key'] is not allowed. Following is a simple example −
dict = {['Name']: 'Zara', 'Age': 7}
print "dict['Name']: ", dict['Name']
OUTPUT:
Traceback (most recent call last):
File "test.py", line 3, in <module>
dict = {['Name']: 'Zara', 'Age': 7};
TypeError: unhashable type: 'list'
Loop through a Dictionary
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are
the keys of the dictionary, but there are methods to return the values as well.
Example: Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example: Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
Example: You can also use the values() method to return values of a dictionary:
for x in thisdict.values():
print(x)
Example: Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
print(x, y)
Check if Key Exists: To determine if a specified key is present in a dictionary use the in keyword:
Example: Check if "model" is present in the dictionary:

By Amit Kumar Bhatia


Programming in Python

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Nested Dictionary
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Example: Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
if you want to nest three dictionaries that already exists as dictionaries:
Example: Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}

myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}

By Amit Kumar Bhatia


Programming in Python

Built – in Dictionary Functions and Methods


Python includes the following dictionary functions −

SN Function with Description

1 cmp(dict1, dict2): Compares elements of both dict.

2 len(dict): Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.

3 str(dict): Produces a printable string representation of a dictionary

4 type(variable): Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.

Python includes following dictionary methods −

SN Methods with Description

1 dict.clear() : Removes all elements of dictionary dict

2 dict.copy(): Returns a shallow copy of dictionary dict

3 dict.fromkeys(): Create a new dictionary with keys from seq and values set to value.

4 dict.get(key, default=None): For key key, returns value or default if key not in dictionary

5 dict.has_key(key): Returns true if key in dictionary dict, false otherwise

6 dict.items(): Returns a list of dict's (key, value) tuple pairs

7 dict.keys(): Returns list of dictionary dict's keys

dict.setdefault(key, default=None): Similar to get(), but will set dict[key]=default if key is not already
8
in dict

9 dict.update(dict2): Adds dictionary dict2's key-values pairs to dict

10 dict.values(): Returns list of dictionary dict's values

By Amit Kumar Bhatia


Programming in Python

Tuples in Python
A Tuple is a collection of Python objects separated by commas. In some ways a tuple is similar to a list in terms of
indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable. Tuples are
represented and created using small brackets ( ).
Creating Tuples
# Another for doing the same
tup = ("apple", "banana", "cherry")
print(tup)
Output
("apple", "banana", "cherry")
Concatenation of Tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', 'Language')
print(tuple1 + tuple2)
Output:
(0, 1, 2, 3, 'python', ''Language ')
Nesting of Tuples
tuple1 = (0, 1, 2, 3)
tuple2 = ('python', ''Language ')
tuple3 = (tuple1, tuple2)
print(tuple3)
Output :
((0, 1, 2, 3), ('python', 'Language '))
Repetition in Tuples
tuple3 = ('python',)*3
print(tuple3)
Output
('python', 'python', 'python')
Try the above without a comma and check. You will get tuple3 as a string ‘pythonpythonpython’.
Immutable Tuples
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
Output
Traceback (most recent call last):
File "e0eaddff843a8695575daec34506f126.py", line 3, in
tuple1[0]=4
TypeError: 'tuple' object does not support item assignment
Slicing in Tuples
tuple1 = (0 ,1, 2, 3)
print(tuple1[1:])

By Amit Kumar Bhatia


Programming in Python

print(tuple1[::-1])
print(tuple1[2:4])
Output
(1, 2, 3)
(3, 2, 1, 0)
(2, 3)
Deleting a Tuple
tuple3 = ( 0, 1)
del tuple3
print(tuple3)
Error:
Traceback (most recent call last):
File "d92694727db1dc9118a5250bf04dafbd.py", line 6, in <module>
print(tuple3)
NameError: name 'tuple3' is not defined
Finding Length of a Tuple
tuple2 = ('python', 'geek')
print(len(tuple2))
Output
2
Converting list to a Tuple
list1 = [0, 1, 2]
print(tuple(list1))
print(tuple('python')) # string 'python'
Output
(0, 1, 2)
('p', 'y', 't', 'h', 'o', 'n')
Takes a single parameter which may be a list, string, set or even a dictionary ( only keys are taken as elements) and
converts them to a tuple.
Tuples in a loop
tup = ('GOOD',)
n = 5 #Number of time loop runs
for i in range(int(n)):
tup = (tup,)
print(tup)
Output :
(('GOOD ',),)
(((' GOOD',),),)
(((('GOOD',),),),)
(((((‘GOOD',),),),),)
(((((('GOOD',),),),),),)

By Amit Kumar Bhatia


Programming in Python

Python Modules
Consider a module to be the same as a code library. A file containing a set of functions you want to include in your
application. A module is a file containing Python definitions and statements. A module can define functions, classes
and variables. A module can also include runnable code. Grouping related code into a module makes the code
easier to understand and use.
Module allows you to logically organize your Python code. Grouping related code into a module makes the code
easier to understand and use.

# A simple module, calc.py


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
The import statement
We can use any Python source file as a module by executing an import statement in some other Python source
file.When interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches for importing a module. For
example, to import the module calc.py, we need to put the following command at the top of the script :
# importing module calc.py
import calc
print add(10, 2)
Output:
12
The from import Statement
Python’s from statement lets you import specific attributes from a module. The from .. import .. has the following
syntax : from modname import name1[, name2[, ... nameN]]

By Amit Kumar Bhatia


Programming in Python

Example:
# importing sqrt() and factorial from the module math OUTPUT
from math import sqrt, factorial 4.0
print sqrt(16) 720
print factorial(6)
A module is loaded only once, regardless of the number of times it is imported. This prevents the module
execution from happening over and over again if multiple imports occur.
The from...import * Statement
It is also possible to import all names from a module into the current namespace by using the following import
statement − from modname import *
This provides an easy way to import all the items from a module into the current namespace; however, this
statement should be used sparingly.

Python Built-in Functions


The Python built-in functions are defined as the functions whose functionality is pre-defined in Python. The
python interpreter has several functions that are always present for use. These functions are known as Built-in
Functions. There are several built-in functions in Python which are listed below:
Python sum() Function
As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e., list.
s = sum([1, 2,4 ])
print(s)
OUTPUT
7
s = sum([1, 2, 4], 10)
17
print(s)
Python eval() Function
The python eval() function parses the expression passed to it and runs python expression(code) within the
program.
Example:
x=8 OUTPUT
print(eval('x + 1')) 9
Python len() Function
The python len() function is used to return the length (the number of items) of an object.
Example:
strA = 'Python'
print(len(strA))
OUTPUT
6
L=[33,44,55,66]
4
print(len(L))
Python ord() Function
The python ord() function returns an integer representing Unicode code point for the given Unicode character.
print(ord('8'))
print(ord('R')) OUTPUT
56
print(ord('&'))
82
38
By Amit Kumar Bhatia
Programming in Python

Python chr() Function


Python chr() function is used to get a string representing a character which points to a Unicode code integer. For
example, chr(97) returns the string 'a'. This function takes an integer argument and throws an error if it exceeds
the specified range. The standard range of the argument is from 0 to 1,114,111.
result = chr(65) # It returns string representation of a char
result2 = chr(98) OUTPUT
print(result) A
print(result2) b
Python min() Function
Python min() function is used to get the smallest element from the collection. This function takes two arguments,
first is a collection of elements and second is key, and returns the smallest element from the collection.
# Calling function
small = min(2225,325,2025) # returns smallest element
small2 = min(1000.25,2025.35,5625.36,10052.50)
# Displaying result OUTPUT
print(small) 325
print(small2) 1000.25
Python sorted() Function
Python sorted() function is used to sort elements. By default, it sorts elements in an ascending order but can be
sorted in descending also. It takes four arguments and returns a collection in sorted order. In the case of a
dictionary, it sorts only keys, not values.
str = "javatpoint" # declaring string
# Calling function OUTPUT
sorted1 = sorted(str) # sorting string ['a', 'a', 'i', 'j', 'n', 'o', 'p', 't', 't', 'v']
# Displaying result
print(sorted1)
Python pow() Function
The python pow() function is used to compute the power of a number. It returns x to the power of y. If the third
argument(z) is given, it returns x to the power of y modulus z, i.e. (x, y) % z.
print(pow(4, 2)) OUTPUT
print(pow(-4, 2)) 16
print(pow(4, -2)) 16
print(pow(-4, -2)) 0.0625
Python range() Function 0.0625
The python range() function returns an immutable sequence of numbers starting from 0 by default, increments
by 1 (by default) and ends at a specified number.
# empty range
print(list(range(0))) OUTPUT
print(list(range(4))) []
# using the range(start, stop) [0, 1, 2, 3]
print(list(range(1,7 ))) [1, 2, 3, 4, 5, 6]

By Amit Kumar Bhatia


Programming in Python

Python reversed() Function


The python reversed() function returns the reversed iterator of the given sequence.
String = 'Java'
print(list(reversed(String)))
Tuple = ('J', 'a', 'v', 'a')
print(list(reversed(Tuple)))
OUTPUT
[‘a’, ‘v’, ‘a’, ‘J’ ]
Range = range(8, 12)
[‘a’, ‘v’, ‘a’, ‘J’ ]
print(list(reversed(Range))) [11, 10, 9, 8]
List = [1, 2, 7, 5] [5, 7, 2, 1]
print(list(reversed(List)))
Python round() Function
The python round() function rounds off the digits of a number and returns the floating point number.
# for integers
print(round(10)) OUTPUT
# for floating point 10
print(round(10.8)) 11
# even choice 7
print(round(6.6))
Random Numbers in Python
Python defines a set of functions that are used to generate or manipulate random numbers. This particular type of
functions are used in a lot of games, lotteries or any application requiring random number generation.
random() :- This number is used to generate a float random number less than 1 and greater or equal to 0.
randint() is an inbuilt function of the random module in Python3. The random module gives access to various
useful functions and one of them being able to generate random numbers, a random integer in range including
the end points.
Syntax: randint(start, end)
Example:
Import random() OUTPUT
Random number between 0 and 1 is: 0.7072527917168734
r=random.random()
Random number between 0 and 10 is 5
print("Random number between 0 and 1 is, r) Random number between -10 and -1 is -7
r1 = random.randint(0, 10) Random number between -5 and 5 is 2 10
print("Random number between 0 and 10 is, r1) 11
r2 = random.randint(-10, -1) 7
print("Random number between -10 and -1 is, r2)
r3 = random.randint(-5, 5)
print("Random number between -5 and 5 is, r3)

By Amit Kumar Bhatia


Programming in Python

Python math module

By Amit Kumar Bhatia


WORKING WITH FUNCTIONS
FUNCTION:
A function is a named part of a program which performs some specific work in the program and can be invoked /
called / executed from other parts of the program. Functions support the concepts of Modular Programming which
states that a larger problem may be subdivided into smaller parts by which the problem becomes more specific
and easily understandable.
A function is a set of statements that take inputs, do some specific computation and produce output. Since larger
programs are difficult to manage, hence the idea is to put some commonly or repeatedly done tasks together and
make a function so that instead of writing the same code again and again for different inputs, we can call the
function.
There are two types of functions: Standard Library Functions and User defined Functions.
Library Functions: Functions that readily comes with Python are called built-in functions. Set of functions is
stored in a file called MODULE, and this approach is known as MODULARIZATION. These are also known as built –
in or readymade functions. For example print (), pow(), append() etc.
User defined functions: The functions which are created according to the need of the programmer are known
as User – Defined Functions.
Advantages of user-defined functions
 User-defined functions help to decompose a large program into small segments which makes program easy
to understand, maintain and debug.
 If repeated code occurs in a program. Function can be used to include those codes and execute when
needed by calling that function.
 Programmers working on large project can divide the workload by making different functions.
Steps to Create User – Defined Functions
 In Python, a user-defined function's declaration begins with the keyword def followed by the function name.
 Function name must be unique and follows naming rules same as for identifiers. The function may take
arguments(s) as input within the opening and closing parentheses, just after the function name followed by a
colon (:) to mark the end of function header.
 After defining the function name and arguments(s), a block of program statement(s) start at the next line and
these statement(s) must be indented. These statement define the working of function and this block is known
as BODY of the function.
 We may have an optional return statement to return a value from the function.
 For the execution of the function, it is to be called by supplying the required number of values (parameters) along with
its name.
Here is the syntax of a user defined function.
Syntax: def function_name (argument1, argument2, ...):
Statement_1
Statement_2 Body of the Function
………………....
User Defined function can be
 Function with no arguments and no return
 Function with arguments but no return value
 Function with arguments and return value
 Function with no argument but return value
WORKING OF A USER DEFINED FUNCTION
Example: Program to find the sum of two numbers
a=int (input("Enter First Number :"))
b=int (input("Enter Second Number :"))
c=a + b
print("Sum=",c)

PROGRAM USING FUNCTION WORKING OF PROGRAM WITH FUNCTION


def sum(x, y):
CALLING FUNCTION
z=x + y
a=int(input("Enter First Number :"))
return z
b=int(input("Enter Second Number :"))
#main program
a=int(input("Enter First Number :"))
c=sum(a,b) # function call
b=int(input("Enter Second Number :")) print("Sum=",c)
Name of the function
sum(a,b)
print("Sum=",c) Called Function
 a and b are known as Actual Parameters, which a calling def sum(x,y):
Function passes to the called function at the time of function call.
 x and y are known as Formal Parameters
z=x+y Function Definition

 Actual and formal parameters can have same names return z (Body of the function)
 Function is called by supplying the required number of values.
 If called function is returning any value, it must be stored
Or used in some way.
Keyword to define the function

Difference between Method and Function


Simply, function and method both look similar as they perform in almost similar way, but the key difference is the
concept of ‘Class and its Object‘. Functions can be called only by its name, as it is defined independently. But
methods can’t be called by its name only, we need to invoke the class by a reference of that class in which it is
defined, i.e. method is defined within a class and hence they are dependent on that class.
Difference between Parameter and Argument
The terms parameter and argument can be used for the same thing: information that are passed into a function.
A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that
are sent to the function when it is called.
Difference between Calling and Called Function
The function which sends the values (Parameters at the time of function call is known as CALLING FUNCTION and
the function which receives the values of Parameters (in arguments) is known as called function.
Examples on Functions
a) Function with no arguments and no return: These functions are also known as void functions.

b) Function with arguments and no return value:


# A simple Python function to check whether x is even or odd
def evenOdd( x ):
if (x % 2 == 0):
print(x, “is even") OUTPUT
else: 2 is even
print(x, “is odd") 3 is odd
# Main Program
evenOdd(2) #calling
evenOdd(3) #calling

c) Function with arguments and return value: We can return single or multiple values from function
using return keyword. The return value must be used at the calling place by
 Either store it any variable
 Use with print()
 Use in any expression

# A simple Python function to print the sum of all numbers from 1 to n where n is entered by the user.
def findsum( x ):
s=0
for a in range(1, x+1):
s=s+a
return s
OUTPUT
# Main Program
Enter a number 12
n = int(input(“Enter a number”))
Sum of numbers from 1 to 12 is 78
sum=findsum(n)
print(“Sum of numbers from 1 to”, n, “is”, sum)
# A simple Python function to find the reverse of a number.
def reverse( x ):
r=0
while x>0:
d = x % 10 OUTPUT
r = r * 10 + d Enter a number 367
x = x // 10 Reverse of 367 is 763
return r
# Main Program
n = int(input(“Enter a number”))
print(“Reverse of “, n, “is”, reverse(n))

Returning Multiple Values from a function: Unlike other programming languages, python lets you
return more than one value from function. If multiple values are returned by a function, they can be stored in the
equal number of variables or they can be stored in a tuple.
# A simple Python function to find the total marks and percentage of marks of 5 subjects.
def result(m1, m2, m3, m4, m5):
t=m1+m2+m3+m4+m5
p=t*100/500
return t, p
# Main Program
m1=float(input("Enter the marks of Subject 1 : ")) OUTPUT
m2=float(input("Enter the marks of Subject 2 : ")) Enter the marks of Subject 1: 66
m3=float(input("Enter the marks of Subject 3 : ")) Enter the marks of Subject 2: 88
m4=float(input("Enter the marks of Subject 4 : ")) Enter the marks of Subject 3: 95
m5=float(input("Enter the marks of Subject 5 : ")) Enter the marks of Subject 4: 81
tot, per= result(m1, m2, m3, m4, m5) Enter the marks of Subject 5: 78
print("Total Marks : ", tot) Total Marks: 408.0
Percentage : 81.6
print("Percentage : ", per)
OR
def result(m1, m2, m3, m4, m5):
t=m1+m2+m3+m4+m5
p=t*100/500
return t, p
# Main Program
m1=float(input("Enter the marks of Subject 1 : ")) OUTPUT
m2=float(input("Enter the marks of Subject 2 : ")) Enter the marks of Subject 1: 66
m3=float(input("Enter the marks of Subject 3 : ")) Enter the marks of Subject 2: 88
m4=float(input("Enter the marks of Subject 4 : ")) Enter the marks of Subject 3: 95
m5=float(input("Enter the marks of Subject 5 : ")) Enter the marks of Subject 4: 81
res= result(m1, m2, m3, m4, m5) Enter the marks of Subject 5: 78
print("Total Marks : ", res[0]) Total Marks: 408.0
Percentage : 81.6
print("Percentage : ", res[1])
Default arguments: We can provide default values for our arguments while defining the function. In this case
if we are not passing any value at the time of function call, then default values will be considered. If a function has
any argument with default value then all its proceeding arguments must have default values.
Example: def interest (principal, rate, time=15): #valid
def interest (principal, rate=8.5, time=15): #valid
def interest (principal, rate=8.5, time): #invalid
# A simple Python function to demonstrate use of default arguments.
def draw (symbol= ‘@’, times=10): OUTPUT
for a in range(times): ##########
print(symbol, end= ‘ ’) $$$$$$$$$$
# Main Program @@@@@@@@@@@@@@@
draw()
draw(‘#’)
draw(‘$’, 15)

METHODS OF FUNCTION CALLING


Call by value Method: In Python every variable name is a reference to a memory location. When we pass a
variable (Actual parameter) to a function, a new reference to the object (Formal Parameter) is created. Hence if we
change the values of formal parameters then changes are not reflected in actual parameters.
Example:
# Python program to demonstrate call by value method
def myFun(x):
print("Value received:", x)
x=x+10
print("Changed value:", x) OUTPUT
This output shows that the
# Main Program Original value: 25
changes made in formal
a=25 Value received: 25
parameters are not reflected
print(“Original value :”,a) Changed value: 35
in actual parameters.
myFun(x) # function called Now the value is: 25
print("Now the value is:", x)
If the actual argument variable represents an immutable object such as int, float, tuple, or a string, any modification
inside function will result in creating a different object (which will be local to the called function) and not affect the
original variable.
Call by Reference Method: If the actual argument variable represents a mutable object such as List or
dictionary, any modification performed on formal arguments inside function will be directly reflected in actual
arguments.
Example:
# Python program to demonstrate call by value method by passing LIST as argument
def fun(a):
a.append (40) OUTPUT This output shows that the
print("Inside function call", a) Before function call [10, 20, 30] changes made in formal
# Main Program Inside function call [10, 20, 30, 40] parameters are reflected in
L=[10, 20, 30] After function call [10, 20, 30, 40] actual parameters.
print("Before function call", L)
fun(L)
print("After function call", L)

Example:
# Python program to demonstrate call by value method by passing DICTIONARY as argument
def fun(d1):
d1["AGE"]=17
print("Dictionary Inside function call",d1)
OUTPUT
# Main Program
Dictionary Before function call {'RN': 1, 'NAME': 'Priyanka'}
d={'RN':1, 'NAME':"Priyanka"} Dictionary Inside function call {'RN': 1, 'NAME': 'Priyanka', 'AGE': 17}
print("Dictionary Before function call",d) Dictionary After function call {'RN': 1, 'NAME': 'Priyanka', 'AGE': 17}
fun(d)
print("Dictionary After function call",d)
********************************************************************************************
Scope and Lifetime of Variables
Scope refers to the visibility of variables and Lifetime of variable refer to the duration for which the variable exists.
In Python there are broadly 2 kinds of Scopes: Global Scope and Local Scope
Lifetime is the time for which a variable lives in memory. For Global variables the lifetime is entire program run i.e.
as long as program is executing. For Local variables lifetime is their function’s run i.e. as long as function is
executing.
Local Scope / Local Variables
Local Variables are variable that are declared inside method or block. Local variables are accessible only within the
declared method or block and cannot assessable outside that method or block. A name declare in a function body
is said to have local scope i.e. it can be used only within this function and the other block inside the function. The
formal parameters are also having local scope.
Global Scope / Global Variables
A name declared in top level segment (main) of a program is said to have global scope and can be used in entire
program. Variable defined outside all functions are global variables.
Name Resolution (Scope Resolution): If a function has used a variable which is not declared in it then it checks
the variable whether it has been declared in global scope, if it is found then it access the value of that global variable
otherwise gives an error.
Local variables can have the same name as global variables (those declared outside of any function). In that case,
the global variable is inaccessible from within the function.
Example:
# Python program to demonstrate the Local and Global scope of variables
def fun1():
a=10 # Local to fun1()
print("a from fun1():",a)
print("c from main in fun1():",c) # Accessing Global Variable c

def fun2():
b=20 # Local to fun2()
print("b from fun2():",b)
print("c from main in fun2():",c) # Accessing Global Variable c

def fun3():
print("c from main in fun3():",c) # Accessing Global Variable c

def fun4():
c=55 OUTPUT
print("c from fun4():",c) # Accessing Local Variable c a from fun1(): 10
c from main in fun1(): 30
# Main Program b from fun2(): 20
c=30 # Global variable c from main in fun2(): 30
c from main in fun3(): 30
fun1()
c from fun4(): 55
fun2() c inside main= 30
fun3()
fun4()
print("c inside main=",c)
********************************************************************************************

RECURSION
It is one of the most powerful tool in programming language. It is a process where function calls itself again and
again. Recursion basically divides the big problem into small problems up to the point where it can be solved easily,
for example if we have to calculate factorial of a 5, we will divide factorial of 5 as 5* factorial(4), then 4*factorial(3),
then 3*factorial(2), then 2*factorial(1) and now factorial of 1 can be easily solved without any calculation, now
each pending function will be executed in reverse order.
Condition for Implementing Recursion
 It must contain BASE CONDITION i.e. at which point recursion will end otherwise it will become infinite.
 BASE CONDITION is specified using to specify the termination condition.
 Execution in Recursion is in reverse order using STACK. It first divide the large problem into smaller units and
then starts solving from bottom to top.
Advantages of Recursion
 Recursive functions make the code look clean and elegant.
 A complex task can be broken down into simpler sub-problems using recursion.
 Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
 The computer may run out of memory if recursion becomes infinite or termination condition not specified.
 It is less efficient in terms of speed and execution time.
 Sometimes the logic behind recursion is hard to follow through.
 It takes more memory as compare to LOOP statement because with every recursion call memory space is
allocated for local variables.
 Recursive functions are hard to debug.

Example 1: Sum of all numbers from 1 to 10


Using for Loop Using Recursive Function
def sum(n): def sum(n):
total = 0 if n > 0:
return n + sum(n-1)
for index in range(n+1):
return 0
total += index
return total result = sum(100)
print(result)
result = sum(100)
print(result)

Example 2: Factorial of a number using Recursion


DATA STRUCTURE IN PYTHON
DATA STRUCTURE IN PYTHON
Data structures are a way of organizing and storing data so that they can be accessed and worked with
efficiently. They define the relationship between the data, and the operations that can be performed on
the data.
data structures can be classified into two types — primitive and non-primitive. The former is the basic way
of representing data which contain simple values. The latter is a more advanced and a complex way of
representing data that contain a collection of values in various formats.
Non primitive data structures can further be categorized into built-in and user defined structures. Python
offers implicit support for built in structures that include List, Tuple, Set and Dictionary. Users can also
create their own data structures (like Stack, Tree, Queue, etc.) enabling them to have a full control over
their functionality.
SEARCHING IN A LIST
Linear / Sequential Search: In this search the search value is compared with each element of the list
right from beginning, whenever the matching value is found, the search stops at that point otherwise the
search continues till last element of the list.
L=[12,25,19,13,27,44,56,18] n(size)=8 val (Value to search) = 27

ELEMENTS 12 25 19 13 27 44 56 18
INDEXES 0 1 2 3 4 5 6 7(n-1)
i i=0 i=1 i=2 i=3 i=4

Val=27

SEARCH ENDED (i=4)

PROGRAM / FUNCTION FOR LINEAR SEARCH


Q: Define a python function lsearch(LIST,val) to search for an element “val” in the a list “LIST” using linear
search method. The function returns the position of the element if it is found otherwise returns –1.
def lsearch(LIST, val):
for i in range(0,len(LIST)):
if LIST[i]==val:
return i+1
return -1

L=[]
n=int(input("How many values do you want ?"))
print("Enter Elements")
for i in range(0,n):
L.append(int(input()))
value=int(input("Enter value to search:"))
k=lsearch(L,value)
if k==-1:
print("Element not found:")
else:
print("Element found at position",k)
Linear search analysis
 Each element of linear list is compared with the given item to be searched one by one. This method
traverse the linear list sequentially to locate the given item.
 For Linear Searching item need not be in any order, it can be performed on random list.
 Linear Searching is suitable for small list only.
 Best Case: when item to be search is at first position
 Worst Case: when item to be search is at last position or not present.
 Average Case: when item is somewhere in list other than first or last position.

BINARY SEARCHING: This method works only on sorted arrays and is also known as DIVIDE AND RULE
METHOD. In this method, the list is divided into two parts and middle element is taken. Now, the search
value is compared with mid element, if they are equal then the search stops. If the middle element is smaller
than the search value then the search continues in right section of the array and the left part if not checked
(in case of ascending order). If the middle element is greater than the search value then the search continues
in the left section of the list and right section is not checked. This process is repeated till the element is not
found.

L=[3,12,19,23,27,45,56,58] n(size)=9 val (Value to search) = 56

ELEMENTS 3 12 19 23 27 45 56 58 65
INDEXES 0 1 2 3 4 5 6 7 8(n-1)
LB=0 mid LB=5 UB=8

EXPLANATION / DRY RUN / TRACING


VAL=56 LB=0, UB=8 MID=(LB+UB)/2 = (0+8)/2=4
L[MID]==VAL----- L[4]==VAL---->27==56-----FALSE
L[MID]>VAL--->27>56-----FALSE
L[MID]<VAL--->27<56-----TRUE-----LB=MID+1 = LB=4+1=5(LEFT PART NOT REQUIRED TO CHECK)
NOW REMAINING LIST TO CHECK IS
45 56 58 65
5 6 7 8(n-1)
LB=5 UB=8

LB=5, UB=8 MID=(LB+UB)/2 = (5+8)/2=6


L[MID]==VAL----- L[6]==VAL---->56==56-----TRUE RETRUNS MID+1 = 6+1=7(POSITION)
PROGRAM / FUNCTION FOR BINARY SEARCH
Q: Define a python function bsearch(mylist, item) to search for an element “item” in the a list “mylist”
using Binary search method. The function returns the position of the element if it is found otherwise
returns –1.

def bsearch(mylist,item):
lb = 0
ub = len(mylist)-1
while(lb<=ub):
mid = (lb+ub)//2
if mylist[mid]==item:
return mid+1
elif mylist[mid]<item:
ub = mid-1
else:
lb = mid+1
return -1
L=[]
n=int(input("How many values fo you want ?"))
print("Enter Elements")
for i in range(0,n):
L.append(int(input()))
value=int(input("Enter value to search:"))
k=bsearch(L,value)
if k==-1:
print("Element not found:")
else:
print("Element found at position",k)

Binary search analysis


 Data must be SORTED either in ascending or descending order to search using binary method.
 Searching Starts from the middle position.
 To find middle position Mid = (lower bound + higher bound) / 2
 If middle value is equal to search element “SEARCH SUCCESSFUL”
 If middle value if larger than search value, searching continues towards left of middle position
otherwise towards right side of middle position. [for data arranged in ascending order else vice versa]
 Best case is when the element to search is at the middle.
 Worst case is when only one element (lb=ub) is remaining to compare after repeating the process.
 Takes less time compare to Linear searching
 Suitable for LARGE list
SORTING ON LISTS
SELECTION SORT: In this method, the first value of the list is taken from the beginning and is compared with each element
of the list one by one for finding the minimum value of the list along with its index number. After one complete pass, the
minimum value is swapped with the first element. At this point the minimum value of the list moves to the first position.
Now the second value is taken from the beginning and is compared with rest elements of the list one by one for finding the
minimum value of the list along with its index number. After second pass, the minimum value is swapped with the second
element. At this point the second smallest value of the list moves to the second position. This process is repeated for total n-1
passes where n is the size of the list.

STEPS OF SELECTION SORT


PROGRAM OF SELECTION SORT
L=[]
n=int(input("Number of elements"))
for k in range(0,n):
b=int(input("Enter element"))
L.append(b)
print(“Original List:”, L)
for i in range(0,n-1):
min=L[i]
pos=i
for j in range(i+1,n):
if(L[j]<min):
min=L[j]
pos=j
L[i],L[pos]=L[pos],L[i]
print(“Sorted List:”, L)

PROGRAM USING FUNCTION OF SELECTION SORT


#FUNCTION
def selection_sort(L):
for i in range(0,n-1):
min=L[i]
pos=i
for j in range(i+1,n):
if(L[j]<min):
min=L[j]
pos=j
L[i],L[pos]=L[pos],L[i]

#MAIN PROGRAM
LIST=[]
n=int(input("Number of elements"))
for k in range(0,n):
b=int(input("Enter element"))
LIST.append(b)
print(“Original List:”, LIST)
selection_sort(LIST) #Function called
print(“Sorted List:”, L)
BUBBLE SORT: In this method, the consecutive pair of elements of the list is compared and if they are out of required
order then they are swapped. Now the next pair of elements of the list is compared and if they are also out of required order
then they are also swapped. After one complete pass, the largest value of the list moves to the last position.
In second pass also the same process is repeated and after second pass, the second largest value of the list moves to the second
last position. This process is repeated till the list is not sorted. If there are n elements then total n – 1 passes are required. In
first pass, there are n – 1 steps and with each pass, the steps are reduced by 1

STEPS OF BUBBLE SORT


LIST 9 6 3 5 2 1

STEP 1 6 9 3 5 2 1

STEP 2 6 3 9 5 2 1

PASS 1 STEP 3 6 3 5 9 2 1

STEP 4 6 3 5 2 9 1

STEP 5 6 3 5 2 1 9

STEP 1 3 6 5 2 1 9

STEP 2 3 5 6 2 1 9
PASS 2
STEP 3 3 5 2 6 1 9

STEP 4 3 5 2 1 6 9

STEP 1 3 5 2 1 6 9

PASS 3 STEP 2 3 2 5 1 6 9

STEP 3 3 2 1 5 6 9

STEP 1 2 3 1 5 6 9
PASS 4
STEP 2 2 1 3 5 6 9

PASS 5 STEP 1 1 2 3 5 6 9
PROGRAM OF BUBBLE SORT
L=[]
n=int(input("Number of elements"))
for k in range(0,n):
b=int(input("Enter element"))
L.append(b)
print(“Original List:”, L)
for i in range(0,n-1):
for j in range(0,n-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print(“Sorted List:”, L)

PROGRAM USING FUNCTION OF BUBBLE SORT


#FUNCTION
def bubble_sort(L):
for i in range(0,n-1):
for j in range(0,n-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]

#MAIN PROGRAM
LIST=[]
n=int(input("Number of elements"))
for k in range(0,n):
b=int(input("Enter element"))
LIST.append(b)
print(“Original List:”, LIST)
bubble_sort(LIST) #Function called
print(“Sorted List:”, L)
INSERTION SORT: In this method, the list is divided into two parts; Sorted and Unsorted. The elements from the
unsorted part are compared with the elements of sorted part one by one and the elements are inserted at proper place one
by one. This process is repeated till the list is not sorted.

STEPS OF INSERTION SORT


UNSORTED PART
SORTED PART
8 4 6 5 2 3 1

4 8 6 5 2 3 1

4 6 8 5 2 3 1

4 5 6 8 2 3 1

2 4 5 6 8 3 1

2 3 4 5 6 8 1

1 2 3 4 5 6 8
Explanation / DRY RUN / TRACING
PROGRAM OF INSERTION SORT
LIST 8 4 6 5 2 3 1
L=[]
INDEX Nos. 0 1 2 3 4 5 6 n=int(input("Number of elements"))
for k in range(0,n):
i=1 temp=L[i] = L[1] = 4 j=1–1=0
b=int(input("Enter element"))
temp < a[j]  temp < a[0] 4 < 8  true;
L.append(b)
j>=0true
 L[j+1]=L[j]  L[0+1] = L[0]  L[1]=L[0]  L[1]=8 print("Original List:", L)
j=0-1 j = –1 for i in range(1, len(L)):

LIST AT THIS 8 8 6 5 2 3 1 temp=L[i]


POINT j=i-1
0 1 2 3 4 5 6
while j >=0 and temp<L[j] :
j>=0false (WHILE LOOP ENDED)
L[j+1]=temp  L[–1+1]=temp  L[0] =4 L[j+1]=L[j]

LIST AT THIS 4 8 6 5 2 3 1 j = j-1


POINT L[j+1] = temp
0 1 2 3 4 5 6
print("Sorted List:", L)

i=2 temp=L[2] = L[2] = 6 j=2–1=1


temp < a[j]  temp < a[1] 6 < 8  true;
j>=0true
 L[j+1]=L[j]  L[1+1]=L[1]  L[2]=L[1]  L[2]=8
j=1-1 j = 0

LIST AT THIS 4 8 8 5 2 3 1
POINT
0 1 2 3 4 5 6
temp < a[j]  temp < a[0] 8 < 4  FALSE (WHILE LOOP ENDED)
L[j+1]=temp  L[0+1]=temp  L[1] =6

LIST AT THIS 4 6 8 5 2 3 1
POINT
0 1 2 3 4 5 6
PROGRAM USING FUNCTION OF INSERTION SORT
#FUNCTION
def insertion_Sort(L):
for i in range(1, len(L)):
temp=L[i]
j=i-1
while j >=0 and temp<L[j] :
L[j+1]=L[j]
j = j-1
L[j+1] = temp

# MAIN FUNCTION
LIST=[]
n=int(input("Number of elements"))
for k in range(0,n):
b=int(input("Enter element"))
LIST.append(b)
print("Original List:", LIST)
insertion_Sort(LIST) #Function called
print("Sorted List:", LIST)
STACK: In the English dictionary the word stack means arranging objects one over another. Stack is a special form
of list with the restriction of LIFO, i.e. the last entered element will be deleted first. It stores the data elements in a
similar fashion as a bunch of plates are stored one above another in the kitchen. Addition and Deletion of takes place
only from one end known as “TOP” of the stack. Two types of operations can be performed on STACKS namely PUSH
and POP.
PUSH OPERATION: It means addition of new elements in the stack which starts from 1 st element and goes
sequentially. TOP is a variable which keeps the track of the latest entered element. With each addition the value of
TOP is increased by 1.
POP OPERATION: It means deletion of elements from the stack which starts from the topmost element (Last entered
element). Precisely, the element at the TOP is removed and with every deletion the value of the TOP is decreased by
1. When the value of TOP reaches to – 1, it indicates that the list is empty and the situation of further attempt to
deletion is known as UNDERFLOW.

Initially LIST is empty TOP = – 1 (Underflow)

PUSH OPERATION LIST POP OPERATION


POSITION OF STACK INDEX POSITION OF
TOP=TOP+1 TOP=TOP – 1
TOP STATUS NOS. TOP
ADD “29” TOP=0 29 0 REMOVE 29 TOP=0
ADD “53” TOP=1 53 1 REMOVE 53 TOP=1
ADD “14” TOP=2 14 2 REMOVE 14 TOP=2
ADD “41” TOP=3 41 3 REMOVE 41 TOP=3
ADD “27” TOP=4 27 4 REMOVE 27 TOP=4
ADD “66” TOP=5 66 5 REMOVE 66 TOP=5
MENU BASED PROGRAM FOR STACK OPERATIONS
# PUSH FUNCTION
def spush(stack, val):
stack.append(val)

# POP FUNCTION
def spop(stack):
if len(st)==0:
return None
else:
return stack.pop()

# DISPLAY FUNCTION
def disp(stack):
print("The current status of stack is :",end='')
if len(stack)==0:
print("NO ELEMENT PRESENT")
else:
print(stack)

st=[]
while(True):
print("\n\nMenu")
print("1. Push an Item into stack")
print("2. Pop an item from Stack")
print("3. Display Stack")
print("4. Quit")
ch=int(input("Enter your choice :"))

if ch==1:
pushval=int(input("Enter the value to push :"))
spush(st,pushval)

elif ch==2:
popval=spop(st)
if popval==None:
print("STACK UNDERFLOW... NO ELEMENT PRESENT")
else:
print("You removed",popval)

elif ch==3:
disp(st)

else:
print("Thanks for using the program....Quitting")
break
Sample Question: Write a function in Python PUSH(Arr), where Arr is a list of numbers. From this list push all numbers divisible
by 5 into a stack implemented by using a list. Display the stack if it has at least one element, otherwise display appropriate error
message.
Ans:
def PUSH(Arr):
s=[]
for x in range(0,len(Arr)):
if Arr[x]%5==0:
s.append(Arr[x])
if len(s)==0:
print("Empty Stack")
else:
print(“Stack is “, s)

Sample Question: Write a function in Python POP(Arr), where Arr is a stack implemented by a list of numbers. The function
returns the value deleted from the stack
Ans:
def popStack(st) :
if len(st)==0:
print("Underflow")
else:
return st.pop()
Queue: A Queue is a special form of list which follows the First-in-First-Out (FIFO) principle which means that the
first entered element will be deleted first. For example a queue of customers in a Bank where the person who comes
in the queue first, comes out first. It is opened from both the ends hence we can easily add elements to the back and
can remove elements from the front. To implement a queue, we need two simple operations:
ADDITION OPERATION: It means addition of new elements in the Queue and the operation is also known as “ENQUE”.
Addition starts from one end known as “REAR” end. REAR is a variable which keeps the track of the latest entered
element. With each addition the value of REAR is increased by 1.
DELETION OPERATION: It means deletion of elements from the queue and the operation is also known as “DEQUE”.
Deletion occurs at other end known as “FRONT” end. Precisely, If the list is empty and the situation of further attempt
to deletion is known as UNDERFLOW.

Few more functions are required to make the above-mentioned queue operation efficient. These are −

peek() – The peek operation is used isfull() − Checks if the queue is full. isempty() − Checks if the queue is
to get the element at the front of Code: empty.
the queue without removing it.
def isfull(queue, maxsize): Code:
Code: def peek(queue): if length(queue)==maxsize: def isfull(queue):
return queue[0] print(“Queue is full”) if length(queue)==0:
print(“Queue is Empty”)
MENU BASED PROGRAM FOR QUEUE OPERATIONS
# ADD FUCNTION
def qadd(q, val):
q.append(val)

# DELETE FUCNTION
def qdel(q):
if len(q)==0:
return None
else:
return q.pop(0)

# DISPLAY FUCNTION
def disp(q):
print("The current status of Queue is :",end='')
if len(q)==0:
print("NO ELEMENT PRESENT")
else:
print(q)

queue=[]
while(True):
print("\n\nMenu")
print("1. Add an Item into Queue")
print("2. Remove an item from Queue")
print("3. Display Queue")
print("4. Quit")
ch=int(input("Enter your choice :"))

if ch==1:
addval=int(input("Enter the value to add :"))
qadd(queue,addval)

elif ch==2:
remval=qdel(queue)
if remval==None:
print("QUEUE UNDERFLOW... NO ELEMENT PRESENT")
else:
print("You removed",remval)

elif ch==3:
disp(queue)

else:
print("Thanks for using the program....Quitting")
break
DATA FILE HANDLING IN PYTHON
Introduction
In programming, Sometimes, it is not enough to only display the data on the console. Those data are to be
retrieved later on, then the concept of file handling comes. It is impossible to recover the programmatically
generated data again and again. However, if we need to do so, we may store it onto the file system which
is not volatile and can be accessed every time. Here, comes the need of FILE HANDLING in Python. So far
in our python program the standard input in coming from keyboard an output is going to monitor i.e.
nowhere data is stored permanent and entered data is present as long as program is running. File handling
in Python enables us to create, update, read, and delete the files stored on the file system through our
python program. It is a mechanism by which we can read data of disk files in python program or write back
data from python program to disk files.
DATA FILES:
A file is a sequence of bytes on the disk/permanent storage where a group of related data is stored. File is
created for permanent storage of data. It contains data pertaining to a specific application, for later use.
The data files are of 2 types: Text Files and Binary Files
Text File: A file whose contents can be viewed using a text editor is called a text file.
 Text file stores information in ASCII OR UNICODE character. In text file everything will be stored as
a character for example if data is a string value “ABCDEFGH” then it will take 8 bytes and if the data
is floating value like 11237.9876 it will take 10 bytes.
 In text file each line is terminated by special character called EOL. In text file some translation takes
place when this EOL character is read or written. In python EOL is ‘\n’ or ‘\r’ or combination of both.
Binary files
 It stores the information in the same format as in the memory i.e. data is stored according to its
data type so no translation occurs.
 In binary file there is no delimiter for a new line
 Binary files are faster and easier for a program to read and write than text files.
 Data in binary files cannot be directly read, it can be read only through python program for same.
Steps in Data File Handling
1. OPENING FILE: We should first open the file for read or write by specifying the name of file and
mode.
2. PERFORMING READ/WRITE: Once the file is opened now we can either read or write for which file
is opened using various functions available
3. CLOSING FILE: After performing operation we must close the file and release the file for other
application to use it.
Opening File To perform any file operation, it must be opened first then after reading, writing or
editing operation can be performed. To create any new file also, it must be opened. On opening of any
file, a file relevant structure is created in memory as well as memory space is created to store contents.
File can be opened for either reading, writing or appending.
SYNTAX: file_object = open(filename) OR file_object = open(filename,mode)
(** default mode is “read”)
Example: myfile = open(“story.txt”)
Here disk file story.txt is loaded in memory and its reference is linked to myfile object, now python program
will access story.txt through myfile object. The file story.txt is present in the same folder where .py file is
stored otherwise if disk file to work is in another folder we have to give full path.
Example: myfile=open(“article.txt”, “r”)
Here “r” is for read (although “r” is by default, we can use “a” for append and “w” for write.
Example: myfile = open(“d:\\mydata\\poem.txt”) Here separate location i.e. d:\mydata folder.
At the time of giving path of file we must use double backslash (\\) in place of single backslash because in
python single slash is used for escape character and it may cause problem like if the folder name is amit
and we provide path as d:\amit\poem.txt then in \amit \ will become escape character for new line, SO
ALWAYS USE DOUBLE BACKSLASH IN PATH.
Another solution of double backslash is raw string i.e. no special meaning attached to any character as:
Myfile = open(r“d:\mydata\poem.txt”)
File Handler or File Object
Myfile = open(r“d:\mydata\poem.txt”)
In the above example Myfile is the file object or file handle or file pointer holding the reference of disk file.
In python we will access and manipulate the disk file through this file handle only.
File Access Mode: File modes describe how a data file should be used in a program i.e. for reading
or writing or appending. Here is the list of available file modes.
Closing file: When we are done working with the file, we should close the file. Closing a file releases
valuable system resources. In case we forgot to close the file, Python automatically close the file when
program ends or file object is no longer referenced in the program. However, if our program is large and
we are reading or writing multiple files that can take significant amount of resource on the system. If we
keep opening new files carelessly, we could run out of resources. Hence close the file as soon as all task
are done with it. Example: myfile.close()
Note: open function is built-in function used standalone while close() must be called through file handle
with statement: It is mandatory to close the file which has been opened for any task. If we use “with”
statement while opening the file, there is no need to call file.close() to close the data file. It automatically
closes the data file. The ‘with’ statement itself ensures proper acquisition and release of resources.
Example: with open(“article.txt”, “r”) as myfile (** myfile is the file object)
File object attributes:
 closed: It returns true if the file is closed and false when the file is open.
 mode: Returns file opening mode.
 name: Returns the name of the file which file object holds.
Example: f = open("a.txt", 'a+')
OUTPUT
print(f.closed) False
print(f.mode) a+
a.txt
print(f.name)

TEXT FILE OPERATIONS


Writing into a Text file
For writing to a file, we first need to open it in write or append mode. If we open an existing file in write
mode, the previous data will be erased, and the file object will be positioned at the beginning of the file.
On the other hand, in append mode, new data will be added at the end of the previous data as the file
object is at the end of the file. After opening the file, we can use the following methods to write data in
the file.
 write() - for writing a single string
 writeline() - for writing a sequence of strings
The write () method:
The write() method takes a string as an argument and writes it to the text file. It returns the number of
characters being written on single execution of the write () method. Also, we need to add a newline
character (\n) at the end of every sentence to mark the end of line.
Example: Writing data in a text file on python shell using write() method.
>>> myobject=open("myfile.txt",'w')
>>> myobject.write("Hey I have started #using files in Python\n")
41
>>> myobject.close( )
On execution, write () returns the number of characters written on to the file. Hence, 41, which is the
length of the string passed as an argument, is displayed. Note: ‘\n’ is treated as a single character
If numeric data are to be written to a text file, the data need to be converted into string before writing to
the file.
Example:
>>>myobject=open ("myfile.txt",'w')
>>> marks = 58 #number 58 is converted to a string using #str()
>>> myobject.write(str(marks))
2
>>>myobject.close ()
The write () actually writes data onto a buffer. When the close() method is executed, the contents from
this buffer are moved to the file located on the permanent storage.
Example: Writing multiple values in a text file using program (Write Mode)
file = open('abc.txt','w') FIRST RUN SECOND RUN
Enter Name: Shan Enter Name: Sumit
for i in range(0,3):
Enter Name: Ajay Enter Name: Anil
name=input("Enter Name: ") Enter Name: Enter Name: Swati
OUTPUT
file.write(name) Pragya
Shan Sumit
file.write("\n") Ajay Anil
file.close() Pragya Swati
When we write the data using “w” mode then it overwrites the previous
data with new data if the file already exists. If we want to retain the
previous data in a data file then we should use append mode.
Example: Writing multiple values in a text file using program (Append Mode)
file = open('abc.txt','a')
FIRST RUN FILE CONTENTS Writing the data
for i in range(0,3): Enter Name: Shan Shan in append mode
name=input("Enter Name: ") Enter Name: Ajay Ajay adds the data at
Enter Name: Pragya Pragya the end of the
file.write(name) OUTPUT
SECOND RUN Sumit previous data as
file.write("\n") Enter Name: Sumit Anil
shown in the
Enter Name: Anil Swati
file.close() output.
Enter Name: Swati

The writelines() method


This method is used to write multiple strings to a file. We need to pass an iterable object like lists, tuple,
etc. containing strings to the writelines() method. Unlike write(), the writelines() method does not return
the number of characters written in the file. The following code explains the use of writelines().
Example: Writing data in a text file on python shell using writelines() method.
>>> myobject=open("myfile.txt",'w') Now this file needs to be opened in notepad to see the contents.
>>> lines = ["Hello everyone\n", "Writing
multiline strings\n", "This is the third line"]
>>> myobject.writelines(lines)
>>>myobject.close()
Reading from File
To read from an existing text file python provide many functions like:
a. Filehandle.read([n]): reads and return n bytes, if n is not specified it reads entire file.
b. Filehandle.readline([n]): reads a line of input. If n is specified reads at most n bytes. Read bytes in
the form of string ending with line character or blank string if no more bytes are left for reading.
c. Filehandle.readlines(): reads all lines and returns them in a list
NOTE: The read() and readline() reads data from file and return it in the form of string and readlines()
returns data in the form of list.
read() Method It is used to read the entire file / specified number of characters(bytes) and returns
the contents in the form of a string.
Syntax: String Variable = File Object.read (no. of characters)
Example 1:
file = open('abc.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
f=open('abc.txt') OUTPUT
str1=f.read()
print(str1)
f.close()
Example 2:
# Writing into text file
f = open("a.txt", 'w')
line1 = 'We are studying in class 12. This is the time when we should concentrate on studies. Examinations will be
taken in two terms and first term is approaching.'
f.write(line1)
line2="\nInformatics Practices is an interesting and scoring subject"
f.write(line2)
line3="\nIt has PYTHON and MYSQL as major part of syllabus"
f.write(line3) OUTPUT
f.close()
# Reading text file
f = open("a.txt", 'r')
text = f.read(10)
print("FIRST READ STATEMENT:",text)
text = f.read(5)
print("SECOND READ STATEMENT:",text)
text = f.read()
print("THIRD READ STATEMENT:",text)
f.close()
Example 3: OUTPUT
f = open("a.txt", 'r')
text = f.read()
print("FIRST READ STATEMENT:",text)
text = f.read(10)
print("SECOND READ STATEMENT:",text)
text = f.read(5)
print("THIRD READ STATEMENT:",text)
f.close()
Example : Read file through for loop
F = open("file2.txt","r");
for i in fileptr:
print(i) # i contains each line of the file
readline([size]) method: This method reads one complete line from a file where each line
terminates with a newline (\n) character. It can also be used to read a specified number (n) of bytes of
data from a file but maximum up to the newline character (\n).
Example 4:
# Reading text file OUTPUT
f = open("a.txt", 'r')
text = f.readline()
print(text)
text = f.readline()
print(text)
text = f.readline()
print(text)
f.close()
Example:
# Reading text file OUTPUT
f = open("a.txt", 'r')
line1=f.readline()
line2=f.readline()
line3=f.readline(10)
print(line1)
print(line2)
The difference in both outputs is that in the second example, readline() has been used
print(line3)
to read only 10 characters of the line.
f.close()
The readlines() method
The method reads all the lines and returns the lines along with newline as a list of strings.
Example:
OUTPUT
f = open("a.txt", 'r')
text=f.readlines()
print(text)
f.close()

In case we want to display each word of a line separately as an element of a list, then we can use split()
function.
Example: Accessing Every Word of every line in a File
f=open("a.txt",'r') OUTPUT
d=f.readlines()
for line in d:
words=line.split()
print(words)
f.close()
Example: Accessing Every Word in a File
f = open("a.txt", 'r')
txt=f.read()
word=txt.split( )
print(word)
f.close()
QUESTIONS BASED ON TEXT FILES
Q1: Write a python program to create and read the city.txt file in one go and print the contents on the
output screen. Also print the length of the file in bytes.
Solution:
f=open("city.txt","w")
f.write("My city is very clean city.")
f.close()
f=open("city.txt","r")
dt = f.read()
print(dt)
print(“Length of file in bytes is”,len(dt))
f.close()
Q2: Write a program to count the number of uppercase alphabets present in a text file "abc.txt".
Solution:
count = 0
file = open("abc.txt","r")
txt = file.read()
for i in txt :
if i.isupper() :
count += 1
print("Number of upper case alphabet : ", count)
file.close()

PRACTICE PROGRAMS
Q3: Write a program to count the number of lower-case alphabets present in a text file "abc.txt".
Q4: Write a program to count the number of alphabets, digits and special characters present in a
text file "abc.txt".
Q5: Write a program to count the number of vowels present in a text file "abc.txt".

Q6: Write a function AMCount() in Python, which should read each character of a text file “abc.txt”,
should count and display the occurrence of alphabets ‘A’ and ‘M’ (including small cases ‘a’ and ‘m ‘too).
Solution:
def AMCount():
file = open("abc.txt", "r")
txt = file.read()
print(txt)
counta, countm=0,0
for i in txt:
if i=='A' or i=='a':
counta+=1
if i=='M' or i=='m':
countm+=1
print("A or a = ",counta)
print("M or m = ",countm)
file.close()
Q7: Write a user defined function countwords() in python to count how many words are present in a
text file named “abc.txt”.
Solution:
file = open("abc.txt", "r")
txt = file.read()
words=txt.split()
print("No of words in the file are:",len(words))
Q8. Write a program in python to count the number of words in a text file ‘abc.txt’ which is starting with
an alphabet ‘A’ or ‘a’.
Solution:
file = open("abc.txt", "r")
txt = file.readlines()
count=0
for i in txt:
words=i.split()
for j in words:
if j[0]=='A' or j[0]=='a':
count+=1
print("No of words starting with alphabet A or a = ",count)
Q9. Write a function in python to count the number of lines in a text file ‘abc.txt’ which is starting with
an alphabet ‘A’ or ‘a’.
Solution:
file = open("abc.txt", "r")
txt = file.readlines()
count=0
for i in txt:
if i[0]=='A' or i[0]=='a':
count+=1
print("No of lines starting with alphabet A or a = ",count)
file.close()

PRACTICE PROGRAMS
Q10. Write a program in python to count the number of words in a text file ‘abc.txt’ which is starting
with an alphabet ‘A’ and ending with alphabet ‘e’.
Q11. Write a user-defined function named count() that will read the contents of text file named
“Story.txt” and count the number of lines which starts with either “I‟ or “M‟.
Q12. Write a program in python to read a text file. Reverse and print each word of the text file.
Q13. Write a function in Python that counts the number of “ME” or “MY” (in smaller case also) words
present in a text file “abc.txt”. If the “abc.txt” contents are as follows:
ME and my friends are going with MY uncle.
He told me to go with MY uncle.
The output should be “Frequency of me and my is: 4”
Solution:
Def countmeandmy( ):
f=open("abc.txt")
txt=f.read()
words=txt.split()
count=0
for i in words:
if i=='Me' or i=='ME' or i=='MY' or i=='my':
count+=1
print("Frequency of me and my is:",count)
Write a program to count the words "to" and "the" present in a text file "Poem.txt".
Q14: Consider following lines for the file friends.txt and predict the output:
Friends are crazy, Friends are naughty!
Friends are honest, Friends are best!
Friends are like keygen, friends are like license key!
We are nothing without friends, Life is not possible without friends!
Solution:
f = open("friends.txt")
l = f.readline() Output:
l2 = f.readline(18) Friends are honest
ch3=f.read(10) , Friends
print(l2) are best!
print(ch3)
print(f.readline())
f.close()
Q15. Write a function count_lines() to count and display the total number of lines from the file. Consider
above file – friends.txt.
Solution:
def count_lines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
print("no. of lines:",cnt)
f.close()
Q16: Write a method/function DISPLAYWORDS() in python to read lines from a text file ABC.TXT, and
display those words, which are less than 4 characters.
Solution:
def DISPLAYWORDS() :
file = open("abc.txt", "r")
lst = file.readlines()
for i in lst :
word = i.split()
for j in word :
if len( j ) < 4 :
print( j )
file.close()
Q17: Write a function display_oddLines() to display odd number lines from the text file. Consider above
file – friends.txt.
Solution:
def display_oddLines():
f = open("friends.txt")
cnt =0
for lines in f:
cnt+=1
if cnt%2!=0:
print(lines)
f.close()
Q18: Write a program that appends the contents of one file to another. Have the program take the
filenames from the user.
Solution:
file1 = input("Enter the name of file which you want to append : ")
file2 = input("Enter the name of original file : ")
old = open( file2 , "r" )
new = open( file1 , "a" )
data = old.read()
new.write( "\n" + data)
old.close()
new.close()
Q19: Write a program that read a text file “abc.txt” Now create 3 other text file as per the given criteria.
All lower case characters get stored inside the file LOWER, all upper case characters get stored inside
the file UPPER and all other characters get stored inside file OTHERS.
Solution:
f=open("abc.txt")
upper = open("UPPER.txt", "w")
lower = open("LOWER.txt" , "w" )
other = open ("OTHER.txt" , "w")
data=f.read()
for i in data:
if i.isupper():
upper.write(i)
elif i.islower():
lower.write(i)
else:
other.write(i)
f.close()
upper.close()
lower.close()
other.close()

PRACTICE PROGRAMS
Q20. Write a program in python to copy all the vowels of a text file “abc.txt” in another text file
“xyz.txt”
Q21. Write a program in python to copy all those lines of a text file “abc.txt” in another text file
“xyz.txt” which are starting with letter ‘A’,
Q22. Write a program in write the all lines of a text file “abc.txt” in another text file “xyz.txt” by
reversing..

The flush () function: When we write any data to file, python hold everything in buffer (temporary
memory) and pushes it onto actual file later. If you want to force Python to write the content of buffer
onto storage, you can use flush() function. Python automatically flushes the files when closing them i.e. it
will be implicitly called by the close (), BUT if you want to flush before closing any file you can use flush ()
File Pointer
Every file maintains a file pointer which tells the current position in the file where reading and writing
operation will take. When we perform any read/write operation two things happens:
 The operation at the current position of file pointer.
 File pointer advances by the specified number of bytes.

The tell() method


This function returns an integer that specifies the current position of the file object in the file. The position
so specified is the byte position from the beginning of the file till the current position of the file object.
Syntax: file_object.tell()

The seek() method:


This method is used to position the file object at a particular position in a file.
Syntax: file_object.seek(offset [, reference_point])
In the above syntax, offset is the number of bytes by which the file object is to be moved. reference_point
indicates the starting position of the file object. That is, with reference to which position, the offset has to
be counted. It can have any of the following values:
0 - beginning of the file 1 - current position of the file 2 - end of file
By default, the value of reference_point is 0, i.e. the offset is counted from the beginning of the file. For
example, the statement fileObject.seek(5,0) will position the file object at 5th byte position from the
beginning of the file.
Example: Using seek() and tell()
f = open("a.txt", 'w')
line = 'Welcome to World of Python\nBe an Artificial Intelligence Programmer'
f.write(line) OUTPUT
f.close()
f = open("a.txt", 'rb+')
print("Current Position while opening the file", f.tell())
f.read()
print("All contents read, file pointer reaches at end",f.tell())
f.seek(7)
print("Placing the file pointer at 7th byte from beginning",f.tell())
f.seek(15)
print("Placing the file pointer at 15th byte from beginning",f.tell())
print(f.seek(5,1))
print("Placing the file pointer 5 bytes ahead of current position",f.tell())
f.seek(-5,2)
print("Placing the file pointer 5 bytes prior to end",f.tell())
f.close()
Binary file Operations
If we want to write a structure such as list or dictionary to a file and read it subsequently we need to use
the Python module pickle.
The Pickle Module:
We know that Python considers everything as an object. So, all data types including list, tuple, dictionary,
etc. are also considered as objects. Python pickle module is used for serializing / Pickling and de-serializing
/ Unpickling a Python object structure. Any object in Python can be pickled so that it can be saved on disk.
What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a
python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all
the information necessary to reconstruct the object in another python script.
The pickle module deals with binary files. Here, data are not written but dumped and similarly, data are
not read but loaded. The Pickle Module must be imported to load and dump data. The pickle module
provides two methods - dump() and load() to work with binary files for pickling and unpickling,
respectively. For performing binary file operations, first we need to import the pickle module.
This module provides 2 main functions:
The dump() method
This method is used to convert (pickling) Python objects for writing data in a binary file. The file in which
data are to be dumped, needs to be opened in binary write mode (wb).
Syntax: pickle.dump(data_object, file_object)
Where data_object is the object that has to be dumped to the file with the file handle named file_object.
The load() Method
Dumped data can be read from file using load() i.e. it is used to read object from pickle file.
Syntax: data_object = pickle.load(file_Object)
Where data_object is the object which that has to be dumped to the file with the file handle named
file_object.
Pickle examples:

Pickle a simple list:


import pickle
mylist = ['a', 'b', 'c', 'd']
with open('datafile.txt', 'wb') as fh:
pickle.dump(mylist, fh)
Explanation: In the above code, list – “mylist” contains four elements (‘a’, ‘b’, ‘c’, ‘d’). We open the file in
“wb” mode instead of “w” as all the operations are done using bytes in the current working directory. A
new file named “datafile.txt” is created, which converts the mylist data in the byte stream.
Unpickle a simple list
import pickle
pickle_off = open ("datafile.txt", "rb")
emp = pickle.load(pickle_off)
print(emp)
Output: On running above scripts, you can see your mylist data again as output.
['a', 'b', 'c', 'd']
Pickle a simple dictionary
import pickle
EmpID = {1:"Zack",2:"53050",3:"IT",4:"38",5:"Flipkart"}
pickling_on = open("EmpID.pickle","wb")
pickle.dump(EmpID, pickling_on)
pickling_on.close()
Unpickle a dictionary
import pickle
pickle_off = open("EmpID.pickle", 'rb')
EmpID = pickle.load(pickle_off)
print(EmpID)
Explanation: On running above script (unpickle) we get our dictionary back as we initialized earlier. Also,
please note because we are reading bytes here, we have used “rb” instead of “r”.
Output: {1: 'Zack', 2: '53050', 3: 'IT', 4: '38', 5: 'Flipkart'}

Exception handling in python


Python Exception
An exception can be defined as an unusual condition in a program resulting in the interruption in the flow
of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is not
executed. Therefore, an exception is the run-time error that is unable to handle to Python script. An
exception is a Python object that represents an error

Python provides a way to handle the exception so that the code can be executed without any interruption.
If we do not handle the exception, the interpreter doesn't execute all the code that exists after the
exception. Python has many built-in exceptions that enable our program to run without interruption and
give the output. These exceptions are given below:

Common Exceptions
Python provides the number of built-in exceptions, A list of common exceptions that can be thrown from
a standard 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. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being performed.
The try-expect statement
If the Python program contains suspicious code that may throw the exception, we must place that code in
the try block. The try block must be followed with the except statement, which contains a block of code
that will be executed if there is some exception in the try block.

QUESTIONS BASED ON BINARY FILES


Q1.a) Write a program to write the following List in a binary file. L = [1, "Amit", 25000]
b) Read the binary file created and print its contents.
Solution:
import pickle
f = open("data.dat", 'wb')
L = [1, "Amit", 25000]
pickle.dump(L,f)
f.close()

f = open("data.dat", 'rb')
L1=pickle.load(f)
print(L1)
f.close()
Q2.a) Write a program to write the following dictionary in a binary file.
d = {1 : "Amit", 2 : "Sumit", 3 : "Naina"}
b) Read the binary file created and print its contents.
Solution:
import pickle
f = open("data.dat", 'wb')
d = {1 : "Amit", 2 : "Sumit", 3 : "Naina"}
pickle.dump(d,f)
f.close()
f = open("data.dat", 'rb')
d=pickle.load(f)
print(d)
f.close()
Q3.a) Write a program to write the following List of records in a binary file.
L =[ [1, "Amit", 25000],[2, “Sunaina”, 34000], [3, “Raghav”, 21000]]
b) Read the binary file created and print its contents.
Solution:
import pickle
f = open("data.dat", 'wb')
L =[ [1, "Amit", 25000],[2, "Sunaina", 34000], [3, "Raghav", 21000]]
pickle.dump(L,f)
f.close()
f = open("data.dat", 'rb')
L=pickle.load(f)
print(L)
f.close()
Q4.a) Write a function addrecord() to add record of teacher in file “teacher.dat” Each record should
contain the following data (using list) : Teacher Name, Teacher designation and Teacher Salary
b) Write a function displayrec() to read and display the record of a particular teacher according to the
name entered by the user from a file “teacher.dat” (created above)
Solution:
import pickle
def addrecord():
f=open("aa.dat",'wb')
data=[ ]
while True:
name=input("Enter Name:")
desig=input("Enter Designation:")
sal=int(input("Enter Salary:"))
rec=[name,desig,sal]
data.append(rec)
choice=input("Do you want to add more records(Y/N)?")
if not(choice=='Y' or choice=='y') :
print("Thanks... Program ended")
break
pickle.dump(data,f)
f.close()
def displayrec():
f=open("aa.dat",'rb')
data=pickle.load(f)
for i in data:
print(i)
f.close()
Q5. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
a) Write a user defined function CreateFile() to input data for a record and add to Book.dat .
b) Write a function CountRec(Author) in Python which accepts the Author name as parameter and
count and return number of books by the given Author are stored in the binary file “Book.dat
Solution:
import pickle
def createfile():
fobj=open("Book.dat","ab")
BookNo=int(input("Enter Book Number : "))
Book_name=input("Enter book Name :")
Author = input("Enter Author name: ")
Price = int(input("Price of book : "))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
fobj.close()
def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
fobj.close()
return num
Q6. A binary file “STUDENT.DAT” has structure [admission_number, Name, Percentage]. Write a
function countrec() in Python that would read contents of a file “STUDENT.DAT” and displays the details
of those students whose percentage is above 75. Also display number of students scoring above 75%.
Solution:
import pickle
def countrec():
fobj=open("student.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]>75:
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
Q7. Write a function in python to search and display details, whose destination is “Cochin” from binary
file “Bus.Dat”. Assuming the binary file is containing the following elements in the list: Bus Number, Bus
Starting Point and Bus Destination.
Solution:
import pickle
def countrec():
fobj=open("bus.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2]=="Cochin" or rec[2]=="cochin":
num = num + 1
print(rec[0],rec[1],rec[2])
except:
fobj.close()
return num
Update record in Binary file
Q8.a) Write a function writedata() to add record of employees in file “data.dat” Each record should
contain the following data (using list) : Employee Number, Name, and Salary.
b) Write a function readdata() to read and display the records from the file “data.dat” (created above).
c) Write a function updatedata() to ask the user to input an employee number, search the employee
number in the file “data.dat” and if found, ask the user to input the new value of salary and modify it
import pickle
def writedata(): #WRITING DATA IN DATA FILE
f=open("data.dat", 'wb')
L =[ [1, "Amit", 25000],[2, "Sunaina", 34000], [3, "Raghav", 21000]]
pickle.dump(L,f)
f.close()

def readdata():
f = open("data.dat", 'rb')
L1=pickle.load(f)
print(L1)
f.close()

def updatedata():
file = open("data.dat", "rb+")
list = pickle.load(file)
found = 0
lst = []
r=int(input("Enter Employee no. to search:"))
for x in list:
if r==x[0]:
found = 1
x[2]= int(input('Enter new Salary'))
lst.append(x)
if(found == 1):
file.seek(0)
pickle.dump(lst, file)
print("Record Updated")
else:
print('Employee Number does not exist')
file.close()

writedata()
print(“Printing the data from the file”)
readdata()
updatadata()
print(“Printing the modified data”)
readdata()

PRACTICE QUESTIONS
Q8. Write a function addrec() in Python to add more new records at the bottom of a binary file
“STUDENT.dat”, assuming the binary file is containing the following structure: [Roll No, Student Name]
Q9. Write a function searchprod( pc) in python to display the record of a particular product from a file
product.dat whose code is passed as an argument. Structure of product contains the following elements
[product code, product price]
Q10. Write a function routechange(route number) which takes the Route number as parameter and
modify the route name(Accept it from the user) of passed route number in a binary file “route.dat”.
Q11. Write a function countrec(sport name) in Python which accepts the name of sport as parameter and
count and display the coach name of a sport which is passed as argument from the binary file “sport.dat”.
Structure of record in a file is given below ——————– – [sport name, coach name]
Q12. A binary file “salary.DAT” has structure [employee id, employee name, salary]. Write a function
countrec() in Python that would read contents of the file “salary.DAT” and display the details of those
employee whose salary is above 20000.
Q13. Amit is a monitor of class XII-A and he stored the record of all the students of his class in a file named
“class.dat”. Structure of record is [roll number, name, percentage]. His computer teacher has assigned the
following duty to Amit.
Write a function remcount( ) to count the number of students who need remedial class (student who
scored less than 40 percent)

SUMMARY
 A file is a named location on a secondary storage media where data are permanently stored
for later access.
 A text file contains only textual information consisting of alphabets, numbers and other
special symbols. Such files are stored with extensions like .txt, .py, .c, .csv, .html, etc. Each
byte of a text file represents a character.
 Each line of a text file is stored as a sequence of ASCII equivalent of the characters and is
terminated by a special character, called the End of Line (EOL).
 Binary file consists of data stored as a stream of bytes.
 open() method is used to open a file in Python and it returns a file object called file handle.
The file handle is used to transfer data to and from the file by calling the functions defined
in the Python’s io module.
 close() method is used to close the file. While closing a file, the system frees up all the
resources like processor and memory allocated to it.
 write() method takes a string as an argument and writes it to the text file.
 writelines() method is used to write multiple strings to a file. We need to pass an iterable
object like lists, tuple etc. containing strings to writelines() method.
 read([n]) method is used to read a specified number of bytes (n) of data from a data file.
 readline([n]) method reads one complete line from a file where lines are ending with a
newline (\n). It can also be used to read a specified number (n) of bytes of data from a file
but maximum up to the newline character (\n).
 readlines() method reads all the lines and returns the lines along with newline character, as
a list of strings.
 tell() method returns an integer that specifies the current position of the file object. The
position so specified is the byte position from the beginning of the file till the current
position of the file object.
 seek()method is used to position the file object at a particular position in a file.
COMMA SEPARATED VALUE (CSV)
CSV FILE
CSV is a simple file format used to store tabular data, such as a spreadsheet or database. Files in the CSV
format can be imported to and exported from programs that store data in tables, such as Microsoft Excel
or OpenOffice Calc. CSV stands for "comma-separated. A comma-separated values file is a delimited text
file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one
or more fields, separated by commas. The use of the comma as a field separator is the source of the name
for this file format. For example the general format of CSV file is as given below:
column1 name, column2 name, column 3 name
first row data1, first row data2, first row data3
second row data1, second row data2, second row data3 and so on and on …………….....
Notice how each piece of data is separated by a comma. Normally, the first line identifies each piece of
data—in other words, the name of a data column. Every subsequent line after that is actual data and is
limited only by file size constraints.
In general, the separator character is called a delimiter, and the comma is not the only one used. Other
popular delimiters include the tab (\t), colon (:) and semi-colon (;) characters. Properly parsing a CSV file
requires us to know which delimiter is being used.
Writing/ Reading CSV files in Python
Python provides an in-built module called CSV to work with CSV files. There are various classes provided
by this module for writing and reading data with CSV files:
 Using csv.writer class
 Using csv.DictWriter class
csv.writer class provides two methods for writing to CSV. They are writerow() and writerows().
The writerow() Method:
This method writes a single row at a time. Field row can be written using this method.
Syntax: writerow(fields)
The writerows() Method:
This method is used to write multiple rows at a time. This can be used to write rows list.
Syntax: writerows(rows)
The csv.reader() Method:
At first, the CSV file is opened using the open() method in ‘r’ mode(specifies read mode while opening a
file) which returns the file object then it is read by using the reader() method of CSV module that returns
the reader object that iterates throughout the lines in the specified CSV document.
Note: The ‘with’ keyword is used along with the open() method as it simplifies exception handling and
automatically closes the CSV file.
Example: Python program to depict the read / write operation in CSV file
import csv
# field names
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2', '9.1'], ['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'], ['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']]
# writing to csv file
with open(“college.csv”, 'w', newline=‘ ’) as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)
# writing the fields
csvwriter.writerow(fields)
# writing the data rows
csvwriter.writerows(rows)
# opening the CSV file for reading
with open('college.csv', mode ='r')as file:
# reading the CSV file
csvFile = csv.reader(file)
# displaying the contents of the CSV file
for lines in csvFile:
print(lines)
NOTE: The csv.writer writes \r\n into the file directly. Hence while opening CSV file in Writing mode, give
another argument newline= ‘ ‘ .
INTERFACE PYTHON WITH MYSQL
Introduction
Every application required data to be stored for future reference to manipulate data. Today every
application stores data in database for this purpose.
For example, reservation system stores passenger’s details for reserving the seats and later on for sending
some messages or for printing tickets etc. In schools, student details are saved for many reasons like
attendance, fee collections, exams, report card etc. Python allows us to connect all types of database like
Oracle, SQL Server, MySQL.
Pre-requisite to connect Python with MySQL
 First step is to install connecter module for which we should write the following command at
command prompt (Administrator login): pip install mysql-connector-python
 Before we connect python program with any database like MySQL we need to build a bridge to
connect Python and MySQL.
 To build this bridge so that data can travel both ways we need a connector called mysql.connector
 We can install mysql.connector by using following method:
At command prompt (Administrator login) Type install mysql.connector and press enter
This connector will work only for MySQL 5.7.3 or later
 Once the connector is installed you are ready to connect your python program to MySQL.
Steps to follow while connecting your python program with MySQL
 Open python
 Import the package required (import mysql.connector) Open the connection to database
 Create a cursor instance
 Execute the query and store it in resultset Extract data from resultset
Importing mysql.connector
import mysql.connector OR import mysql.connector as ms
Open a connection to MySQL Database
To create connection, connect() function is used Its syntax is:
connect(host=<server_name>,user=<user_name>, passwd=<password>[,database=<database>])
Here server_name means database servername, generally localhost User_name means user by which we
connect with mysql.
Database is the name of database whose data(table) we want to use
Creating Cursor and Executing Query
It is a useful control structure of database connectivity.
When we fire a query to database, it is executed and resultset (set of records) is sent over the connection
in one go. We may want to access data one row at a time, but query processing cannot happens as one
row at a time, so cursor help us in performing this task. Cursor stores all the data as a temporary container
of returned data and we can fetch data one row at a time from Cursor.
TO CREATE CURSOR
Cursor_name = connectionObject.cursor() For e.g.
mycursor = mycon.cursor()
TO EXECUTE QUERY
We use execute () function to send query to connection Cursor_name.execute(query)
Example: mycursor.execute(Select * from EMP)
Fetching(extracting) data from ResultSet
To extract data from cursor following functions are used:
The fetchall() Method: it will return all the record in the form of tuple.
The fetchone() Method: it returns one record from the result set. i.e. first time it will return first
record, next time it will return second record and so on. If no more record it will return None
The fetchmany(n) Method: it will return n number of records. It no more record it will return an
empty tuple.
The rowcount() Method: it will return number of rows retrieved from the cursor so far.
The commit ( ) Method: This method sends a COMMIT statement to the MySQL server, committing
the current transaction. Since by default Connector/Python does not autocommit or save changes jence it
is important to call this method after every transaction that modifies data for tables using command like
insert, update and delete. It is required to make the changes, otherwise no changes are made to the table.

Example of Database connectivity / commands with python


# import the library
import mysql.connector as ms
# create connection object between mysql and python
con=ms.connect(host='localhost', user='root', passwd='nhgws')
# creating cursor object
mycursor = con.cursor()
#Executing query for creating database
mycursor.execute("CREATE DATABASE ex8")
#Executing query for opening database
mycursor.execute("use ex8")
#Executing query for creating table
mycursor.execute("CREATE TABLE stu (rno int, name VARCHAR(20), mks int)")
#Executing queries for inserting records
mycursor.execute("insert into stu values(1, 'Shreyansh', 88)")
mycursor.execute("insert into stu values(2, 'Kunal', 87)")
mycursor.execute("insert into stu values(3, 'Sachin', 92)")
mycursor.execute("insert into stu values(4, 'Sanya', 99)")
#Using commit function to make permanent changes in table data
con.commit()
# Executing queries for displaying data
mycursor.execute("select * from stu")
# Accessing all records
data=mycursor.fetchall()
# printing the data imported from MYSQL
for i in data:
print(i)
# Executing queries for updating data
mycursor.execute("update stu set mks=77 where rno=3")
#Using commit function to make permanent changes in table data
con.commit()
# Executing queries for displaying data
mycursor.execute("select * from stu")
data=mycursor.fetchall()
for i in data:
print(i)
COMPUTER NETWORKS
Introduction to computer networks
We are living in a connected world. Information is being produced, exchanged, and traced across the globe in real time.
It's possible as almost everyone and everything in the digital world is interconnected through one way or the other.

A group of two or more similar things or people interconnected with each other is called network. Some of the examples
of network in our everyday life includes Social network, Mobile network, Network of computers, Airlines, railway, banks,
hospital’s networks etc.
A computer network is an interconnection among two or more computers or computing devices. Such interconnection
allows computers to share data and resources among each other. A basic network may connect a few computers placed
in a room.
The network size may vary from small to large depending on the number of computers it connects. A computer network
can include different types of hosts (also called nodes) like server, desktop, laptop, cellular phones.

Apart from computers, networks include networking devices like switch, router, modem, etc. Networking devices are
used to connect multiple computers in different settings. For communication, data in a network is divided into smaller
chunks called packets. These packets are then carried over a network. Devices in a network can be connected either
through wired media like cables or wireless media like air.
In a communication network, each device that is a part of a network and that can receive, create, store or send data to
different network routes is called a node. In the context of data communication, a node can be a device such as a
modem, hub, bridge, switch, router, digital telephone handset, a printer, a computer or a server.
Interconnectivity of computing devices in a network allows us to exchange information simultaneously with many
parties through email, websites, audio/video calls, etc. Network allows sharing of resources. For example, a printer can
be made available to multiple computers through a network; a networked storage can be accessed by multiple
computers. People often connect their devices through hotspot, thus forming a small personal network.
Evolution of Networking
In the 1960s a research project was commissioned by Advanced Research Projects Agency Network (ARPANET) in the
U.S. Department of Defense to connect the academic and research institutions located at different places for scientific
collaborations. The first message was communicated between the University of California, Los Angeles (UCLA) and
Stanford Research Institute (SRI). Slowly but gradually, more and more organizations joined the ARPANET, and many
independent smaller networks were formed. Few of the milestones in the magnificent journey of evolution of computer
networks is depicted in the timeline shown in Figure.

Benefits of Network
RESOURCE SHARING
COMMUNICATION
COST EFFECTIVE
SECURITY
RELIABILTY
CENTRAL STORAGE

NETWORK TERMINOLOGIES
Nodes (Workstations): The term nodes refers to computers that are attached to a network and are seeking to share
resources.
Server: A computer that facilities the sharing of data, software and hardware resources on the network.
Network Interface Unit (NIU): A Network interface unit is an interpreter that helps in establishing communication
between the server and the client. It is also known as NIC (Network Interface Card) or LAN Card.
Domain Name: It is a way to identify and locate the computers connected to the internet. It must be unique.
URL (Uniform Resource Locator): A URL is the Web address of a specific resource on the Internet. For example,
the URL of the TechTerms website is "http://techterms.com."
For ex - http://techterms.com/definition/url. It has following information-
http:// – the URL prefix, which specifies the protocol used to access the location
techterms.com – the server name or IP address of the server
/definition/url – the path to the directory or file
Structure of a Network
Sender: A device or computer that send information/data.
Receiver: A device or computer who receives data/information.
Message: An information needs to broadcast.
Transmission Medium: It is a physical path with the help of which information goes from sender to receiver.
Communication: Each node in a network should be uniquely identified so that a network device can identify the
sender and receiver and decide a routing path to transmit data. Let us explore further and know how each node is
distinguished in a network.
MAC Address: MAC stands for Media Access Control. The MAC address, also known as the physical or hardware
address, is a unique value associated with a network adapter called a NIC. The MAC address is engraved on NIC at the
time of manufacturing and thus it is a permanent address and cannot be changed under any circumstances. The machine
on which the NIC is attached, can be physically identified on the network using its MAC address.
Each MAC address is a 12-digit hexadecimal numbers (48 bits in length), of which the first six digits (24 bits) contain the
manufacturer’s ID called Organizational Unique Identifier (OUI) and the later six digits (24 bits) represents the serial
number assigned to the card by the manufacturer. A sample MAC address looks like:

Types of Networks
There are various types of computer networks ranging from network of handheld devices (like mobile phones or tablets)
connected through Wi-Fi or Bluetooth within a single room to the millions of computers spread across the globe. Some
are connected wireless while others are connected through wires.
Based on the geographical area covered and data transfer rate, computer networks are broadly categorized as:
PAN (Personal Area Network) LAN (Local Area Network)
MAN (Metropolitan Area Network) WAN (Wide Area Network)
Personal Area Network (PAN)
It is a network formed by connecting a few personal devices like computers, laptops, mobile phones, smart phones,
printers etc., as shown in Figure. All these devices lie within an approximate range of 10 metres. A personal area network
may be wired or wireless. For example, a mobile phone connected to the laptop through USB forms a wired PAN while
two smartphones communicating with each other through Bluetooth technology form a wireless PAN or WPAN.

Local Area Network (LAN)


It is a network that connects computers, mobile phones, tablet, mouse, printer, etc., placed at a limited distance. The
geographical area covered by a LAN can range from a single room, a floor, an office having one or more buildings in the
same premise, laboratory, a school, college, or university campus. The connectivity is done by means of wires, Ethernet
cables, fibre optics, or Wi-Fi.

LAN is comparatively secure as only authentic users in the network can access other computers or shared resources.
Users can print documents using a connected printer, upload/download documents and software to and from the local
server. Such LANs provide the short range communication with the high speed data transfer rates. These types of
networks can be extended up to 1 km. Data transfer in LAN is quite high, and usually varies from 10 Mbps (called
Ethernet) to 1000 Mbps (called Gigabit Ethernet), where Mbps stands for Megabits per second. Ethernet is a set of rules
that decides how computers and other devices connect with each other through cables in a local area network or LAN.
Metropolitan Area Network (MAN)
Metropolitan Area Network (MAN) is an extended form of LAN which covers a larger geographical area like a city or a
town. Data transfer rate in MAN also ranges in Mbps, but it is considerably less as compared to LAN. Cable TV network
or cable based broadband internet services are examples of MAN. This kind of network can be extended up to 30-40
km. Sometimes, many LANs are connected together to form MAN, as shown in Figure 10.6.

Wide Area Network (WAN)


Wide Area Network connects computers and other LANs and MANs, which are spread across different geographical
locations of a country or in different countries or continents. A WAN could be formed by connecting a LAN to other
LANs via wired/wireless media. Large business, educational and government organizations connect their different
branches in different locations across the world through WAN. The Internet is the largest WAN that connects billions of
computers, smartphones and millions of LANs from different continents.
Network devices
To communicate data through different transmission media and to configure networks with different functionality, we
require different devices like Modem, Hub, Switch, Repeater, Router, Gateway, etc. Let us explore them in detail.
Modem
Modem stands for ‘Modulator DEModulator’. It refers to a device used for conversion between analog signals and digital
bits. We know computers store and process data in terms of 0s and 1s. However, to transmit data from a sender to a
receiver, or while browsing the internet, digital data are converted to an analog signal and the medium (be it free-space
or a physical media) carries the signal to the receiver. There are modems connected to both the source and destination
nodes. The modem at the sender’s end acts as a modulator that converts the digital data into analog signals. The modem
at the receiver’s end acts as a demodulator that converts the analog signals into digital data for the destination node to
understand.

Ethernet Card
Ethernet card, also known as Network Interface Card (NIC card in short)
is a network adapter used to set up a wired network. It acts as an
interface between computer and the network. It is a circuit board
mounted on the motherboard of a computer. The Ethernet cable
connects the computer to the network through NIC. Ethernet cards can
support data transfer between 10 Mbps and 1 Gbps (1000 Mbps). Each
NIC has a MAC address, which helps in uniquely identifying the
computer on the network.

RJ45
RJ 45 or Registered Jack-45 is an eight-pin connector that is used
exclusively with Ethernet cables for networking. It is a standard
networking interface that can be seen at the end of all network cables.
Basically, it is a small plastic plug that fits into RJ-45 jacks of the
Ethernet cards present in various computing devices.
Repeater
Data are carried in the form of signals over the cable. These signals can
travel a specified distance (usually about 100 m). Signals lose their
strength beyond this limit and become weak. In such conditions,
original signals need to be regenerated.
A repeater is an analog device that works with signals on the cables to
which it is connected. The weakened signal appearing on the cable is
regenerated and put back on the cable by a repeater.
Hub
An Ethernet hub is a network device used to connect
different devices through wires. Data arriving on any of
the lines are sent out on all the others. The limitation of
Hub is that if data from two devices come at the same
time, they will collide.
A network hub with 8 ports
Switch
A switch is a networking device that plays a central role in
a Local Area Network (LAN). Like a hub, a network switch
is used to connect multiple computers or communicating
devices. When data arrives, the switch extracts the
destination address from the data packet and looks it up
in a table to see where to send the packet. Thus, it sends
signals to only selected devices instead of sending to all. It
can forward multiple packets at the same time. A switch
does not forward the signals which are noisy or corrupted.
It drops such signals and asks the sender to resend it.
Ethernet switches are common in homes/offices to
connect multiple devices thus creating LANs or to access
the Internet.
Router
A router is a network device that can receive the data, analyze it and
transmit it to other networks. A router connects a local area network
to the internet. Compared to a hub or a switch, a router has advanced
capabilities as it can analyze the data being carried over a network,
decide/alter how it is packaged, and send it to another network of a
different type. For example, data has been divided into packets of a
certain size. Suppose these packets are to be carried over a different
type of network which cannot handle bigger packets. In such a case,
the data is to be repackaged as smaller packets and then sent over
the network by a router. A router can be wired or wireless. A wireless
router can provide Wi-Fi access to smartphones and other devices.
Usually, such routers also contain some ports to provide wired
Internet access. These days, home Wi-Fi routers perform the dual task
of a router and a modem/ switch. These routers connect to incoming
broadband lines, from ISP (Internet Service Provider), and convert
them to digital data for computing devices to process.
Gateway
As the term “Gateway” suggests, it is
a key access point that acts as a
“gate” between an organization’s
network and the outside world of the
Internet. Gateway serves as the entry
and exit point of a network, as all
data coming in or going out of a
network must first pass through the
gateway in order to use routing
paths. Besides routing data packets,
gateways also maintain information
about the host network's internal
connection paths and the identified
paths of other remote networks. If a
node from one network wants to
communicate with a node of a
foreign network, it will pass the data
packet to the gateway, which then
routes it to the destination using the
best possible route.
Wi-Fi Cards
A Wi-Fi card connects to your laptop either in your USB port or a
wider card slot. This card generally is geared to a particular Wi-
Fi network, so to use it you must be in range of a wireless
Internet signal dedicated to that network. In this way, the Wi-Fi
card acts as both a receiver and transmitter. It receives the
wireless signal and communicates with the wireless network,
enabling you to access the Web with your laptop.

Networking topologies
As we already know that a number of computing devices are connected together to form a Local Area Network (LAN),
and interconnections among millions of LANs forms the Internet. The geographic arrangement of computers and other
peripherals in a network is called its topology. Common network topologies are Mesh, Ring, Bus, Star and Tree.
Mesh Topology
In this networking topology, each communicating device is connected
with every other device in the network as shown in given Figure. Such
a network can handle large amounts of traffic since multiple nodes can
transmit data simultaneously. Also, such networks are more reliable in
the sense that even if a node gets down, it does not cause any break in
the transmission of data between other nodes. This topology is also
more secure as compared to other topologies because each cable
between two nodes carries different data. However, wiring is complex
and cabling cost is high in creating such networks and there are many
redundant or unutilized connections.
Ring Topology
In ring topology, each node is connected to two other
devices, one each on either side, as shown in Figure. The
nodes connected with each other thus forms a ring. The link
in a ring topology is unidirectional. Thus, data can be
transmitted in one direction only (clockwise or
counterclockwise).

Bus Topology
In bus topology, each communicating device connects to a
transmission medium, known as bus. Data sent from a node
are passed on to the bus and hence are transmitted to the
length of the bus in both directions. That means, data can
be received by any of the nodes connected to the bus. In
this topology, a single backbone wire called bus is shared
among the nodes, which makes it cheaper and easier to
maintain. Both ring and bus topologies are considered to be
less secure and less reliable.
Star Topology
In star topology, each communicating device is connected
to a central node, which is a networking device like a hub
or a switch, as shown in Figure.
Star topology is considered very effective, efficient and fast
as each device is directly connected with the central device.
Although disturbance in one device will not affect the rest
of the network, any failure in a central networking device
may lead to the failure of complete network.
The central node can be either a broadcasting device means
data will be transmitted to all the nodes in the network, or
a unicast device means the node can identify the
destination and forward data to that node only.
Tree or Hybrid Topology
It is a hierarchical topology, in which there are multiple
branches and each branch can have one or more basic
topologies like star, ring and bus. Such topologies are
usually realized in WANs where multiple LANs are
connected. Those LANs may be in the form of a ring, bus or
star. In given figure, a hybrid topology is shown connecting
4-star topologies in a bus.
In this type of network, data transmitted from source first
reaches the centralized device and from there the data
passes through every branch where each branch can have
links for more nodes.
IP Address: Every machine on a TCP/IP Network has a unique identifying number called an IP Address. The initial IP
Address is a 32 bit numeric address, written as four numbers separated by periods, where each number is the decimal
(base-10) representation for an 8-bit binary (base-2) number and each can take any value from 0 - 255. A sample IPV4
address looks like: 192:168:0:178

COMMUNICATION/TRANSMISSION MEDIA
In data communication terminology, a transmission medium is a physical path between the transmitter and the
receiver i.e. it is the channel through which data is sent from one place to another. These are of following types:

TWISTED PAIR (Ethernet) CABLE


 2 or 4 insulated wires are in twisted form in this cable. Twisting resists the effect of surrounding noise and
electromagnetic interference. RJ-45 (registered jack) connector is used to connect computers.
 Cat-5 and Cat-6 specifications are generally used in LAN whereas other lower categories are used in
telephone connections.
 It is further divided in to categories-unshielded and shielded twisted pair cable. Shielded twisted pair cable
remains covered with insulation to reduce signal interference.
ADVANTAGES: * Cheap, light weight and flexible cable.
* It is easy to install and maintain.
DISADVANTAGES: * It is effective up to 100 meters only after this, repeaters are required.
* It supports low bandwidth with the speed up to 100Mbps.

Shielded Twisted Unshielded Twisted


Pair Pair
COAXIAL CABLE (coax)
In a coax, there are two solid insulated conductors which shares one common axis. Inner conductor is a straight
wire surrounded by a wired mesh. Internal core carries signals and mesh works as a noise reflector. It is generally
used in cable TV transmission.
ADVANTAGES:
 It provides high bandwidth. It carries data up to the distance of 185-500 meters.
 It is suitable for broadband transmission (cable TV) and can also be useful in shared cable network.
 It is less sensitive towards electromagnetic fields.
DISADVANTAGES:
 As compared to twisted pair cable, it is less flexible and is expensive.
 Installation is not easy due to thickness of 1 cm diameter and poor flexibility.
OPTICAL FIBRE CABLE
 Its design is based on the concept of total internal reflection.
 It has glass tubes to carry signals in the form of light rays (photons). Signals are to be emitted by Light
Emitting Diode (LED) or laser beam from source. It has following parts-
 CORE (Glass/Plastic): it is a thin glass rode, light rays travels from one end to other.
 CLADDING: it is an optical material covering core that transforms the light and sends it back to the core.
 BUFFER COATING: it is a plastic coating which prevents the cable from damage and moisture.
ADVANTAGES:
 It is free from Electromagnetic Interference (EMI).
 It is secure and suitable for high speed transmission.
DISADVANTAGES:
 It is fragile and very expensive.
 Its installation is very tough and expensive.

WIRELESS MEDIA
•RADIO WAVES
•Radio waves uses radio frequencies in the
limit 3 GHz to 3 Ghz. Signals are modified on
high speed radio wave carrier frequency
using amplitude modulation (AM) and
frequency modulation (FM). These waves
uses ionosphere as shown in the diagram for
signal transmission. It can be transmitted on
long distance and supports mobility.
•Radio waves are used for communication
from small walkie-talkie distances to
sufficient distances within a city (AM/FM
radio broadcasting).
ADVANTAGES:
 Radio communication covers a big area and supports mobility.
 Radio waves can disperse in all directions and can cross the solid walls as well.
 These waves facilitates the communication in inaccessible areas.
 It is not needed to physically aligned transmitter and receiver antenna.
DISADVANTAGES:
 It is expensive and unsecured communication medium.
 It is very sensitive towards weather..
 Permission from concerned departments is required for radio waves transmission.
MICROWAVES
In microwave transmission, two direct parabolic antennas are needed to install on towers/ buildings/mountains
for sending and receiving signals. They are needed to align to each other.
ADVANTAGES:
 This facilitates transmission in tough areas.
 It supports data transmission at the speed of 16 Giga bits per second.
DISADVANTAGES:
 It is an unsecured communication.
 Signals are distributed and transmitted in all directions.
 It gets affected by weather conditions.
 Cost of placing tower and antenna is high.

INFRARED WAVES
Infrared waves allows transmission in devices up to small distances of 300 GHz to 400 THz (about 5 meters) using
wireless signals. Infrared transmission technique used in computer is similar to the technique used in remote
operated electronic equipment like TV, cordless phone toys etc.
ADVANTAGES DISADVANTAGES

It is a kind of line of sight transmission,


It is a kind of line of sight
therefore, at a time, only two devices
transmission.
can communicate with each other.
It does not require It cannot travels through solid
government License. materials.

It is basically for less


It gets affected by long distances.
distance transmission.
SATELLITE LINK
Satellite communication uses microwave (1.5GHz-20GHz) as a medium. Satellites like Geostationary or Polar
satellites are used to set transmission on various center on earth.
Services like DTH, VSAT, GPS Satellite phones, etc. have become possible by satellite transmission. A satellite
works as a Trans-Receiver Antenna in space which receive, regenerate and redirect signals.
ADVANTAGES DISADVANTAGES
It covers a large geographical These are slow than
area. microwave transmission.
It provides secure, uninterrupted Legal permissions are needed
and high quality transmission. for these.
Geographical conditions like
mountains, tall building, and
Installation is very complex.
towers does not raise
interruption.
Signals sent or received by earth Signals can be interrupted by
stations may be fixed or mobile. external interference.

Switching Techniques
Switching is the technique by which nodes control or switch data to transmit it between specific points on a
network. There are 3 common switching techniques: Circuit Switching. Packet Switching. Message Switching.
Circuit Switching
 Circuit switching is a switching technique that establishes a dedicated path between sender and receiver.
 In the Circuit Switching Technique, once the connection is established then the dedicated path will remain to
exist until the connection is terminated.
 Circuit switching in a network operates in a similar way as the telephone works.
 A complete end-to-end path must exist before the communication takes place.
 Circuit switching is used in public telephone network. It is used for voice transmission.
 Fixed data can be transferred at a time in circuit switching technology.
 In case of circuit switching technique, when any user wants to send the data, voice, video, a request signal is
sent to the receiver then the receiver sends back the acknowledgment to ensure the availability of the
dedicated path. After receiving the acknowledgment, dedicated path transfers the data.
Communication through circuit switching has 3 phases:
Packet Switching
 The packet switching is a switching technique in which the message is sent in one go, but it is divided into
smaller pieces, and they are sent individually.
 The message splits into smaller pieces known as packets and packets are given a unique number to identify
their order at the receiving end.
 Every packet contains some information in its headers such as source address, destination address and
sequence number.
 Packets will travel across the network, taking the shortest path as possible.
 All the packets are reassembled at the receiving end in correct order.
 If any packet is missing or corrupted, then the message will be sent to resend the message.
 If the correct order of the packets is reached, then the acknowledgment message will be sent.

Network protocols
Network protocols are a set of rules, conventions, and data structures that dictate how devices exchange data
across networks. In other words, network protocols can be equated to languages that two devices must understand
for seamless communication of information, regardless of their infrastructure and design disparities.

Hyper Text Transfer Protocol (HTTP): HTTP is designed for transferring a hypertext among two or more
systems. HTML tags are used for creating links. These links may be in any form like text or images. HTTP is designed
on Client-server principles which allow a client system for establishing a connection with the server machine for
making a request. The server acknowledges the request initiated by the client and responds accordingly.
Hyper Text Transfer Protocol Secure (HTTPS): HTTPS is abbreviated as Hyper Text Transfer Protocol Secure
is a standard protocol to secure the communication among two computers one using the browser and other
fetching data from web server. HTTP is used for transferring data between the client browser (request) and the
web server (response) in the hypertext format, same in case of HTTPS except that the transferring of data is done
in an encrypted format. So it can be said that https thwart hackers from interpretation or modification of data
throughout the transfer of packets.
File Transfer Protocol (FTP): FTP allows users to transfer files from one machine to another. Types of files may
include program files, multimedia files, text files, and documents, etc.
Point - to - Point Protocol (PPP): It is a communication protocol of the data link layer that is used to transmit
multiprotocol data between two directly connected (point-to-point) computers. It is a byte - oriented protocol that
is widely used in broadband communications having heavy loads and high speeds.
Transmission Control Protocol (TCP): TCP is a popular communication protocol which is used for
communicating over a network. It divides any message into series of packets that are sent from source to
destination and there it gets reassembled at the destination.
Internet Protocol (IP): IP is designed explicitly as addressing protocol. It is mostly used with TCP. The IP
addresses in packets help in routing them through different nodes in a network until it reaches the destination
system. TCP/IP is the most popular protocol connecting the networks.
Simple mail transport Protocol (SMTP): SMTP or Simple Mail Transfer Protocol is an application that is used
to send, receive, and relay outgoing emails between senders and receivers. When an email is sent, it's transferred
over the internet from one server to another using SMTP. In simple terms, an SMTP email is just an email sent using
the SMTP server.
POP and POP3: Post Office Protocol (version 3): The Post Office Protocol is also an email protocol. Using
this protocol, the end user can download emails from the mail server to their own email client. Once the emails are
downloaded locally, they can be read without an internet connection. Also, once the emails are moved locally, they
get deleted from the mail server, freeing up space. POP3 is not designed to perform extensive manipulations with
the messages on the mail server, unlike IMAP4. POP3 is the latest version of the Post Office Protocol.

Telnet: Telnet is a set of rules designed for connecting one system with another. The connecting process here is
termed as remote login. The system which requests for connection is the local computer, and the system which
accepts the connection is the remote computer.
Voice over Internet Protocol (VoIP): It is a technology that allows you to make voice calls using a broadband
Internet connection instead of a regular (or analog) phone line.

Mobile telecommunication technologies


1G Vs. 2G Vs. 3G Vs. 4G Vs. 5G
The "G" stands for "GENERATION”. While you connected to internet, the speed of your internet is depends upon
the signal strength that has been shown in alphabets like 2G, 3G, 4G and 5G etc. right next to the signal bar on your
home screen. Each Generation is defined as a set of telephone network standards, which detail the technological
implementation of a particular mobile phone system. The speed increases and the technology used to achieve that
speed also changes. For e.g., 1G offers 2.4 kbps, 2G offers 64 Kbps and is based on GSM, 3G offers 144 kbps-2 mbps
whereas 4G offers 100 Mbps - 1 Gbps and is based on LTE technology .
The aim of wireless communication is to provide high quality, reliable communication just like wired
communication(optical fibre) and each new generation of services represents a big step in that direction.
1G - First Generation
This was the first generation of cell phone technology. The very first generation of commercial cellular network
was introduced in the late 70's with fully implemented standards being established throughout the 80's. It was
introduced in 1987 by Telecom (known today as Telstra), Australia received its first cellular mobile phone network
utilizing a 1G analog system. 1G is an analog technology and the phones generally had poor battery life and voice
quality was large without much security, and would sometimes experience dropped calls. These are the analog
telecommunications standards that were introduced in the 1980s and continued until being replaced by 2G digital
telecommunications. The maximum speed of 1G is 2.4 Kbps.
2G - Second Generation
Cell phones received their first major upgrade when they went from 1G to 2G. The main difference between the
two mobile telephone systems (1G and 2G), is that the radio signals used by 1G network are analog, while 2G
networks are digital . Main motive of this generation was to provide secure and reliable communication channel.
It implemented the concept of CDMA and GSM. Provided small data service like sms and mms. Second generation
2G cellular telecom networks were commercially launched on the GSM standard in Finland by Radiolinja (now part
of Elisa Oyj) in 1991. 2G capabilities are achieved by allowing multiple users on a single channel via multiplexing.
During 2G Cellular phones are used for data also along with voice. The advance in technology from 1G to 2G
introduced many of the fundamental services that we still use today, such as SMS, internal roaming, conference
calls, call hold and billing based on services e.g. charges based on long distance calls and real time billing. The max
speed of 2G with General Packet Radio Service (GPRS) is 50 Kbps or 1 Mbps with Enhanced Data Rates for GSM
Evolution (EDGE). Before making the major leap from 2G to 3G wireless networks, the lesser-known 2.5G and 2.75G
was an interim standard that bridged the gap.
3G - Third Generation
This generation set the standards for most of the wireless technology we have come to know and love. Web
browsing, email, video downloading, picture sharing and other Smartphone technology were introduced in the
third generation. Introduced commercially in 2001, the goals set out for third generation mobile communication
were to facilitate greater voice and data capacity, support a wider range of applications, and increase data
transmission at a lower cost .
The 3G standard utilizes a new technology called UMTS as its core network architecture - Universal Mobile
Telecommunications System. This network combines aspects of the 2G network with some new technology and
protocols to deliver a significantly faster data rate. Based on a set of standards used for mobile devices and mobile
telecommunications use services and networks that comply with the International Mobile Telecommunications-
2000 (IMT-2000) specifications by the International Telecommunication Union. One of requirements set by IMT-
2000 was that speed should be at least 200Kbps to call it as 3G service.
3G has Multimedia services support along with streaming are more popular. In 3G, Universal access and portability
across different device types are made possible (Telephones, PDA's, etc.). 3G increased the efficiency of frequency
spectrum by improving how audio is compressed during a call, so more simultaneous calls can happen in the same
frequency range. The UN's International Telecommunications Union IMT-2000 standard requires stationary speeds
of 2Mbps and mobile speeds of 384kbps for a "true" 3G. The theoretical max speed for HSPA+ is 21.6 Mbps.
Like 2G, 3G evolved into 3.5G and 3.75G as more features were introduced in order to bring about 4G. A 3G phone
cannot communicate through a 4G network, but newer generations of phones are practically always designed to
be backward compatible, so a 4G phone can communicate through a 3G or even 2G network.
4G - Fourth Generation
4G is a very different technology and its purpose is to provide high speed, high quality and high capacity to users
while improving security and lower the cost of voice and data services, multimedia and internet over IP. Potential
and current applications include amended mobile web access, IP telephony, gaming services, high-definition
mobile TV, video conferencing, 3D television, and cloud computing.
The key technologies that have made this possible are MIMO (Multiple Input Multiple Output)
and OFDM (Orthogonal Frequency Division Multiplexing). The two important 4G standards are WiMAX
and LTE (has seen widespread deployment). The max speed of a 4G network when the device is moving is 100 Mbps
or 1 Gbps. When 4G first became available, it was simply a little faster than 3G. 4G is not the same as 4G LTE which
is very close to meeting the criteria of the standards. To download a new game or stream a TV show in HD, you can
do it without buffering.
5G - Fifth Generation
5G is a generation currently under development, that's intended to improve on 4G. 5G promises significantly faster
data rates, higher connection density, much lower latency, among other improvements. Some of the plans for 5G
include device-to-device communication, better battery consumption, and improved overall wireless coverage.
The max speed of 5G is aimed at being as fast as 35.46 Gbps, which is over 35 times faster than 4G.
Key technologies to look out for: Massive MIMO, Millimeter Wave Mobile Communications etc. Massive MIMO,
millimeter wave, small cells, Li-Fi all the new technologies from the previous decade could be used to give 10Gb/s
to a user, with an unseen low latency, and allow connections for at least 100 billion devices . Different estimations
have been made for the date of commercial introduction of 5G networks.

Introduction to web services


WWW: It stands for World Wide Web, which is also known as a Web, is a collection of websites or web pages
stored in web servers and connected to local computers through the internet. Users can access the content of these
sites from any part of the world over the internet using their devices such as computers, laptops, cell phones, etc.
Hyperlink: A hyperlink is a word, phrase, or image that you can click on to jump to a new document or a new
section within the current document. It is a place in an electronic document on a computer or a website that is
connected to another electronic document.
Hyper Text Markup Language (HTML): It stands for Hyper Text Markup Language. It is the standard markup
language for creating Web pages which describes the structure of a Web page. HTML consists of a series of elements
which tell the browser how to display the contents.
Extensible Markup Language (XML): XML stands for extensible markup language. A markup language is a
set of codes, or tags that describes the text in a digital document. It is dynamic because it is used to transport the
data not for displaying the data as HTML do.
Website: A Web site is a collection of Web Pages. The first Page of a web site is known as a Home Page.
Webpage: A web page is one full page of contents in a website. A webpage may contain any content such as image,
text audio, video or hyperlinks etc.
Web Browser: It is a client side software to view website over the internet. Some popular Web Browsers are
Google Chrome, Mozilla Firefox, Internet Explorer, Amazon Silk, Apple Safari, Brave, Dolphin, Microsoft Edge and
Opera etc.
Web Server: A web server is a computer that runs websites. It's a computer program that distributes web pages
as they are requisitioned. The basic objective of the web server is to store, process and deliver web pages to the
users.
Web Hosting: Web hosting is a service that allows organizations and individuals to post a website or web page
onto the Internet. ... Their computer will then connect to your server and your webpages will be delivered to them
through the browser. Most hosting companies require that you own your domain in order to host with them.
Network Formation Based questions (Answer guidelines)
 Best layout of Network: It will be the arrangement where minimum wire is used.
 Placement of various devices:
 Server / Modem: The building having maximum number of computers
 Switch / hub / Router: Every building
 Repeater: in between the buildings where distance is more than or equal to 70
meters
 Best Topology
 Bus
 Star (If told that there’s a central computer of centralization required)
 Best wire / Communication Channel (Below given is the order of maximum speed of data)
 Optical fibre
 Ethernet Cable
 Telephone Cable
 Coaxial Cable
 Twisted Pair
 Wireless Medium – Satellite( if connection required between countries)
 Radio wave(For connecting in hilly area)
 Difference / Installation of LAN, MAN and WAN while connecting
 LAN: If distance is given in meters( upto 2 kilometers)
 MAN( Distance is more than 2 kilometers but city is same)
 WAN: Outside city or state or country
 Best way to connect to internet: BROADBAND CONNECTION
SAMPLE PAPER 2021 – 21(IP)

Ans: i) W3-W1-W2-W4
ii) Star Topology
iii) Broadband.
iv). a. Not required. Repeaters may be skipped as per above layout (because distance is less
than 70 m)
b. In every wing
v) Radio Waves
SAMPLE PAPER 2021 – 21(CS)

Ans: a). Most suitable place to install the server is HR center, as this center has maximum number of
computers.
b)

c) Switch
d) Repeater may be placed where distance between 2 buildings is more than 70 meter.
e) WAN, as the given distance is more than the range of LAN and MAN.
QUESTION 1: (2015)
QUESTION 2: (2016)
QUESTION 2: (2017)
QUESTION 2: (2018)
QUESTION 2: (2019)
NETWORKS FULL FORMS
TCP/IP Transmission Control Protocol / Internet Protocol DTR Data Terminal Ready
LAN Local Area Network RJ45 Registered Jack 45
MAN Metropolitan Area Network VoIP Voice over Internet Protocol
WAN Wide Area Network AUI Attachment Unit Interface
Modem Modulation(tor)/Demodulation(tor) SNA Systems Network Architecture
URL Uniform Resource Location VFIR Very Fast Infrared
FTP File Transfer Protocol URI Uniform Resource Identifier
HTTP Hyper Text Transfer Protocol URN Uniform Resource Name
PPP Point to Point Protocol MIME Mail and Multipurpose Internet Mail Extensions
GSM Global System for Mobile POP Post Office Protocol
CDMA Code Division Multiple Access SMTP Simple Mail Transfer Protocol
WLL(WiLL) Wireless in Local Loop NNTP Network News Transfer Protocol
SMS Short Message Service HTTP Hyper Text Transfer Protocol
WWW World Wide Web NTP Network Time Protocol
HTML Hyper Text Markup Language IMAP Internet Mail Transfer Protocol
XML Extensible Markup Language SLIP Serial Line Internet Protocol
NFS Network File System IPCP IP Control Protocol
ARPANET Advanced Research Projects Agency NCP Network Control Protocol
NSFnet National Science Foundation LCP Link Control Protocol
NIU Network Interface Unit PC Personal Computer
NIC Network Interface Card ISP Internet Service Provider
TAP Terminal Access Point (NIU = NIC = TAP) SIM Subscriber Identity Module
VGM Voice Grade Medium TDMA Time Division Multiple Access
DGM Data Grade Medium TDM Time Division Multiplexing
STP Shielded Twisted Pair IDEN Integrated Digital Enhanced Network
UTP Unshielded Twisted Pair WCDMA Wideband CDMA
LED Light Emitting Diode PSTN Public Switched Telephone Network
LD Laser Diode 3G Third Generation
KBPS Kilobits Per Second UMTS Universal Mobile Telecommunications System
KBPS Kilo Bytes Per Second EDGE Enhanced Data rates for Global Evolution
Mbps Mega Bits Per Second SMSC Short Message Service Center
MBps Mega Bytes Per Second HLR Home Location Register
Gbps Giga Bits Per Second Email Electronic Mail
GBps Giga Bytes Per Second PM Phase Modulation
OFC Optic Fiber Cable, Fiber Optic Cable VSNL Videsh Sanchar Nigam Limited
KHz Kilo Hertz DNS Domain Name Server
MHz Mega Hertz DHTML Dynamic Hyper Text Markup Language
GHz Giga Hertz A/F Audio Frequency
THz Tera Hertz IE Internet Explorer
Bps Bytes Per Second CTS Clear to Send
bps Bits Per Second RTS Request to Send
PDA Personal Digital Assistants CD Carrier Detect
P-P Point to Point DSR Data Set Ready
AM Amplitude Modulation FM Frequency Modulation

You might also like