Class 12 - Cs - Full Notes
Class 12 - Cs - Full Notes
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.
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.
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.
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.
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
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.
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
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.
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.
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
-------- ----------
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
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)
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;
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
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.
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.
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.
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 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
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
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
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
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
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
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
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)
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.
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)
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
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
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
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:
# 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");
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
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 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
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
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)
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
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]
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.
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.
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)
Repetition The repetition operator enables the list elements l1*2 = [1, 2, 3, 4, 1, 2, 3,
to be repeated multiple times. 4]
Iteration The for loop is used to iterate over the list for i in l1:
elements. print(i)
Output
1
2
3
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
SN Function Description
SN Function Description
1 list.append(obj) The element represented by the object obj is added 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.
11 list.sort([func]) It sorts the list by using the specified compare function if given.
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?
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)
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.
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])
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)
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)
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 range slice operator. It is used to access the characters from the specified
range.
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
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.
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.
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.
It is used to convert the string into the title-case i.e., The string meEruT will
title() be converted to Meerut.
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.
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
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 −
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:
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
}
2 len(dict): Gives the total length of the dictionary. This would be equal to the number of items in the
dictionary.
4 type(variable): Returns the type of the passed variable. If passed variable is dictionary, then it would
return a dictionary type.
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
dict.setdefault(key, default=None): Similar to get(), but will set dict[key]=default if key is not already
8
in dict
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:])
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',),),),),),)
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.
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.
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
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)
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.
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
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.
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
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)
#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
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)
#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.
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>=0true
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 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.
# 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)
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.
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.
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.
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.
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.
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:
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
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.
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