csitnote
csitnote
Structure
Structure is a user-defined data type used to represent a collection of logically related different
types data items with a common name.
● The keyword used to create a structure struct
Syntax Example1 Example2
struct structure_tag struct student struct employee
{ { {
data_type variable1; int rollno; int empno;
data_type variable2; char name[30]; char empname[30];
...................; float marks; float salary;
data_type variableN; }; };
};
1
Write a program to define a structure student with rollno and marks in three subjects and find total mark.
#include <iostream>
using namespace std;
struct student {
int rollno;
int m1,m2,m3;
};
int main()
{
student s; //structure variable
int total;
cout<<"Enter roll number: ";
cin>>s.rollno;
cout<<"Enter three marks: ";
cin>>s.m1>>s.m2>>s.m3;
cout<<”Total:”<<s.m1+s.m2+s.m3;
return 0;
}
Nested structure;A structure inside another structure.
Example(we can write 2 types of definition)
struct date struct student
{ {
int day; int rollno;
int month; char name[20];
int year; struct date
}; {
struct student int day;
{ int month;
int rollno; int year;
char }dob;
name[20]; float marks;
date dob; };
float marks;
};
2
Previous year questions
1. Structure combines different types of data under a single unit. Write a structure definition in
C++ which includes student details admission number, name, age and weight.
2.
A variable is associated with two values: L-value and R-value, where L-value is the address of the
variable and R-value is its content. Figure shows that, the L-value of num is 1001 and R-value is
25. If we want to store the L-value of a variable, we need another variable . This variable is known as
pointervariable
Declaration of pointer variable
Syntax:-datatype* pointer variable;
example:-int* ptr;
criterion for pointer datatype-The data type of a pointer should be the same as that of the data pointed to by
it.
The operators & and *
Address of operator(&):
It used to get the address of a variable
unary operator
It can be used with any type of variables
If num is an integer variable, its address can be stored in pointer ptr by the statements in the following
table:
Code Afterexecution
Int num=25;
int* ptr;
ptr=#
cout<<num; 25
cout<<*ptr; 25
cout<<ptr 1001
cout<<#
cout<<&ptr; 1001
1500
cout<<*num; error
indirection or dereference operator or value at operator (*):
retrieves the value at the location pointed to by the pointer.
Unary operators
Only be used with pointer variables
Methods of memory allocation
Static memory allocation: The memory allocation that takes place before the
execution of the program Eg.,intx,y;(variable declaration statements in the program).
Dynamic memory allocation:The memory allocation that takes place during the
execution of the program .It is facilitated by an operator, named new. C++ provides another
4
operator,named delete to de-allocate the memory.
Static memory allocation Vs.Dynamic memory allocation
Sl. Staticmemoryallocation Dynamicmemoryallocation
No.
1 Takes place before the execution of Takes place during the execution of
the program. the program.
2 No pointer is needed Pointer variable is essential.
3 No special operators needed. New operator is required.
4 No statement is needed for deallocate memory by using delete
deallocation. statement.
Operations on pointers
Arithmetic operations: only addition and subtraction allowed(+,-,++,--)
Relational operations:equal to(==) ,not equal to(!=)
Pointer and array
int ar[10]={34,12,8,18,24,38,43,14,7,19};
int *ptr;
6
Previous year questions
24.predict output
3.Data abstraction:
It refers to showing only the essential features of the application and hiding the details from outside
world.
4.Data encapsulation:
It binds the data and functions together and keeps them safe.
Wrapping up of data and functions into a single unit.
5.Polymorphism:
The ability to process objects differently depending on their data type or class.
6.Inheritance:
It is the process by which objects of one class acquire the properties and behaviour of another class.
7.Modularity:
Concept through which a program is partitioned into modules
How to create a Class in C++
Use keyword ‘class’
Syntax:
class classname
{
private:
variable declaration;
9
function decalratios;
public:
variable declaration;
function decalratios;
};
Data members: variables inside a class
Member functions: functions written inside a class
Example :
To define A class employee with two functions to read and display details of employees.
class employee {
private : int empno;
char name[30];
char designation[25];
long int salary;
public : void ReadData() {
cin>>empno;
cin>>name;
cin>>designation;
cin>>salary;
}
void DispData() {
cout<< name;
cout<< designation;
cout<< salary;
} };
10
Example program:
To create A class employee with two functions to read and display details of employees using
inlinefunctions
#include<iostream>
using namespace std;
class employee {
private : int empno;
char name[30];
char designation[25];
longint salary;
public : void ReadData() {
cin>>empno;
cin>>name;
cin>>designation;
cin>>salary;
}
void DispData() {
cout<< name;
cout<< designation;
cout<< salary;
}
};
int main()
{
employee e;
cout<< "Enter details of an employee ";
e.ReadData();
cout<< " The details are : ";
e.DispData();
return 0;
}
11
};
void employee : :ReaData()
{
cin>>empno;
cin>>name;
cin>>designation;
cin>>salary;
}
void employee : :DispData()
{
cout<< name;
cout<< designation;
cout<< salary;
}
int main()
{
employee e;
cout<< "Enter details of an employee ";
e.ReadData();
cout<< " The details are : ";
e.DispData();
return 0;
}
Inheritance
The technique of building new class(s) from an existing class(s) is called inheritance.
It support hierarchical classification and reusability.
Base class /parent class/super class: existing class
Derived class/child class/sub class: new class created from old one
Note:Any number of classes can be derived from an existing class
Types of inheritance
12
1. Single Inheritance
Derivation of a class from only one base class
2. Multiple Inheritance
One derived class from several base class.
3. Hierarchical Inheritance
One base class and several derived class
4. Multilevel Inheritance
Derivation of a class from another derived class
5. Hybrid Inheritance
Derivation of a class involving more than one form of inheritances (combination of different
inheritances)
To create derived class
Syntax:
Class derivedclasssname:accessspecifier baseclass
{
Class definition;
};
Simple program to create Student class using single inheritance
#include<iostream>
using namespace std;
class Student{
public:
int roll;
char sname[100];
char cname[100];
void input(){
cout <<"Enter Your Roll Number:";
cin>>roll;
cout <<"Enter Your Name:";
cin>>sname;
13
cout <<"Enter College Name:";
cin>>cname;
}
};
Class College:public Student {
public:
void display(){
cout <<"Your Roll is :"<< roll;
cout <<"\nYour Name is :"<< sname;
cout <<"\nCollege Name is :"<< cname;
}
};
Int main(){
College obj;
obj.input();
obj.display();
return0;
}
Polymorphism
Polymorphism means that some code or operations or objects behave differently in different contexts.
There are two types of polymorphism
a)Compile time (Early binding / Static)polymorphism.
b)Run-time (Late binging /Dynamic) polymorphism.
Compile time polymorphism:
Compile time polymorphism is achieved through Function overloading and operator overloading.
Run-time polymorphism is achieved through virtual functions. Here binding or linking of a function with
function definition is done during execution(run) time.
14
Compile time polymorphism:
Function Overloading:
Functions with the same name, but different signatures can act differently.
Defining multiple functions with the same name and different function signatures is known as
function overloading
For example area(int) can be used to find the area of a square whereas area(int, int) can be used to
find the area of a rectangle. Thus, the same function area() acts in two different ways depending on
its signature.
Simple program for area and volume of a rectangle and square(FUNCTION OVERLAODING
#include<iostream>
using namespace std;
int area(int s)
{
return s * s;
}
int area(int s1, int s2){
return (s1*s2);
}
int volume(int s)
{
return s*s*s;
}
int volume(int s1, int s2,int s3){
return (s1*s2*s3);
}
int main() {
cout << "Area and volume of Square:" << area(5)<<volume(5);
cout << "Area and volume of Rectangle:"<< area (7,2)<<volume(7,2,3);
}
Operator overloading:
Operator overloading is the concept of giving new meaning to an existing C++ operator.
To overload an operator, we need to write a member function for the operator we are
overloading.
Syntax:
returntype classame::operator(arguments)
{
function body;
}
class space {
private:
15
int x,y,z;
public:
int main() {
space s;
s.getdata(10,-20,30);
cout<<”s:”;
s.putdata();
return 0;
}
10.draw diagram and identify the type of inheritance for the following
a)class grade: public mark;
b) class job:private emp,private office;
11.an customer can use ATM without knowing its background details
a)name OOPs concept that we can correlate with this
b)explain the concept.
12.define virtual function
13. showing essential details by hiding implementation details is ………….. data abstraction
14.wrapping up of data and functions is ………………..data encapsulation.
15.derived class is also known as……… child class/subclass
16.base class is also known as ……… parent/super class
17.write program to overload a function area to find area of square and circle
17
18. which among the following is an object - oriented programming language ? Pascal (b) FORTRAN (c)
C++ (d) C
19.In inheritance the existing class is called ________ base class
20.define polymorphism.explian two types of polymorphism
21.Differentiate between data abstraction and data encapsulation
Data abstraction encapsulation
18
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++
source file.
Opening A File
A file must be opened before you can read from it or write to it.
Either of stream or fstream object may be used to open a file for writing.
ifstream object is used to open a file for reading purpose only.
syntax for open() function
streamobject .open ( " filename", filemode);
File Modes
ios::app
Append mode.
Append to end of file
ios::ate
Open a file for output and move the R/W control to the end of the file.
ios::in
Open a file for reading.
ios::out
Open a file for writing.
ios::trunk
If the file already exists, contents will be truncated
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory
and close all the opened files. But it is always a good practice that a programmer should close all the opened
files before program termination.
Syntax
Streamobject .close();
20
CHAPTER 4 WEB TECHNOLOGY
Abbrevations
HTML:Hyper Text Markup Language
TCP/IP:Transmission Control/Internet Protocol
DNS:Domain Name Server
HTTP:Hyper Text Transfer Protocol
HTTPS:Hyper Text Transfer Protocol Secure
SSL;Secure Socket Layer
URL : Uniform Resource Locator
SMTP:Simple Mail Transfer Protocol
Protocol:
Special set of rules to be followed by all devices in the communication.
Steps for routing a data packet from sender to receiver by using TCP/IP
Communication on WEB
Communication on the web can be categorised as
(i) client (browser) to web server example;email service
(ii) web server to web server communication.example:online shopping
Client to web server communication
web server is often used for referring to the server computer that hosts websites
example;email service
21
Web server technologies
Webserver
Web server
the server computer that hosts websites
a powerful computer which is always switched on and connected to a high bandwidth Internet
connection.
It consists of a server computer that runs a server operating system and a web server software
installed on it.
server operating systems :Linux distributions (Redhat, openSUSE, Debian, Ubuntu, etc.), Microsoft
Windows Server, FreeBSD, Oracle Solaris, etc.
web server packages : Apache Server,Microsoft Internet Information Server (IIS), Google Web
Server (GWS) and nginx
software port ( 16-bit unique number)
used to connect a client computer to a server to access its services like HTTP, FTP, SMTP, etc.
data center
• a dedicated physical location where organizations house their servers and networking systems. (
used for storing, processing and serving large amounts of mission-critical data to their clients)
• requires extensive backup power supply systems, cooling systems, high speed networking
connections and security systems.
DNS Server
• The Domain Name System (DNS) runs on a DNS server and returns the IP address of a domain
name requested by the client computer.
Web Designing
The first step in setting up a website is planning the web pages for the website.
After deciding the pages and the links, we need to design these web pages. Any text editor can be
used.
22
web designing softwares :Bluefish, Bootstrap, Adobe Dreamweaver
23
Scripting languages
Client scripting languages
A. JavaScript
client side scripting language and developed by Brendan Eich
B. VB Script
based on the programming language Visual Basic.
Server sidescripting languages
C. PHP
PHP stands for 'PHP: Hypertext Preprocessor'.
an open source general-purpose scripting language deveolped by Rasmus Lerdorf
PHP interpreter is available for all operating systems.
Linux platforms :LAMP (Linux, Apache, MySQL and PHP) server.
Windows operating systems : WAMP server software
D. Active Server Pages
Microsoft Active Server Pages (ASP) is a server-side scripting
ASP files have the extension .asp.
To run Microsoft's web server software, Internet Information Server (IIS) is required.
ASP files are executed only on Windows operating systems.
E. Java Server Pages
It is a server side scripting language that was developed by Sun Microsystems in 1999.
JSP is similar to PHP, but uses Java as programming language.
JSP files have the extension .jsp.
To run JSP, Apache Tomcat web server is required.
Previous year questions
1. Briefly explain web server
2. Compare client side scripting and
3. Compare static and dynamic webpages
4. write full form HTTP
SMTP
5. What is port?write port numbers for the services SMTP; HTTP; FTP;
6. Name protocol used for secure data transfer………….
7. Classify the following scripting languages into client side and server side.ASP,PHP,Javascript,VBscript
25
Common tags
<H1>, <H2>, <H3>, <H4>, <H5> and <H6> - Heading tags
<H1> creates the biggest text and <H6> the smallest.
Attributes:
Align :Left,Right ,Center
<P> tag - Creating paragraphs
Container tag
Align :left, right, center or justify.
<BR> tag - Inserting line break
used to break the current line of text and continue from the beginning of the next line.
an empty tag
<P> <BR>
Create paragraphs Breaks the current line and continues to the next line.
27
Adding comments in HTML document
HTML comments are placed within <!-- --> tag.
Previous year questions
1.expalin empty tag and container tag give example
2.write basic structure of HTML document
3.expalin essential tags in HTML
4.expalin attributes of <BODY >tag?
5.<HR>is a -----tag
6.compare <P> tag and <BR>
7.HTML stand for.........
8.the type of tag that require only starting tag but not an ending tag.....
9.explain text formatting tags
10.write HTML codes to display x>y x3+y3
11.which tag perform the same function of <STRONG>tag
12.pick odd one out a)HTML b)ALIGN c)HEAD d)CENTER
13.Face attribute is used with......tag
14.what is use of <PRE> tag
15.for scrolling text we use ........tag
16.normal font size of <FONT> tag
17.write about HTML entities for reserved characters or how special characters are represented in HTML
18.To insert image in an HTML document ....tag is used
19.......is the main attribute of <IMG> tag
20.What is the use of Alt attribute of<IMG> tag.
21.Design a webpage about Kerala with two or three sentences and use any four formatting tags. Also
include a map or image of Kerala
<HTML>
<HEAD>
<TITLE>Kerala</TITLE>
</HEAD>
<BODY bgcolor=Yellow>
<H1 Align="center">KERALA TOURISM</H1>
<P align="center">
<B>Kerala</B>, a state situated on the <I>tropical Malabar Coast of southwestern India</I>
is one of the most popular tourist destinations in the country. Named as one
of the ten paradises of the world by<U> National Geographic Traveler</U>, <EM>Kerala</EM> is
famous especially for its ecotourism initiatives and beautiful backwaters
</P>
<IMG SRC="/home/student/Desktop/kl.jpeg">
</BODY>
</HTML>
28
22 Write the use of the following tags: a)<B> b)<I> c)<U> d)<Q>
23. …….tag identifies the document as an HTML document
24. Write the HTML statement to scroll the text computer from top to bottom.
<marquee direction=“down”> <i> COMPUTER </i> </marquee>
25. Write the HTML code fragment to insert an image “Profile.jpg” aligned in center of a webpage.
<html><head><title>picture</title></head>
<body>
<center><img src=“profile.jpg”></center>
</body></html>
26. Identify errors in the following HTML code :
(a) < h1 > < b > web programming < /b > < /i > < /h1 >
<I> is not included
(b) < img src = ‘Profile.jpg’ size = 50 >
There is no attribute size for <img> tag.
27. Develop a web page of an organization with the following features:(March 2016, 2 Marks)
( a ) Has an image as background.
( b ) Welcomes users with a marquee in attractive fonts.
( c ) Displays address of the organization.
Ans.<HTML>
<BODY Background = “ pic.jpg “ >
<MARQUEE Height = “ 80 ” BGColor = “ Red “ Direction = “ Left “ > <font face=“arial”>Hello!!!!!!
Welcome to our world………..</font>
< /MARQUEE >
<ADDRESS> Address of the Instituition </ADDRESS>
</BODY>
</HTML>
28. ……….. tag is used to make the size of the text smaller than current text in HTML.
(a) <b> (b) <small> (c) <sub> (d) <sup>
29. Which is the tag used to create lin. break in a HTML page ?
Ans:<BR>
30. Categorize the following tags in HTML appropriately.
< br > , < h1 > , < img > , < table >
CHAPTER 5
Database Management Systems
DBMS stands for Database Management Systems
Drawback of file management system
• Duplication of data.
• No mechanism to protect the data
• May be chances of inaccuracy in the information.
• Inconsistency of data occurs
• No standardization on data.
Database :An organized collection of inter-related data stored together with minimum redundancy,
Database Management System (DBMS) : a set of programs which used for storing, retrieving and
managing database.
The primary goal of DBMS :to provide an environment that is both convenient and efficient to use in
retrieving and storing database.
29
Advantages of DBMS
a) Controlling data redundancy:- Duplication of data is known as data redundancy. In
DBMS data is kept in one place .So data redundancy is controlled.
b) Data consistency:- Data redundancy leads to data inconsistency (Different copies of same
data hold different values because the updation of data may not occur in all the copies). In
DBMS it is avoided by eliminating redundancy.
c) Efficient data access:- DBMS utilizes a variety of techniques to store and retrieve data
efficiently.
d) Data can be shared:- The data stored in the database can be shared among many users
and new programs can be developed to share the existing data.
e) Data integrity:- Integrity refers to the overall completeness, accuracy and consistency of
data in the database. It can be achieved by use of error checking, validation, avoiding
duplicationetc.
f) Security:- Security refers to accidental or intentional disclosure or unauthorized access,
modification or destruction. Through the use of passwords, information in the database is
made available only to authorized person. Access to specific information can be limited to
selected users by using access rights.
g) Enforcement of standards:- The database administrator defines standards like display
formats, report structure, update procedures, access rules etc.. for the DBMS.
h) Crash recovery:- If the system crashes, data in the database may become unusable.
DBMS provides some mechanism to recover data from the crashes.
Components of DBMS
a) Hardware: It includes actual computer system used for storage and retrieval of database.i.e.,
computers, storage devices, network devices, and other supporting devices.
b) Software: It consists of DBMS, application programs and utilities.
c) Data: The database should contain all the data needed by the organization.For effective
storage and retrieval of information, data is organized as fields, records and files.
1) Field: A field is a smallest unit of stored data. e.g. Name, Mark, etc.
2) Record: A record is a collection of related fields.
3) File: A file is a collection of records.
d) Users: The users of database can be classified depending on the mode of their interactionswith
DBMS.
e) Procedures: Procedures refers to the instructions and rules that govern the design and use
of the database.
Users of database
• Database administrator(DBA): responsible for the control of the database
Functions of DBA:
30
Design of the conceptual and physical schemas
Security and authorization
Data availability
recovery from failures:
• Application programmers :Computer professionals who interact with the DBMS through
application programs.(Interact with the DBMS through Data Manipulation Language (DML)).
• Sophisticated users : include engineers, scientists, business analysts, and others who are
thoroughly familiar with the facilities of the DBMS.( They interact with the systems through
their own queries)
• Naive users: interact with the system by using prewritten application programs.They don’t
know about DBMS.
Example: People accessing data over the web, clerical staff in an office, billing clerk in a
supermarket or hotels, bank clerk,
Data abstraction
a. Physical level
The lowest level of abstraction describes how data is actually stored on secondary storage devices
such as disks and tapes
b. Logical level
describes what data is stored in the database, and what relationships exist among those data.
also referred as conceptual level.
DBA uses logical level abstraction
c. View level
the highest level of database abstraction and is the closest to the users.
Data independence
The ability to modify the schema definition (data structure definition) in one level without affecting the
schema definition at the next higher level
a. Physical data independence
the ability to modify the schema followed at the physical level without affecting the schema followed
at the conceptual level.
b. Logical data independence
the ability to modify a conceptual schema without causing any changes in the schema followed at
view (external) level
PREVIOUS YEAR QUESTIONS
1. Expand DBMS
2. Explain advantages of DBMS
3. Drawback of file system compared to DBMS
4. Explain components of DBMS
5. Explain users of DBMS
6. List functions of DBA
7. Explain 3 levels of data abstraction
8. What is data independence?
9. Data about data is........
10. Storing same data in different places is........
11. Unauthorised accessing of data can be prevented from using.......
12. The billing clerk in a super market is.........user
13. The person who interact with DBMS using query
14.......interact with prewritten application programs
31
Relational data model
It is a model of DBMS that represents database as a collection of tables called relations. Most of the
database products are based on the relational model and they are known as Relational DataBase
Management System (RDBMS).
Eg: Oracle, Microsoft SQLServer, MySQL,DB2,Informix,Ingress
Query languages;SQL,QBE or Datalog
Terminologies in RDBMS
Entity: It is a person or a thing in the real world that is distinguishable from others. For
example, student, teacher etc.
Relation: It is a collection of data organized in the form of rows and columns. A relation is also
called Table. Example
Relational algebra
• The collection of operations that is used to manipulate the entire relations of a database
• The fundamental operations in relational algebra
SELECT, PROJECT, UNION, INTERSECTION, SET DIFFERENCE,CARTESIAN PRODUCT, etc.
• The SELECT and PROJECT operations – Unary Operations
• The remaining operations -Binary operations
SELECT operation
• to select rows from a relation that satisfies a given predicate(condition)
• denoted using lower case letter sigma ( ).
• The relational algebra uses various comparison operators < (less than), <= (less than or equal to), >
(greater than), >= (greater than or equal to), = (equal to) and < > (not equal to) and logical operators
(OR), (AND) and ! (NOT)
33
PROJECT operation
• selects certain attributes from the table and forms a new relation.
• It is denoted by lower case letter
UNION operation
• a binary operation
• returns a relation containing all tuples appearing in either or both of the two specified relations. It is
denoted by ∪ .
• two relations must be union-compatible
• Eliminates duplicates,ARTS ∪ SPORTS
34
INTERSECTION operation
• a binary operation
• it returns a relation containing the tuples appearing in both of the two specified relations.
• It is denoted by ∩ .
• The two relations must be union-compatible,ARTS ∩ SPORTS
35
PREVIOUS YEAR QUESTIONS
15. Distinguish between the terms degree and cardinality used in RDBMS
16. Define the following terms a)Entity :b)Relation c)Tuples and attributes d)schema
17. Explain about UNION, INTERSECTION and SET in Relational Algebra.
18. The number of rows in a relation is called ……
19. What is a primary Key? What is the significance of primary key in a relation?
Ans. A primary key is a set of one or more attributes that can uniquely identify tuples within the
relation. Eg: In student table no two student have the same Admno. So Admno can be used as
primary key in student table
20. A candidate key that is not a primary key is called … …. … key
21. Define primary key and alternate key
22.The number of attributes in a relation is called ………
23. . …….. symbol is used for select operation in relational algebra.a). σ b). π c). υ d).n
24. . In RDBMS a relation contains 10 rows and 5 columns.What is the degree of the relation?
25. Define the following.a) field b) record
26.
27. Consider the following table :
( a ) Identify the degree,domain of total and cardinality of the given table.
( b ) Identify a suitable primary key for the given table.
28. First table containing 4 rows and 3 columns, second table contains 5 rows and 2 columns, then
the cartesian product table contains…….. rows and ……….columns,
29. Consider the given table SPORTS and write the relational expressions for the following
questions: (a) Select the name of all players.
36
(b) Select name and goals scored by players who have scored more than 70 goals.
CHAPTER 6
STRUCTURED QUERY LANGUAGE(SQL)
Structured Query Language (SQL) is a language designed for managing data in relational database
management system (RDBMS).
SQL is a non-procedural language
Query:A query is a request to a database
Components of SQL
Data Definition Language (DDL): DDL component is dealing with schema (structure) definition of the
RDBMS. DDL commands are used to create, modify and remove the database objects such as tables, views
and keys
eg: CREATE, ALTER, DROP commands
Data Manipulation language (DML): DML permits users to insert data into tables, retrieve existing
data, delete data from tables and modify the stored data. Data Manipulation Language (DML) statements are
used for managing data in database .
Eg: INSERT,SELECT,UPDATE commands
Data Control Language (DCL): DCL includes commands that control a database, including administering
privileges and committing data eg:GRANT and REVOKE
MySQL
• MySQL is a free, fast, easy-to-use RDBMS
Creating a database
• The database is the container in which we store the tables.
• To create a database in MySQL
CREATE DATABASE command.
The syntax is as follows:
CREATE DATABASE <database_name>;
eg:CREATE DATABASE school;
Opening database
37
• To perform operations on a database, we have to open it explicitly. When we open a database, it
becomes the active database in the MySQL server.
• MySQL gives a command USE to open a database.
The syntax is:
USE <database_name>;
Eg:USE school;
To list the entire databases in our system
The SHOW DATABASE command is used to check whether a database exists or not.
• The syntax is: SHOW DATABASES;
used when the data in a column are of the Used for column that may contain different number of
same fixed length characters
the remaining allocated character the space allocated for the data depends only on the
positions in the string will be filled with actual size of the string
white spaces
38
CREATE TABLE student(adm_no INT,name VARCHAR(20),gender CHAR,dob DATE,course
VARCHAR(15),f_income INT);
Constraints
Constraints are the rules enforced on data that are entered into the column of a table.
• This ensures the accuracy and reliability of the data in the database.
• The constraints ensure database integrity and hence they are often called data base integrity
constraints.
Constraints could be column level or table level.
Column Constraints
applied only to individual columns
i. NOT NULL
• This constraint specifies that a column can never have NULL values.
• NULL is a keyword represents an empty value.
ii. AUTO_INCREMENT
• to perform an auto-increment feature.
• By default, the starting value for AUTO_INCREMENT is 1, and it will be incremented by 1
• The auto increment column must be defined as the primary key of the table.
Only one AUTO_INCREMENT column per table is allowed
iii. UNIQUE
• It ensures that no two rows have the same value in the column specified with this constraint.
iv. PRIMARY KEY
• This constraint declares a column as the primary key of the table.
• This constraint is similar to UNIQUE constraint except that it can be applied only to one column or
a combination of columns.
• The primary keys cannot contain NULL values.
v. DEFAULT
• a default value can be set for a column, in case the user does not provide a value for that column of
a record.
Example :CREATE TABLE student (roll_no INT PRIMARY KEY, name VARCHAR(30), mark INT);
Table constraints
• used not only on individual columns, but also on a group of columns.
• When a constraint is to be applied on a group of columns of a table, it is called table constraint.
40
c. Conditions based on pattern matching
a pattern matching operator LIKE
Patterns are specified using two special wildcard characters % and _
where % matches a substring of characters and _ matches a single character.
Patterns are case sensitive
"A%" :any string beginning with "A".
eg:SELECT * FROM student WHERE name LIKE ‘A%;
"%cat%" : any string containing "cat" as substring.
For example,"education", "indication", "catering" etc.
"_ _ _ _" :any string of exactly four characters without any space in between them.
"_ _ _ %" : any string of at least 3 characters.
d. Conditions based on NULL value search :Use IS operator.
Eg:SELECT name, course FROM student WHERE f_income IS NULL;
Aggregate functions
41
• These functions are called aggregate functions because they operate on aggregate of tuples
(records).
• The result of an aggregate function is a single value.
While calculating these values, the NULL values in the argument column are not considered.
Difference between count(*) and count(column)
• count(*) :return the number of all the columns
• count(column):return the number of non-null values in the column
Grouping of records using GROUP BY clause
• to divide the tuples in a table into different groups based on the values in a column.
• categorisation of records is done.
HAVING clause: Applying conditions to form groups
• SELECT course, COUNT(*) FROM student GROUP BY course HAVING COUNT(*) > 3;
Difference between WHERE and Having Clause
• WHERE clause: places conditions on individual rows.
• HAVING clause : apply conditions to form groups and used along with Group By clause
Nested queries:
One query inside another query
• A MySQL inner query is also called sub query . the query that contains the sub query is called an
outer query.
• SQL first evaluates the inner query(sub query) within the WHERE clause and the result of inner
query is then substituted in the condition of the outer query.
• While using relational operators, ensure that the sub query (inner query) returns a single row output.
Eg:SELECT name, course FROM student2015 WHERE f_income=(SELECT MAX(f_income) FROM
student2015);
Views
• A view is a virtual table that does not really exist in the database, but is derived from one or more
tables.
• The table(s) from which the tuples are collected to constitute a view is called base table(s).
• These tuples are not physically stored anywhere, rather the definition of the view is stored in the
database.
• A view can be created with the DDL command CREATE VIEW.
• The syntax is:
CREATE VIEW <view_name>
AS SELECT <column_name1> [,<column_name2],...]
FROM <table_name>
[WHERE <condition>];
advantages of views
• without using extra storage space, we can use the same table as different tables (but virtual).
• views implement sharing along with privacy
• It also helps to reduce the complexity of conditions with WHERE clause
To delete view use :DROP VIEW command
• it will not affect the base table(s).
• The syntax is:DROP VIEW <view_name>;
PREVIOUS YEAR QUESTIONS
29. Define view in SQL and write the syntax of the command usd,to create a view.
30.What is nested queries
31. ……is a virtual table that does not exist in database
32. Give the correct syntax of the queries in SQL for the following
a) Renaming a table b) Deleting rows from a table c) Changing definition of a column
d) Removing columns from a table e) Adding a new column
33. Write SQL for a). Create a table student with the data [name char(25), rollno number(3), mark number(3)]
b). List name and rollno of all students
c). List name and rollno of students having marks>600
34. An Employee table contains name , empno, basicpay , desig. DA,salary.Write SQL for,
a) a) Display empno, name and basicpay of all managers( desig = “manager”)
b). Display empno and salary of all employees. (salary = basicpay + DA)(DA = basicpay *1.15)
c). Display name and empno of all employees whose basicpay < 10000.
44
CHAPTER 7 ADVANCES IN COMPUTING
Distributed Computing
It is a method of computing in which large problems are divided into many small
problems.
3. Cluster Computing
It is a form of computing in which a group of personal computers, storage devices, etc. are linked
together through a LAN so that they can work like single computer.
It is a low cost form of parallel processing.
Linux is the widely used OS for cluster computing.
Advantages
Price performance ratio
Availability
Scalability
Disadvantages
Programmability issues
Problem in finding fault
5.Cloud computing:
Cloud computing is the use of computing resources that resides on a remote machine and are
delivered to the end users as a service over network.
It uses Internet and central remote servers to maintain data and applications.
Eg:email
Cloud service models
1. SaaS( Software as Service)
2.PaaS( Platform as Service)
3.IaaS( Infrastructure as Service)
1. SaaS:
A SaaS provider gives subscribers access to both resources and a pplications as a
service on demand.
Adobe, Microsoft, facebook.com etc
2. PaaS:
A PaaS provider gives subscribers access to the components that they require todevelop
and operate applications over the Internet,
Google’s App Engine, Microsoft Azure, Force.com
3. IaaS: It deals primarily with computational infrastructure. IaaS provides basic s torage and
computing capabilities as standardized services over the network.
Amazon Web Services, Joyent, AT & T,Go Grid.
Advantages of Cloud computing:
1. Cost savings 2. Scalability/Flexibility 3.Reliabilty:
4. Maintenance: 5.Mobile accessible:
Disadvantages: 1.Security and privacy: 2.Lack of standards.
Previous year questions
1. Compare serial and parallel computing
2. Define cloud computing.Explain cloud computing services?
3. Define distributed computing
4. …….. Computing makes better use of existing hardware.
5………. is the most widely used operating system.
6. Advantages of distributed computing
46
7. The computing technology in which a problem is broken into pieces and solved concurrently is
called……
8. Explain the advantages and disadvantages of cloud computing and grid computing
Artificial Intelligence (AI)
The first definition of AI was established by Alan Turing. AI can be defined as developing computer
programs to solve complex problems by applications of processes that are similar to human reasoning
processes. Alan Turing proposed Turing Test, which is considered as the ultimate test a machine must pass
in order to be called as intelligent.
Computational Intelligence
The study of human-machine interaction to solve real life problems led to the development of Cybernetics. It
is defined as the study of control and communication between man and machines.
Computation Intelligence (CI) (commonly referred to as AI) is the study of adaptive mechanisms
(algorithms) to facilitate intelligent behavior in complex and changing environment so as to solve real life
problems.
The four main paradigms of Computational Intelligence are
Artificial Neural Networks (ANN),
Evolutionary Computation (EC),
Swarm Intelligence (SI)
Fuzzy Systems (FS).
Artificial Neural Networks (ANN)
The research in algorithmic modeling of biological neural system. It focuses on human brain that has
the ability to perform tasks such as pattern matching, perception and body movements, and also the
ability to learn, memorise, generalize etc.
Evolutionary Computation (EC) has its objective to mimic processes from natural evolution. It focuses on
the survival of the fittest and death of the weak. EC is used in data mining, fault diagnosis etc.
Swarm Intelligence (SI) is originated from the study of colonies or swarms of social organisms.
Choreography of bird flocks and foraging behavior of ants led to different optimization algorithms.
Fuzzy Systems (FS) allows reasoning with uncertain facts to infer new facts. In a sense, fuzzy logic allows
the modeling of common sense. Fuzzy systems have been applied in gear transmission in vehicles,
controlling traffic signals etc
Applications of Computational Intelligence
1)Biometrics 2)Robotics 3) Computer vision
4)Natural Language Processing 5)Automatic Speech Recognition
6)Optical Character Recognition and handwritten Character Recognition Systems
7)Bioinformatics 8)Geographic Information System
1.Biometrics: It refers to the measurements (metrics) related to human characteristics. It is used in
identification of individual in terms of finger print, palm veins, face, hand geometry, iris, retina and odour.
2.Robotics:Robotics can be defined as the scientific study associated with the design, fabrication,
theory and application of robots.
3.Computer vision:Computer vision is concerned with the theory and technology for building
artificialsystems that obtain information from images or multi-dimensional data.
4.Natural Language processing (NLP):Natural language processing is the branch of computer
science focused on developingsystems that allow computers to communicate with people using
any human language such as English, Malayalam etc.
5.Automatic Speech Recognition (ASR):This system allows a computer to identify the words
that a person speaks into a microphone or telephone and convert it into written text.
6.Optical Character Recognition(OCR) and Handwritten Character Recognition
Systems(HCR):OCR and HCR is used for pattern recognition. ,OCR converts the scanned
images of printed text (numerals, letters or symbols) into computer processable format.
7.Bioinformatics:Bioinformatics is the application of computer technology to the management of
47
biological information.
8.Geographic Information System (GIS):Geographic Information System(GIS) technology is
developed from digital cartographyand Computer Aided Design(CAD) database management
system.
Previous year questions
9.define cybernetics
10.explain computational intelligence?
11.explain any 4 advantages of computational intelligence?
12.what do you mean by GIS
13.ANN is……..
14.NLP stands for……….
15.the scientific study associated with the design, fabrication,theory,and application of robots are
called…….
CHAPTER 8
ICT and Society
ICT- Information Communication Technology
• Integrating telecommunication and computers comprising of many technologies for
capturing,processing,interpreting and printing information.
ICT Services
• E-Governance
• E-Learning
• E-Business
E-Governance
• Application of ICT for delevering Government services to the public in a convenient, efficient and
transparent manner.
Types of interactions in e-Governance
e-Governance facilitates interaction between different stakeholders in governance
• Government to Govenment(G2G)
• Government to Citizens(G2C)
• Government to Business(G2B)
• Government to Employees(G2E)
Government to Government (G2G) - It is the electronic sharing of data and/or information among
government agencies, departments or organisations.
Government to Citizens (G2C) - It creates an interface between the government and citizens. Here the
citizens enjoy a large range of public services.
Government to Business (G2B) - Here, e-Governance tools are used to aid the business community to
interact with the government.
Government to Employees (G2E) - This interaction is a two-way process between the government and the
employees. The salary and personal details of government employees are also managed through e-
Governance services
e-Governance infrastructure
48
State Data Centers (SDC)
• for providing core infrastructure and storage.
Functions of SDC:
• keeping central data repository of the state,
• securing data storage
• online delivery of services
• citizen information/services portal
• state intranet portal
• disaster recovery, etc.
SDCs also provide better operation and management control and minimize the overall cost of data
management, resource management, deployment etc.
State Wide Area Network (SWAN)
• for connectivity
• Kerala State Wide Area Network (KSWAN) has been set up as a backbone of the State
Information Infrastructure (SII).
It connects Thiruvananthapuram, Kochi and Kozhikode as its hubs and extends to all the 14 districts
linking each of the 152 Block Panchayats.
Common Service Centres (CSC)
• the front-end delivery points of the government, private and social sector services for the rural
citizens of India. A highlight of the CSCs is that it offers web-enabled e-Governance services in rural
areas.
• In Kerala Akshaya centres are working as Common Service Centres.
Major benefits of e-Governance:
It leads to automation of government services.
It strengthens the democracy.
It ensures more transparency and helps eliminate corruption.
It makes each department responsible
It saves time and money.
A few challenges:
• Security measures are highly required.
• Usually a huge initial investment and planning are required.
• Integation of deiffeent deparments are esssential.
• Low e-literacy
Eg: www.dhsekerala.gov.in ,www.keralamvd.gov.in
e-Business
e-Business is the sharing of business information, maintaining business relationships and conducting
business transactions by means of the ICT application.
49
E-comerce and e-business
e-Commerce covers business transaction that involve exchange of money, whereas eBusiness includes all
aspects of running a business such as marketing, obtaining raw materials or goods, customer education,
looking for suppliers etc. Thus e-Business is an extension of e-Commerce.
Electronic Payment System (EPS)
• a system of financial exchange between buyers and sellers in an online environment.
• The financial exchange is facilitated by a digital financial instrument (such as credit/debit card,
electronic cheque or digital cash) backed by a bank and/or an intermediary.
e-Banking or electronic banking
• The automated delivery of banking services directly to customers through electronic channel.
• Facilities such as ATM, debit cards, credit cards, Internet banking and core banking help in
transforming traditional banking into e-Banking.
e-Learning
• The use of electronic media and ICT (Information and Communication Technologies) in education is
termed e-Learning.
e-Learning tools:
• Electronic books reader (e-Books): Portable computer device that are loaded with digital book
content via communication interfaces
• e-Text: Textual information available in electronic format
• Online chat: a real-time exchange of text messages between two or more persons over the Internet.
• e-Content: the e-Learning materials that are delivered in different multimedia like videos,
presentations, graphics, animations, etc
• Educational TV channels:the telecasting/webcasting channels which are dedicated for the e-
Learning purpose.
Major advantages of e-Learning:
e-Learning has the ability to offer courses on variety of subjects to large number of students from
distant location.
Cost for learning is much less. It saves journey time and money, instructor fees, etc.
It provides facility to do online courses from various nationally or internationally reputed
institutions.
Time and place is not a constraint for e-Learning.
A few challenges:
• Face to face contact between students and teachers is not possible.
• Learners who require constant motivation may not be serviced adequately.
• Hands-on practical in real laboratory scenario is also a constraint in e-Learning.
Eg: www.ignouonline.ac.in,www.nptel.iitm.ac.in.www.w3schools.com
50
Information security
Intellectual Property Right(IPR)
• Many people are engaged in creative work like music, literary work, artistic work, discoveries,
inventions, designs and software development. These works are the creation of the mind. They
demand a lots of hard work and time. The outcome of such work is called intellectual property.
• IPR refers to the exclusive right given to a person over the creation of his/her mind, for a period of
time. IPR enables people to earn recognition and financial benefit from what they invent or create.
• World Intellectual Property Organization (WIPO): ensure that the rights of creators or owners of
intellectual property are protected worldwide and the inventors and authors are recognised and
rewarded by their creation.
Intellectual property is divided into two categories
industrial property
copyright.
A. Industrial property
• Industrial property right applies to industry, commerce and agricultural products.
• It protects
patents to inventions
trademarks
industrial designs
geographical indications.
• In India, industrial property rights can be registered with Controller General of Patents Designs and
Trademarks under Ministry of Commerce and Industry.
Patents: A patent is the exclusive rights granted for an invention.
It is the legal right obtained by an inventor for exclusive control over the production and sale of his/her
mechanical or scientific invention for a limited period of time.
Trademark: A trademark is a distinctive sign that identifies certain goods or services produced or provided
by an individual or a company. A Trademark can be a name, logo, symbol,etc. that can be used to
recognise a product or service.
Industrial designs: An industrial design refers to the ornamental or aesthetic aspects of an article. A design
may consist of three-dimensional features such as the shape, surface of an article or two-dimensional
features, such as patterns, lines or colour.
Geographical indications: Geographical indications are signs used on goods that have a specific
geographical origin and possess qualities or a reputation that are due to that place of origin.
B. Copyright
• A copyright is a legal right given to the creators for an original work, usually for a limited period of
time.
• Copyright applies to a wide range of creative, intellectual or artistic forms of works which include
books, music, painting, sculpture, films, advertisement and computer software.
• This covers rights for reproduction,communication to the public, adaptation and translation of the
work.
Infringement
Unauthorised use of intellectual property rights such as patents, copyrights and trademarks are called
intellectual property infringement.
• Patent infringement is caused by using or selling a patented invention without permission from the
patent holder.
• Trademark infringement occurs when one party uses a trademark that is identical to a trademark
owned by another party, where both the parties use it for similar products or services
• Copyright infringement is reproducing, distributing, displaying or adaptating a work without
permission from the copyright holder. It is often called piracy.
51
Cyber space
• Cyber space is a virtual environment created by computer systems connected to the Internet.
• Cyberspace is an unreal world in which communication over computer networks occurs.
• Cyberspace is a space where social interactions dominate.
Cyber Crime
It is defined as a criminal activity in which computers or computer networks are used as a tool ,target or a
place of criminal activity.
The victims of cyber crime lose money, reputation and face mental trauma.
Cyber crimes include phishing, hacking, denial of service attacks, etc.
• Cyber crimes can be basically divided into 3 major categories: They are cyber crimes against
individuals, against property and against government.
A. Cyber crimes against individuals
• An act of a person in cyberspace that causes physical or mental trouble to an individual is referred as
cyber crime.
Cyber crimes against individuals
• Identity theft occurs when someone uses another person's identifying information, like their name,
credit card number, etc. without their permission to commit fraud or other crimes.
• Harassment means posting humiliating comments focusing on gender, race, religion,
nationality at specific individuals in chat rooms, social media, e-mail, etc. is harassment.
The use of the Internet, to harass someone is called cyber stalking
• Impersonation and cheating: Impersonation is an act of pretending to be another person for
the purpose of harming the victim.
• Violation of privacy: Violation of privacy is the intrusion into the personal life of another, without
a valid reason.
• Dissemination of obscene material: Hosting website containing prohibited materials, use of
computers for producing obscene material, downloading obscene materials through the Internet,
etc.
B. Cyber crimes against property
• Cyber crimes against all forms of property like credit cards, intellectual property, etc. are termed as
cyber crime against property.
i. Credit card fraud: Credit card fraud involves an unauthorised usage of another person's credit
card information for the purpose of payments for purchases or transferring funds from it.
ii. Intellectual property theft: The infringement of IPR's come under this category.Violation of
copyright, patent, trademark, etc. are intrusions against property.
iii. Internet time theft:
The usage of the Internet time by unauthorised persons, without the permission of the person who
pays for it is called Internet time theft. This leads to loss of Internet time and money.
Above this, others may use our Internet account for committing crimes, for which we may also be
held responsible.
• The different types of attacks like viruses, worms, man in the middle attack, etc. also fall under cyber
crimes against property.
C. Cyber crimes against government
Increasing popularity of e-governance has made governments vulnerable to cyber attacks.
i. Cyber terrorism: Cyber terrorism is a cyber attack against sensitive computer networks like
nuclear power plants, air traffic controls, gas line controls, telecom, etc.
• Cyber terrorism focuses on the use of the Internet by anti nationals to affect a nation's economic and
technological infrastructure.
ii. Website defacement:
• Defacement of websites includes hacking of government websites and posting derogatory comments
about a government in those websites.
52
iii. Attacks against e-governance websites: These types of attacks deny a particular online
government service. This is done using a distributed Denial of Service (DDoS) attack
• In another case the website may be hacked and controlled by the hackers. This causes huge loss to
the government.
Cyber ethics
• Use anti-virus, firewall, and spam blocking software for your PC.
• Ensure security of websites while conducting online cash transactions.
• Do not respond or act on e-mails sent from unknown sources.
• Use unique and complex passwords for accounts and change your passwords on a regular basis
• Do not select the check boxes or click OK button before reading the contents of any
agreement/message.
• Avoid the use of unauthorised software.
• Do not hide your identity and fool others.
• Do not use bad or rude language in social media and e-mails.
• Remove the check mark against 'Remember me' before logging into your account using computers
other than yours.
Cyber laws
• The term cyber law in general refers to the legal and regulatory aspects of the Internet.
• Cyber law can be defined as a law governing the use of computers and Internet.
• In India which is addressed by the Information Technology Act, 2000 and IT Act Amendment Bill
2008.
53
Cyber forensics can be defined as the discipline that combines elements of law and computer
science to collect and analyze data from computer systems, networks, communication systems and
storage devices in a way that is admissible as evidence in a court of law.
• The goal of computer forensics is to analyse data in a way that preserves the integrity of the evidence
collected so that it can be used effectively in a legal case.
Infomania
• Infomania is the state of getting exhausted with excess information.
• Infomania is the excessive enthusiasm for acquiring knowledge. This may result in neglecting the
more important things like duties, family, etc.
• We may see people browsing for information during dinner. It is now treated as a psychological
problem. Constantly checking e-mails, social networking sites, online news, etc. are the symptoms of
infomania.
• Many people do this to keep themselves up to date with the fear of being out of the group.
CHAPTER 9
Python
Python
Interpreted high level language.
It is portable
It can be treated as procedure oriented and object oriented
Open soure
Extension used for python file is .py
Python Indentation
Indentation refers to the spaces at the beginning of a code line.
Where in other programming languages the indentation in code is for readability only, the indentation in
Python is very important.
Python uses indentation to indicate a block of code.
Python Variables
In Python, variables are created when you assign a value to it:
Python has no command for declaring a variable.
x=5
y = "John"
print(x)
print(y)
You can get the data type of a variable with the type() function.
x=5
y = "John"
print(type(x))
print(type(y))return type of x as int and y as string
Variable Names
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
Multiple Assignment
Python allows you to assign a single value to several variables simultaneously.
For example ,a = b = c = 1
Here, an integer object is created with the value 1, and all three variables are assigned to the same
memory location.
You can also assign multiple objects to multiple variables. For example −a, b, c = 1, 2, "john"
Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and
one string object with the value "john" is assigned to the variable c.
Comments
Single line comment:Comments start with a # Python will render the rest of the line as a comment:
55
multiline comments use triple quotes (“””) and write inside triple quotes
Example:
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
Data Types
In programming, data type is an important concept.
Python has the following data types built-in by default, in these categories:
Text Type: Str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Boolean Type: bool
Int:a whole number, positive or negative, without decimals, of unlimited length.
Float: a number, positive or negative, containing one or more decimals.
complex :number consists of an ordered pair of real floating-point numbers denoted by x +yj, where x and y
are the real numbers and j is the imaginary unit.
String:
Strings in Python are identified as a contiguous set of characters represented in the quotation marks. Python
allows for either pairs of single or double quotes.
• 'hello' is the same as "hello".
List:
- A list contains items separated by commas and enclosed within square brackets [].
- List is a collection which is ordered and changeable(mutable) and allows duplicate members.
57
operator purpose Example(x=5,y=2)
< Less than x<y return false
> Greater than x>y return true
<= Lessthan or x<=y return false
equal to
>= Greater than or x>=y return true
equal to
== Equal to x==y return false
!= Not equal to x!=y return true
Logical operators: used to combine conditional statements:
operator Purpose
And
Returns True if both statements are true
Or
Returns True if one of the statements is true
Not
Reverse the result, returns False if the result is true
Identity operators: Identity operators are used to compare the objects, not if they are equal, but if they are
actually the same object, with the same memory location:
operator Purpose
Is
Returns True if both variables are the same object
is not
Returns True if both variables are not the same object
not in
Returns True if a sequence with the specified value is not present in the object
Conditional statements
if
The if statement contains a logical expression using which data is compared and a decision is made based on
the result of the comparison.
Syntax:
58
if expression:
statement(s)
If the expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If
expression evaluates to FALSE, then the first set of code after the end of the if statement(s) is executed.
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
if else
An else statement can be combined with an if statement. An else statement contains the block of code (false
block) that executes if the conditional expression in the if statement resolves to 0 or a FALSE value.
Syntax of if - else :
if test expression:
Body of if stmts
else:
Body of else stmts
Example:largest of two numbers
a = int(input())
b = int(input())
if a > b:
print("a is greater than b")
else:
print("a is not greater than b")
If-elif-else:
The elif statement allows us to check multiple expressions for TRUE and execute a block of code as soon as
one of the conditions evaluates to TRUE.
Syntax of if – elif - else :
if test expression:
Body of if stmts
elif test expression:
Body of elif stmts
else:
Body of else stmts
Example:largest of 3 numbers
a=int(input('enter the number'))
b=int(input('enter the number'))
c=int(input('enter the number'))
if a>b:
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")
Iteration statements(loop):
Repeated execution of a set of statements with the help of loops is called iteration.
While loop:
Syntax:
59
while(expression):
Statement(s)
Example : print first 10 numbers
i=1
while (i < 10):
print (i)
i = i+1
For loop:
Syntax:
for var in sequence:
Statement(s)
Example: print first 10 numbers
for i in range(1,10):
print i
String builtin functions
function Purpose
isalnum() Returns true if string characters are alphanumeric and false otherwise.
isalpha() Returns true if string characters are alphabetic and false otherwise.
isdigit() Returns true if string contains only digits and false otherwise.
islower() Returns true if string characters are in lowercase and false otherwise
isupper() Returns true if string characters are in uppercase and false otherwise
upper() Convert to uppercase
lower() Convert to lowercase
split() Splits string according to delimiter str (space if not
provided) and returns list of substrings;
example:
string=”Nikhil Is Learning”
string.split()
[‘Nikhil’, ‘Is’, ‘Learning’]
count() counts the occurrence of a string in another string
example:
string='Nikhil Is Learning'
string.count('i')
3
60
pop() Removes the element at the specified position
Eg: college.pop(1)
‘thss’will be removed from list
remove() Removes the first item with the specified value
Eg: college.remove("it")
['thss', 'cse', 'autonomous']
sort() Sort the list
Tuple functions
function Purpose
len() Find length of tuple
cmp() Compare tuples
Return 0 when tuples are equal
Return -1 when tuple 1 < tuple2
Return 1 when tuple 1 > tuple 2
count() Returns the number of elements with the specified value
max() Maximum value of tuple
min() Minimum value of tuple
Tuple() Create new tuple
CGI-Common Gateway Interface
GET and POST
browser uses two methods two pass this information to web server
GET POST
Passing Data is visible Data not visible (send using input file)
Data submitted as part of URL Data submitted as part of http request
Data sending is fast Data secure but slow
Get can only send 1024 characters No limit for data
Previous year questions
1……..symbol used for comment in python
2. Explain while loop in python with example
3. Compare list and tuple in python
4. Write a python program to find largest of 2 numbers
5. Which one is relational operator in python a) + b)< c)= d)&&
6. In python ………..is an unordered collection of key-value pairs
7. Explain any two tuple functions in python
8. Write python program to check whether given number is odd or even
9. Explain any 3 string functions in Python.
10. In python which function is used to read a value from keyboard
11. a) list the data types in python
b) Explain the logical operator in Python
12. Write general form of for loop
13. Write python program to print first 10 numbers.
61
62