Sie sind auf Seite 1von 47

1/5/2020 SQL REVISION

Table:STUDENT

Reg no Rollno. name marks

Primary key Candidate key Alternate key (array attribute except primary key

TABLE:DETAILS
Roll no. Mark1 Mark2 Mark3 Average
1 5 5 5 5
2 1 2 3 2

Foreign key

Cardinality of student & details:4x2=8


Q1) command for using database:
Ans: use Database

Q2) create a table student with the given attributes roll number , name, gender
Ans: create table student (rollno.int, name char(20),gender char(3));

Q3) insert a value for table student


Ans: insert into student values (10, ”viji” ,”M”)

Q1.what are aggregate function in SQL?


Ans) Distinct: Makes a group function to consider only distinct values of the argument. All: Makes a group
function to consider all values including all duplicate
 Min function
 Max function
 Sum function
 Avg function
 Count function

4/5/2020 AGGREGRATE OR GROUP FUNCTIONS


It provides multiple row function which work on multiple values where we can apply select query on a group of
records rather than the entire table.Eg.avg,max,min,count,sum.
Q1)TABLE:employee
Ecode Name salary job city
E1 Ritu jain null Manager delhi
E2 Vikas verma 4500 executive jaipur
E3 Rajat Chaudry 6000 clerk kanpur
E4 Leena arora null manager Bangalore
E5 Shitha sharma 8000 accountant Kanpur

1)select count(salary) from employee ; 2)select count(*) from employee;


Ans:
Count(salary) Count (*)
5 5

3)select count(ecode) from employee; 4)select sum(salary),min(salary) from employee;

Sum(salary Min(salary)
)
18,500 4500

Count(ecode) CONSTRAINTS: condition or check applicable on a field or set of fields with the help of
5 create command constraints are used.
 Unique constraint
 Primary key constraint
 Default constraint
 Check constraint
 Foreign key constraint
 Not null constraint

Eg:
1. Unique constraint: create table student (roll no. int unique, name char (20), gender char (20));
2. Primary key constraint: create table employee (id int primary key, name char (20), branch char
(30),salary int);
3. Default constraint: create table groups (name char (20), albums int, gender char (10) DEFAULT ‘pop’);
4. Check constraint: create table shows (name char (30), ost int, views int CHECK (views >10000));
5. NOT NULL constraint: create table shop (ITEMS char (30), price int NOT NULL, quantity int);
6. Foreign key constraint: create table ITEMS (name char(20),price int, quantity int, due date, customer id
int, foreign key(models) REFERENCES product(models) on delete cascade on update cascade);
TABLE:store

Item no. Item Scode Quality rate Last buy


2005 Sharpener 23 60 8 31-june-10
classic
2003 Ball pen 22 50 25 01-feb-10
2002 Gel pen 21 150 12 24-feb-10
premium
2006 Gel pen classic 21 250 20 11-mar-09
2001 Eraser small 22 110 8 10-jan-09
2004 Eraser big 22 110 8 02-dec-09
2009
scode Ball pen 21 180 sname 18 03-nov-09
21 Premium stationary
23 Soft plastics
22 Tetra supply
TABLE:suppliers
a). To display details of all the items in store in ascending order of last buy
ANS: select * from store order by last buy asc;

b). To display itemno and item name of those items from store table whose rate is more than rupees 15
ans: select item no., item from store where (rate>15);

c). To display minimum rate of items for each supplier individually as per scode from table
Ans: select min(rate) from store, suppliers where (store. scode = suppliers. scode) group by sname;

d)select count (distinct scode) from store;


Count (distinct scode)
3

e) select rate*qty from store where itemno. = 2004;


Rate*qty
880

f)select max(lastbuy) from store;


Max(lastbuy)
24-feb-10

5/5/2020

ORDER BY CLAUSE:
EG: select name, city from student order by name;

GROUP BY CLAUSE:
Can be used in select statement to collect data across multiple records and group the results by one or
more columns.
EG: select name, count(*) as “number of employee” from student where (marks>350) group by city;

JOINTS:
It is a query that fetches data from two or more tables based on a condition
EG: select name, age from student details where name=”suga” and student.rollno.=detailsroll no.;
right joints and left joints

HAVING CLAUSE:
EG: select name ,age from idols group by album having fans>10,000;
7/5/2020 COMPUTER NETWORKS
It is a collection of inter connected autonomous computing devices to share information or resources.

ADVANTAGE OF NETWORKS:
 Sharing of resources(sharing among users programs or applications or data)
 Improved communication (enhanced communication: A computer network enables fast.reliable and
secured communication between users) EG: internet email
 Cost reduction(sharing resources also reduces communication cost)
 Reliability of data

TERMINOLOGIES OF NETWORK:
 Client(sends a request)
 Server(sharing of data, responses to client requests)
 Node (computer devices connected to networking group of nodes are called as workstations)
 NIC-network inferface card
 Acts as interpreter, helps communication between server and client
 MAC=media access control
 IP address: internet protocol address
 Always unique
 To procure IP address of: ”ipconfig” in command prompt(cmd).

 Domain name:[must be unique]:Eg: .com, .in, .edu, .org, etc


 Hub: destination unknown
 Switch: destination known Connectivity devices

 Router: a device which forwards data to the destinations of computer networks

(URL=uniform resource locator)


(SMTP=simple mail transfer protocol)
 Communication channels:wired communication channel: guided media, Eg. fibre optic cable etc
wireless communication channel: unguided media Eg. radio waves, satellites, etc
 Software
 Network services=DNS
 URL=uniform resource locator
TYPES OF NETWORKS:
 LAN(local area network) Eg:schools,office
 WAN(wide area network)Eg. Big geographical wide
 PAN(personal area network) Eg. Home network
 MAN (metropolitan arear network) Eg. City wide network

8/5/2020
TRANSMISSION MEDIA
 Guided /wired twisted pair, coaxial, fibre optic
 Unguided/wireless
TRANSMISSION MEDIA

GUIDED UNGUIDED

TWISTED PAIR MICROWAVE SATELLITE INFRARED


COAXIAL OPTICAL RADIO
FIBRE S
WAVES

Repeater: electronic device which re transmits the data


Mbps=megabytes per sec
mbps = mega bits per sec

coaxial used in cable-TV transmissions


 High bandwidth
 Long distance transmission
 Very thick and less flexible
 Not compatible like vtp rstp
optical fibre transmits light through glass
 Signals modulated and transmitted
 Most efficient and fast transmission
 Compatible for long distances
 Expensive
 Complicated installation
 High speed transmission
 High capacity data transmission

For 10 Mbps to 10 Gbps =Twisted pair cable


>100 Gbps=optical fibre cable
Twisted pair=cheapest cable

radio waves communication


 When frequency>3 GHz
 Large span of area covered
 Cheaper
 Unsecured mode of communication
 Depends on weather
microwave communication
 Data transmission wirelessly over long distance
 Cheaper[compared to cable transmission]
 Easy communicating
 Transmits 16 GBPs data[rate of transmission]
 Expensive installation[antenna, etc]
 Unsecured way of communication]
Infrared wave communication
 Allows transmission in short range
 300hz=400hz
 5m range
 Communication of devices with a short range
 Used in tv, cordless phones
 These rays don’t pass through any solid
 Rectilinear communication, only two devices can be used at a time
 Not compatible for long distances
 It is also used in monitoring and control applications
 No government license required
Satellite communication
 Covers very large geographical area for secured and high-quality transmission
 Requires many legal permissions
 Slower than microwave transmissions
 Very expensive
 Complicated installation
Bluetooth
 Upto 10m range
Wi-fi(wireless fidelity)
 Covers larger area

11/5/2020
1) Internet is a network of physical objects embedded with electronics, software, sensors, and network
connectivity.
2) Client is a host computer that request for some service from a server
3) PAN- personal area network
4) The three wired types of network are twisted pair cable, coaxial cables, fibre optic cable.
5) Network interface unit is a device attached to each of the workstations and a server helps the
workstation to establish are the important connections with the network
6) Bandwidth describes the maximum data transfer.

Rate of network or internet connection:

 BRIDGE: bridge is a device that connects two networks together only handles the network which follow
some protocols.
 PROTOCOL: rules or procedure to govern network communication
 ROUTER: same function as bridge, but it can handle the networks with different protocols. A router is a
network device that forwards data from one network to another.
 GATEWAY: network device which connects dissimilar networks.
BASIC NEWTWORK TOOLS:[COMMAND PROMPT]
 To find out IP address -Ipconfig command it is a networking troubleshooting command used to display
the basic networking information on a given computer
 Ping command-it is used to test the ability of the source computer to reach a specified destination
computer. it’s main purpose is to ensure that a network connection can be established. SYNTAX:
ping(domain name/ip address )
 Nslookup command (nameserver lookup): it displays the name and ipaddress of your computer’s default
DNS server.it is a network utility program used to obtain information about internet servers SYNTAX:
nslookup(IP address)
 Whois command: SYNTAX- whois google.com
the command used to get information on a specific domain name such as who registered it when was
it registered, etc
 Traceroute command(for linux) or trace rt command(for windows):SYNTAX: tracert google.com

12/5/2020

It is a utility to view the number of loops and response time to get to a remote system or website.it is a very
similar to ping except that identifies which network pathways it takes along each hop rather than the time it
takes for each packet to return

SPEED TEST: used to check the download and upload speed of network connection

CLOUD COMPUTING:
Cloud computing is internet based computing where shared resources software and information are
provided to computers
It is the technology of distributed data processing in which some scalable information resources and
capacities are provided as a service to multiple external customers

TYPES OF CLOUDS:
 Public cloud
 Private cloud
 Community cloud
 Hybrid cloud

PUBLIC CLOUD: used by multiple organisations service provided by common portal people using this
service are called as tenants. It is hosted and managed by third party service provides eg. Google drive,
icloud, etc…
PRIVATE CLOUD: these are the clouds for exclusive use by a single organisation and typically controlled
managed and hosted in private data centres eg. VPN
COMMUNITY CLOUD: these are the clouds used by a group of related organisations who wish to make use
of common cloud computing environment eg. Universities in a given region a community
HYBRID CLOUD: it is a combination of private cloud & public cloud
INTERNET OF THINGS: it is a technology that connects the things (the smart devices) to the internet over
wired/wireless connections
RFID: radio frequencies identification
Smart technology: automatic doors, temperature adjustment, stopping a vehicle
13/5/2020
Differences between PUBLIC & PRIVATE

PUBLIC PRIVATE
 Common cloud service made available to  Consists of computing resources used
Multiple subscribers exclusively owned by one business or
organisations
 Cloud resources are owned and operated by  Services and infrastructure are always
third party cloud service provider and maintained on a private network and the
delivered over the internet hardware and software are dedicated solely
to one organisation
 EG: Microsoft azure, google drive, amazon  Used by government agencies, financial
cloud institutions mid and large sized organisations

TYPES OF NETWORKS BY COMPONENT RULES


(i)peer to peer (P2P) networks
This network are often termed as non-dedicated servers. each computer can play the role of a client or a server
NOTE: A dedicated server operates solely as a server can shuttle between the client as well as server role
(ii) client server networks
This networks are otherwise called as master same network. A computer is reserved for server’s job of it does
not double up as a workstation and such a server is known as dedicated server

VARIOUS PROTOCOLS USED ON NETWORKS:


(i)HTTP(hypertext transfer protocol)
not secured
HTTPsecured
HTTP is an application level protocol used to access data on worldwide web

How HTTP works??


for web communication the request message (HTTP request) is sent to an HTTP server from URL’s by the HTTP
client
the HTTP server receives the HTTP request fetches the information as per the request and (open system
interconnection==browse) sends it to the HTTP client
the HTTP client (the browser) receives a response message interprets the message and displays the contents
of the message on the browser’s windows
[for mail networking=SMTP]
(ii)HTTPS
HTTP & SSL(combination)
It provides encrypted communication and secure identification of a network web server

14/5/2020
WORKING OF AN EMAIL
EMAIL client sending server get mx record of the domain from DNS server
SMTP
Recipient inbox receiving server
It is a mechanism of data transfer over internet to provide a safe passage for the transmission of data
It intercepts the data so that third party cannot view the data being transmitted.

FTP-file transfer protocol


It is a standard for the exchange of files across the internet

POP-post office protocol


Pop.3=version three
Helps to download data from mails etc
It is a standard mail protocol it defines rules about receiving emails from a remote server is a local email client
It makes possible for the users to download their received e-mail messages in their local computers even if it is
offline

By default pop.3 protocol works on two ports


port110-the default pop3 non encrypted port used for unsecured email communication
port995-encrypted port

IMAP-internet message access protocol


It is another mail protocol used in conjunction with pop3 protocol for accessing emails on a remote webserver
and downloads them to a local client [multiple applications, clients and different locations]
By default the IMAP protocol works on two ports
port143=non encrypted port
port993=encrypted port

1)each IP packet must contain source destination address


2)DNS- domain name system
3)repeater handles different protocols -false
4)a document that uses HTTP is called a webpage-true

15/5/2020
SMTP-simple mail transfer protocol
It is used for sending emails across the internet by default the SMTP protocol works on these ports.
port25-the default SMTP non-encrypted port
port 465-encrypted port

VOIP-voice over internet protocol


This protocol enables voice communication over the internet through the compression of voice into data
packets can be efficiently transmitted over data networks and then converted back into voice at the other end.

NFC-near field communications


It is used to provide short range wireless connectivity between two electronic devices which is in the distance of
4 to 5 cm

SCP-session control protocol


SSH-secure shell protocol
REMOTE LOGIN:
It is a network application that permits a user sitting at a different location to work on a specific program on
another computer. Eg.TELENEt

ERROR CHECKING(ERROR DEDUCTION)


While transmitting data over networks some errors may occur hence data may get corrupted. the errors can be
of the following types:
1) Single bit error-error just in one bit
2) Multiple bit error-error in 2 or more non consecutive bits
3) Burst error

1)if only one bit of the transmitted data gets changed from 1 to 0 or 0 to1
2)if 2 or more non-consecutive bits when data gets changed
3)if two or more consecutive bits in data get changed from 0 to 1 or 1 to 0

Some of the common error checking methods in networks:


1) Single-dimensional parity checking
2) Two dimensional parity checking
3) Check sum
[parity-addition of an extra bit (0 to1) to data]

SINGLE DIMENSIONAL PARITY CHECKING:


10110111 the no. of 1’s=6(even no.)
11001011 the no. of 1’s=5(odd no.)
Adda an extra bit (either 0 (or) 1)
parity bit to actual data so that number of 1’s along with extra bit become even or remains even
For odd no. of 1’s add 1 as the parity bit
For even no. of 1’s add 0 as the parity bit
1 0 1 1 0 1 1 1 0
1 1 0 0 1 0 1 1 1

Advantages of single dimensional parity checking:


It is s simple mechanism which is easy to implement it is an inexpensive technique for detecting the errors in
data transmission

Disadvatages of single dimensional parity checking:


It can detect only single bit errors which occur rarely

TWO DIMENSIONAL
It is an enhanced.it works with multiple data

Ex:find rows & column parity 0 row parity


1 1 0 1 0 0 0 1 1 1 0 0 1 0 0 1
1
0

1
0 0 1 0 0 0 0 0 1
0 0 1 1 1 1 0 0 0

1 0 0 1 0 0 0 1 1

ADVANTAGES OF TWO DIMENSIONAL PARITY CHECKING:


It is more efficient than single-dimensional parity checking.it can deduct multiple bit errors also.

DISADVANTAGES OF TWO-DIMENSIONAL PARITY CHECKING:


This technique cannot detect four or more bit errors

CHECKSUM:
Checksum refers to a sum of data bits calculated from digital data i.e used to ensure the data integrity at the
receiver’s end.

EG:k=4
Data segments with m=8 bits

Transmitted data: Data unit: 1) 1 0 1 1 0 0 1 1


Data unit: 2) 1 0 1 0 1 0 1 1
Data unit: 3) 0 1 0 1 1 0 1 0
Data unit: 4) 1 1 0 1 0 1 0 1
Data unit: 1) 1 0 1 1 0 0 1 1
Data unit: 2) 1 0 1 0 1 0 1 1
10 1 0 1 1 1 1 0
1

Complement the sum to get checksum=0 1 1 1 0 0 0 0

19/5/2020

1)consider following data units that are to be transmitted along with checksum information

1000 0110 0101 1110


1010 1100 0110 0000
0111 0001 0010 1010
1000 0001 1011 0101 In what form will the data be transmitted?
CHECKSUM VALUE=1101 1010 0110 0000

CHECKSUM-checksum is an error deduction technique used for checking errors in the received data .in this
technique at the transmitter’s end as the device transmits data it takes the sum of all the data elements it is
transmitting to create an aggregate sum this sum is called as data sum
The overflow carries generated by the additions or added back into the data sum the transmitting device then
sends a form of this datasum appended to the end of the block this new form of the data sum is called the
checksum.
At the receiver end as the data elements are received they are added a second time in order to recreate the
datasum once all of the data elements have been received the receiving device compares its calculated datasum
with the checksum sent by the transmitting device
If both these data match the data is considered error free and accepted otherwise rejected

21/5/2020 SOCIETY LAW & ETHICS

What is plagiarism, cybercrime, computer forensic, online fraud? cyber law?


PLAGIARISM: plagiarism is stealing someone else’s intellectual work key representing it as your own work
without giving credits to the man source of work.

CYBERCRIME: cybercrime is any criminal offense that is facilitated by or involves the use of electronic
communication or information systems including electronic devices
COMPUTER FORENSIC: digital or computer forensic refers to the methods used for interpretation of computer
media for digital evidence.
ONLINE FRAUD: fraud commited using the internet is called as online fraud. few examples are non-delivered
goods, stealing information, non-existent companies, etc
CYBERLAW: cyberlaw is a generic term which refers to all the legal and regulatory aspectives of internet and the
worldwide web.

3/6/2020
IP address
Internet protocol version(IPV)
(i)IPV4
(ii)IPV6

(i)IPV4 addresses are 32 bits long and it is the most widely internet protocols used to contact devices to the
internet
(ii)IPV6 addresses are 128 bits

IPV4:
69 89 31 226
01000101 01011001 00011111 11100010
1st octet 2nd octet 3rd octet 4th octet

IPV6:
0021 : 0001 : AC10 :030A :0000 :0000 :0000:9878

ADDRESS SIZE:
IPV4:32-bits
IPV6:128-bits
ADDRESS FORMAT:
IPV4:4 segments, dotted decimal notation
IPV6:8 segments, hexadecimal notation
NUMBER OF ADDRESSES:
IPV4:232
IPV6:2128

ROUTING: it is a process of efficiently selecting a path in the network along with data packets will travel to their
destination
A router maintains a table called routing table that stores routing table that stores routing information based on
which the router determines the best path to a network. Routers are not concerned with host they only deal
with networks and the best path to reach them

NOTE:
ICP is a connection-oriented protocol
IP is a connectionless protocol responsible for providing addresses of each computer & performing routing
UDP (user datagram protocol) it is a connection less protocol

3/6/2020 INTERFACE PYTHON WITH MYSQL


STEP1: start python
STEP2: import mysql.connector
STEP3: the connect() function establishes connection to a mysql database it requires four parameters:
 User
 Password
 Host-name
 Database
SYNTAX: mysql.connector.connect(host=<hostname>,user=<username>,passwd=<password>)

Example: import mysql.connector as sqltor


Mycon=sqltor.connect(host=”localhost”,user=”root”,passwd=”mypass”,database=”test”)
STEP4 : create a cursor instance
SYNTAX:<cursorobject>=<connection object>.cursor()
Database cursor is a specific control structure that facilitates the row by row processing of records in the
result set i.e the set of records retrived as per query
STEP5 : you can execute SQL query using execute()
SYNTAX:<cursorobject>.execute<sqlquery string>
STEP6 : extract data from resultset
1) <data>=<cursor>.fetchall()
2) <data>=<cursor>.fetchone()
3) <data>=<cursor>.fetchmany(<n>)
4) <variable>=<cursor>.rowcount

Fetchall()
Eg.data= cursor.fetchall()
Count=cursor.rowcount
Print(“total no. of rows retrived in resultset:”,count)
For row in data:
Print(row)

Fetchmany(_
Eg. data=cursor.fetchmany(4)
Count=cursor.rowcount
Print(“total no. of rows retrived from resultset:”,count)
For row in data:
Print(row)

Fetchone()
data=cursor.fetchone()
count=cursor.rowcount
print(“total no.of rows retrived from resultset:”,count)
print(data)
print(“\n again fetching one record”)
data=cursor.fetchone()
count=cursor.rowcount
print(“total no. of rows retrived from resultset:”,count)
print(data)

5/6/2020

Creating a table
Import mysql.connector
Mydb=mysql.connector.connect(host=”localhost”,user=”learner”,passwd=”past”,database=”test”)
Mycursor=mydb.cursor()
Mycursor.execute(“create table cust(name varchar(25),address varchar(35)”)
Mydb.commit()

Inserting values into the table


Import mysql.connector
Mydb=mysql.connector.connect(host=”myhost”,password=”passwd”,database=’test”,user=”harihr”)
Mycursor=mydb.cursor()
Sql=”insert into cust(name.address)
Values(%5,%5)”
Val=(“raj”,”Chennai”)
Mycursor.execute(sql,val)
Mydb.commit()
Print(mycursor.rowcount,”record inserted”)

Usage of select statement


Import mysql.connector
Mydb=mysql.connector.connect(host,passwd,database,user)
Mycursor=mydb.cursor()
Mycursor.execute(select * from cust)
Result=mycursor.fetchall()
For x in result:
Print(x)

Sql=”select * from cust where address=”Chennai”


Sql=”select * from cust order by name”

Usage of update command


Import mysgl.connector.connect(“host,password,database,user)
Mycursor=mydb.cursor(_
Sql=”update cust set address=’chennai21’ where address=’chennai’”
Mycursor.execute(sql)
Mydb.commit()
Print(mycursor.rowcount,”records updated”)

6/6/2020

1)to create a new database “school” in mysql through by them:


Import mysql.connector
Mydb=mysql.connector.connect(host=”localhost”,user=”learner”,passwd=”fast”)
Mycursor=mydb.cursor()
Mycursor.execute(“create database school”)

2)to check weather the database has been created or not using python interface
[in sql=show<databse>]
Import mysql.connector
Mydb=mysql.connector.connect(host=”localhost”,user’”learner”,passwd=”fast”)
Mycursor=mydb.cursor()
Mycursor.execute(“show school”)
For a in mycursor:
Print(a)

3)roll no.,name,age,city,marks:
Import mysql.connector
Mydb=mysql.connector.connect(host=”local host”,user=”learner”,passwd=”fast”,database=”school”)
Mycursor=mydb.cursor()
Mycursor.execute(“create tabe school(roll no int,name char(30),age int,city char(10),marks int)
Mydb.commit()

4)insert values into table


Import mysql.connector
Mydb=mysql.connector.connect(host=”localhost”,user=”learner”,passwd=”fast”,databse’”school”)
Mycursor=mydb.cursor()
1)st=[“insert into student(roll no.,name,age,city,marks)
Values(23,’mumbai’,398)
Mycursor.execute(st)
Mydb.commit()
Print(mycursor.rowcount,”record inserted”)
2)”insert into student (roll no,name,age,city marks)
Values(2,’pooja’,’21,’chail’,390)
3)(3,’radhika’,21,’shimala’,388)
4)(4,’sonia’,24,’goa’,300)
5)(5,’vinay’,25,’pune’,410)
6)(10,’shyamla’,15,’delhi’,345)

5)To display all the records of the student table using python

Import mysql.connector
Mydb=mysql.connector.connection(host’”localhost”,user=”learner”,passwd=”slow”,database=”school”)
Mycursor=mydb.cursor()
Count=cursor.rowcount()
Print(“total number of rows retrived in result”,count)
For row in data:
Print(row)

6)for table student


If the option =1 create table
Option=2add records
Option=3update record
Option=4delete the record
Option=5display the records
Option=6exit

ANS: import mysql.connector


print("welcome")
print("1.CREATE TABLE")
print("2.ADD RECORDS")
print("3.UPDATE RECORD")
print("4.DELETE THE RECORD")
print("5.DISPLAY")
print("6.EXIT")
print("choose your option")
x=int(input("enter your choice(1-6):"))
if x==1:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
mycursor.execute("create table student(name,char(35)roll no. int,age int,marks int")
mydb.commit()

elif x==2:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
st=("Insert into student(name,roll no,age,marks) values(%s,%s,%s,%s)")
val=[("rita",1,13,20)
("kim",2,14,20)
("nanjoon",3,16,20)
("techung",4,17,21)]
mycursor.execute(st,val)
mydb.commit()
print(mycursor.rowcount,"records inserted")

elif x==3:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
sql="update student set name="I-hope" where roll no=1"
mycursor.execute()
mydb.commit()
print(mycursor.rowcount,"record inserted")
elif x==4:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
n="delete from student where name="kim""
mycursor.execute(n)
mydb.commit()
print(mycursor.rowcount,"record deleted")

elif x==5:
import mysql.connector
mydb.connector
mydb=mysql.connector.connection(host="local host",user="learner",passwd="slow",database="test")
mycursor=mydb.cursor()
mycursor.execute("select * from student")
myresult=mycursor.fetchall()
for x in myresult:
print(x)
elif x==6:
break

9/6/2020
1)which method is used to retrive all rows and which method is used to retrieve single row?
Ans: fetchall()method = all rows
Fetchone() method = single row

2)what is the name of a special control structure that facilitates the row by row processing of records in the
result set during python mysql connectivity
Ans: database cursor

10/6/2020
1)which command is used for cleaning up the environment?
Close()

2)a resultset is an object that is returned when a cursor object is used to carry a form of query a table
True

3)which command is used for counting the no. of rows in database?


Rowcount()

11/6/2020 RECURSION
RECURSION
Recursion is a technique for solving a large computational problem by repeatedly applying the same procedures
to reduce it to successively smaller problems.
 
NOTE
In iteration the code is executed repeatedly, using the same memory space that is the memory space allocated
once is used for each pass of the loop
In recursion since it involves function call in each step fresh memory is allocated for each recursive call hence
the recursive function runs slower than iteration

Advantage of using recursion


Recursion makes the code short and simple while iteration makes the code longer comparatively
 
Program:
#function to find the factorial of a number using recursion
def recur_factorial(n):
if n==1:
return n
else:
return n*recur_factorial(n-1)
 
num = int(input("enter a number:"))
 
if num<0:
print("sorry,factorial for a negative number does not exist")
elif num==0:
print("the factorial of 0 is 1")
else:
print("the factorial of",num,"is",recur_factorial(num))
 
5*recur_factorial(5-1)
4*recur_factoria(4-1)
3*recur_factoria(3-1)
2*recur_factoria(2-1)
2*1=2
3*2=6
4*6=24
5*24=120
 
 
 
Project 2:
 
#function to display fibonacci series using recursion
 
def recur_fibo(n):
if n<=1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
 
nterms=int(input("how many terms required in the series:"))
print("fibonacci sequence generated is:")
 
for i in range(nterms):
print(recur_fibo(i))+
 
12/6/2020
WRITING A RECURSIVE FUNCTION:
Every recursive function must have two cases;
i)The recursive case(inductive case)
ii)The base case(stopping case),always required.
The base case is a small problem that we know how to solve and is a case causes recursion to end
The recursive case is a general one where it calls the same function recursively
The base case is the keys whose solution is pre known and it is used without computation

13/6/2020
1)write a python function to sum all the numbers in a list
Sample list=[4,6,3,5,6]
sum=0
if i in range(len(samplelist)):
sum=sum+samplelist[i]
print(sum)

def sum(sl):
total=0
for in sl:
total=total+i
return(total)
print(total)

16/6/2020
Ex 6.1
10 12 14 21 23 28 31 37 42 44 49 53
0 1 2 3 4 5 6 7 8 9 10 11

(i)search for element 44

STEP1: beg=0; last=11


Mid=INT(0+11)/2
=INT(5.5) 5

STEP2:DATA[mid] i.e DATA[5] is 28


28<44 beg=mid+1 i.e beg=5+16
STEP3:beg=6,last=11
Mid=INT(6+11)/28
Data[8]=42
42<44 then beg=8+1=9
STEP4:mid=INT(9+11)/210
Data[10]=49
Iteration 1 49>44 beg=10-19
STEP5:mid=INT(9+9)/29
Beg=last=9
Data[9]=44
SEARCH SUCCESSFUL at location number 10

1)write a recursive function to implement binary search algorithm


Ans: def binsearch(ar,key,low,high):
if low>high:
return-999
mid=int((low+high)/2)
if key==ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
return binsearch(ar,key,low,high)
else:
low=mid+1
return binsearch(ar,key,low,high)

ary=[12,15,21,28,32,33,36,43,45]
item=int(input("enter search item:"))
res=binsearch(ary,item,0,len(ary)-1)
if res>=0:
print(item,"found at index",res)
else:
print("sorrry",item,"not found in the array")

Ex: Binary searching in an array (a sorted list)

Ans:def binsearch(ar,key):
low=0
high=len(ar)-1
while low<=high:
mid=int((low+high)/2)
if key == ar[mid]:
return mid
elif key<ar[mid]:
high=mid-1
else:
low=mid+1
else:
return-999

ar=[12,15,21,25,28,32,33,36,43,45]
item=int(input("enter search item:"))
res=binsearch(ar,item)
if res>=0:
print(item,"found at index:",res)
else:
print("sorry",item,"not found in array")

19/6/2020 DATA VISUALISATION USING PYTHON

Data visualisation refers to the graphical or visual representation of information and data using visual elements
like charts, graphs and maps etc.. data visualisation is immensely useful in decision making

USING PYPLOT OF MATPLOTLIB LIBRARY


Matplotlib library offers many different collection of methods.pyplot is a collection of methods within matplotlib
which allow user to construct 2D plot easily and interactively. Pyplot usually essentially produces plotting
functions and behaviour or MATLIB

Impoting pyplot:
Import matplotlib.pyplot
Import matplotlib.pyplot as pl

WORKING WITH PYPLOT METHODS:


The pyplot interface provides many methods for 2D plotting of data. The matplotlib’s pyplot interface lets one
plot data in multiple ways such as line chart, pie chart, scatter chart, etc.
Numpy library: for useful functions to create arrays of data
Using numpy arrar:
Import numpy as np

Numpy array is simply a grid that contains values of same homogeneous type

Ex: import numpy as np


List=[1,2,3,4]
a1.=np.array(list)
Print (a1)

22/6/2020
Creating arrays with numerical range using arrang()
<arrayname>=numpy.arrange([start,]stop[,step][,dtype])
Eg: arr6=np.arrange(1,7,2,np.float)
Arr6
Array([1,3,5],dtype=float 32)

Creating arrays with numerical range using limspace()


<arrayname>=numpy.limspace[<start>,<stop>,<number of values to be generated>]

Eg: al=np.limspace(2.5,5,6)
Al
Array([2.5,3,3.5,4,4.5,5])

Basics of commonly used chart types:


 Line chart
 bar chart
 pie chart

line chart using plot() function


eg. import matplotlib.pyplot as plt
import numpy as np
x=np.arrange(0,10,0.1)
a=np.cos(x)
b=np.sin(a)
plt.plot(x,a,'b')
plt.plot(x,b,’x’)
plt.show() the chart will be shown visually

23/6/2020
Linewidth=<width>
Eg.plt.plot(x,a,linewidth=2)
Linestyle(or)ls=[‘solid’]’dashed’,’dashdot’,’dotted’]
Eg.plt.plot(x,a,linewidh=2,linestyle=’dashed’)

Changing marker tytpe, size and colour


Marker=<valid marker type>,markersize=<inpoints>,markededgecolor=<valid color>
Eg.
Plt.plot(p,q)’k’,marker=’d’,markersize=5,markeredgecolor=’red’)

Plot()method syntax:
Plot(<data>[,<data 2>] [,….<colorcode and markertype>] [,<linewidth>] [,<linestyle>] [,<marker>] [,<markersize>]
[,<markeredgecolor>]

#linechart
import matplotlib.pyplot as plt
x1=[10,20,30]
y2=[20,40,10]
x2=[10,20,30]
y2=[40,10,30]
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.title('two or more lines with different widths and colors with suitable legends')
plt.plot(x,y,color='blue',linewidth=3,label='line1-width-3')
plt.plot(x2,y2,color=”red”,linewidth=5,label=’line2-width-5’)
plt.legend()
plt.show()

#multiple line with multiple colors given expliently


import matplotlib.pyplot as plt
import numpy as np
y=np.arrange(1,3)
plt.plot(y,'y')
plt.plot(y+1,'m')
plt.plot(y+2,'c')
plt.show()

24/6/2020
Bar chart
A bar graph is a graphical display of data using bars of different height

Bar chart is created by bar() function


Ex: matplotlib.pyplot.bar(a,b)

Ex: a, b, c=[1,2,3,4],[2,4,6,8],[1,4,9,16]
Plt.bar(a,b)
Plt.bar(a,c)
For axes label
Matplotlib.pyplot.xlabel(<label string>)
Matplotlib.pyplot.ylabel(<label string>)

Ex:
import matplotlib pyplot as plt
cities=['delhi','mumbai','bangalore','hyderabad']
population=[23456123,20083104,18456123,13411093]
plt.bar(cities,population)
plt.xlabel('cities')
plt.ylabel('population')
plt.show()

To change width of the bar:


<matplotlib.pyplot>.bar(<x-sequence>,<y-sequence>,width=<float value>)/width=<width value sequence>)
Eg.plt.bar(cities, population, width=[0.5,6,7,8])

ex:
1) the python library providing interface and functionality for 2D graphics is matplotlib
2) line charts are creatd by using plot() function
3) pyplot is a collection of methods.

25/6/2020
CREATING A HORIZONTAL BAR CHART:
Horizontal bar chart is created by barh() function
Eg:
import matplotlib pyplot as plt
cities=['delhi','mumbai','bangalore','hyderabad']
population=[23456123,20083104,18456123,13411093]
plt.barh(cities,population)
plt.xlabel('population')
plt.ylabel('cities')
plt.show()

PIE CHART
The pie() function plots a single data only. It will calculate the share of individual elements of the data range
being plotted vs the whole of the data range. The default shape of a pie chart is oval but you can always change
to circle by using axis() of plot, sending ”equal” as argument to it. That is, issue following command before you
use pie() function : matplotlib.pyplot.axis(“equal”)
Ex:
Import matplotlib.pyplot as plt
Contri=[17,8.8,12.75,14]
Plt.pie(contri)
#Ex 1
import matplotlib.pyplot as plt
stream= ['medical','non-medical','commerce with maths','commerce with IP','humanities']
students=[32,41,55,60,50]
colors=['red','gold','yellowgreen','blue','lightcoral']
explode=(0.1,0,0,0,0)
plt.pie(students,explode=explode,labels=stream,colors=colors)
plt.title("grouping of students on the basis of allocated streams")
plt.show()

#Ex 2
import matplotlib.pyplot as plt
labels= 'python','c++','ruby','java'
sizes=[215,130,245,210]
colors=['gold','yellowgreen','lightcoral','light skyblue']
explode=(0.1,0,0,0,0)
plt.pie(sizes,explode=explode,labels=labels,colors=colors,shadow=True,startangle=140)
plt.axis("equal")
plt.show()

Anatomy of a chart
Anatomy generally refers to the study of bodily structure or various parts of a plot that you can create using
pyplot.

26/6/2020

1)write a python program to plot the algebraic equation 10x+14 range 12 to 20


import matplotlib.pyplot as plt
import numpy as np
x=np.arrange(12,20)
plt.plot(10*x+14,color="purple",linewidth=5,linestyle='dashdot')
plt.title("graph plotting")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.show()

2)By default legends are shown in right upper corner part of the plot.

3)To display the plot show() function is used.

4)barh() function is used to create horizontal bar chart

5)Line charts are created by using plot() function

6)You can save the figure by using pyplot savfig in which format
 saved in .pdf, .png, .eps

29/6/2020
1)Consider the following zone-width sales in crores and draw a pie chart by using pyplt interface and display
labels
Sales=[234,345,547,287,198]
Zones=[“EAST”,”WEST”,”NORTH”,”SOUTH”,”CENTRAL”]

import matplotlib.pyplot as plt


zones=[“EAST”,”WEST”,”NORTH”,”SOUTH”,”CENTRAL”]
sales=[234,345,547,287,198]
c=['red','yellow','orange','purple','blue']
plt.pie(sales,labels=zones,color=c)
plt.title("zone-wide sales in crores")
plt.show()

2)Write a program to plot a bar chart in python to display the result of a school for five consecutive years
YEARS=[2015,2016,2017,2018,2019]
List of pass percentage(p)=[98.50,70.25,55.20,90.5,61.50]

import matplotlib.pyplot as plt


years=[2015,2016,2017,2018,2019]
p=[98.50,70.25,55.20,90.5,61.50]
plt.bar(years,p,width=0.2,color=["red","blue","purple","pink","yellow"])
plt.xlabel("years")
plt.ylabel("pass percentage")
plt.title("pass percentage of the school for the past five consecutiv years")
plt.show()

30/6/2020 DATA STRUCTURE


A Data structure is a named group of data of different data types which is stored in a specific way and
can be processed as a single unit a data structure has well defined operations, behaviour and
properties

DATA STRUCTURE
1) simple data structures:
(i)array or linear lists
2) compound data structure:
(i) linear data structures:
(a) stack, (b)queue, (c)linked list
(ii)non linear data structure:
(a) tree

stacks: stack data structure refers to the lists stored and accessed in a special way, where LIFO (last in first out)
technique is followed in stack, insertions and deletions take place only at one end, called the top.
QUEUES: queues data structures are FIFO(first in first out) lists, where insertions take place at the ‘rear’ end of
the queues and deletions take place at the ‘front’ end of the queues.
Ex: stack: 4 50 NO
TOP 3 40 INSERTION
2 30 TOP++ VALID IF IT IS
1 20 TRUE
0 10

ONLY 50 CAN BE RESTORED HENCE IT FOLLOWS LIFO WHEN 50 IS REMOVED 40 BECOMES TOP
Ex: Queue

0 20 30
FRONT REAR

(DELETION) (INSERTION)

FRONT

1/7/2020

Insertion = push operation


Deletion = pop operation
OPERATION IN STACKS:
 data can only be removed from the top (pop) i.e the element at the top of the stack. The removal of
element from a stack is technically called POP operation
 A new data element can only be added to the top of the stack (push). The insertion of element in a stack
is technically called PUSH operation
18, element at the
top is popped
top=none (b)push ‘32’ (c) push
‘18’ (d) 18 pop 1 element
TOP
32 (a)stack empty
32 32
29, element popped

29 TOP
32 32 TOP
(e)push ‘29’ (f)pop 1 element

OTHER STACK TERMS:


1)Peek= Refers to inspecting the values at the stack’s top without removing it. It is also sometimes referred
as inspection.
2)Overflow= Refers to situation (ERROR) when one tries to push an item in stack that is full. This situation
occurs when the size of the stack is fixed and cannot grow further or there is no memory left to
accommodate new item.
3)Underflow= Refers to the situation (ERROR) when one tries to pop/delete an item from an empty stack.
That is stack currently having no item and still one tries to pop an item.

2/7/2020
PROGRAM: python program to implement stack operations
def isEmpty(stk):
if stk==[ ]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isEmpty(stk):
return "Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top =len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return "Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack Empty")
else:
top=len(stk)-1
print(stk[top],"<==top")
for a in range(top-1,-1,-1):
print(stk[a])

Stack= [ ]
top=None

while True:
print("The Stack Operations are:")
print("1.Push")
print("2.Pop")
print("3.Peek")
print("4.Display")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
Push(Stack,item)
elif ch==2:
item=Pop(Stack)
if item=="Underflow":
print("Underflow!EmptyStack")
else:
print("Popped item is",item)
elif ch==3:
item=Peek(Stack)
if item=="Underflow":
print("Underflow!EmptyStack")
else:
print("Topmost item is",item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid choice")

3/7/2020
STACK APPLICATION
1)Reversing a line
2)Polished string
Expressions in Infix, Prefix, Postfix notations:
a) Infix= A+B
Prefix= +AB
Postfix= AB+
b) Infix= (A-C) X B
Prefix= X – ACB
Postfix= AC – BX
Eg: Convert A+(BXC) to postfix  postfix= ABCX+
Eg: Convert (A + B) / (C - D) to postfix
(AB+) / (CD-)
AB+CD-/

Eg: Convert (A + (B X C)) / (C – (D X B))


(A + (BC X)) / (C – (DB X))
ABC X+ CDB X-/

(BODMAS RULE)

Brackets ()
Of exp
DECREASES
Division ÷ or /
Multiplication X
Addition +
Subtraction -

WHEN INCREASES THE PRIORITY DECREASES STAYS VICE VERSA

EG:
((A + B) X C / D + E ^ F) / G to Postfix (* = X)
((AB +) X C / D + (EF) ^) / G
((AB +) X C / D + (EF^)) / G
((AB+C) X / D + (EF^)) / G
((AB + C X D /) + (EF ^) / G
(AB + C X D / EF ^ + G /
AB + C X D / EF ^ + G /

4/7/2020
EG:
A + (B X C – (D / E ^ F) X G) X H to postfix (* = X)
(A + (B X C - (D / E ^ F) X G X H)
(A + (BC X – (DE / ^ F) X G X H)
(ABC X + - (DEF ^ /) X G X H)

SYMBOL SCANNED STACK EXPRESSION


( (
A ( A
+ (+ A
( (+( A
B (+( AB
* (+(* AB
C (+(* ABC
- (+(- ABC*
( (+(-( ABC*
D (+(-( ABC*D
/ (+(-(/ ABC*D
E (+(-(/ ABC*DE
^ (+(-(/^ ABC*DE
F (+(-(/^ ABC*DEF
) (+(- ABC*DEF/
* (+(-* ABC*DEF^/
G (+(-* ABC*DEF^/G
) (+ ABC*DEF^/G*-
* (+* ABC*DEF^/G*-
H (+* ABC*DEF^/G*-H
) ABC*DEF^/G*-H*+

NOTE:
1)When highest priority operator enters the stack the already existing lowest priority operator stays in the stack.

2)When the lowest priority operator enters the stack the already existing highest priority operator comes out of
the stack going to the expression.

3)When a close bracket occurs, LIFO is followed the first out operator goes to the expression.

4)If some priority operator enters the existing some priority operator it goes to the expression.

7/7/2020
1)(A * (B + (C + D) * (E + F) / G * H)
SYMBOL SCANNED STACK EXPRESSION
( (
A ( A
* (* A
( (*( A
B (*( AB
+ (*(+ AB
( (*(+( AB
C (*(+( ABC
+ (*(+(+ ABC
D (*(+(+ ABCD
) (*(+( ABCD+
* (*(+(* ABCD+
( (*(+(*( ABCD+
E (*(+(*( ABCD+E
+ (*(+( ABCD+E
F (*(+*(+ ABCD+EF
) (*(+* ABCD+EF+*
/ (*(+/ ABCD+EF+*
G (*(+/ ABCD+EF+*G
) (* ABCD+EF+*G/+
* (* ABCD+EF+*G/+*
H (* ABCD+EF+*G/+*H
) (* ABCD+EF+*G/+*H*

1)Evaluate the postfix expression AB + C * D /


If A =2 ,B =3,C =4,D =5
2 3 + 4 * 5 /

+ * /
3 3 = 4 ˭ 5 5
2 2 2 5 5 20 20 20 4
The priority order of NOT and OR
10/7/2020
QUEUES:

Operations performed in Queues:


1)Data can only be removed from the front end i.e the element at the front end of the queue. The removal of
element from a queue is technically called DEQUEUE operation.
2)A new data element can only be added to the rear of the queue. The insertion of element in a stack is
technically called ENQUEUE operation.

Other Queue Terms:


1)Peek – Refers to the inspection of queue’s front without removing it. Also known as inspection.
2)Overflow – Situation which occurs when one tries to enqueue an item in a queue that is full. This occurs when
the size of the queue is fixed and cannot grow further or there is no memory left to accommodate new item.
3)Underflow – Situation which occurs when one tries to dequeue an item from an empty queue.

Capacity=4
Ex) (i) queue empty (ii) enqueue ‘a’ (iii) enqueue ‘b’ (iv) enqueue ‘c’ (v)dequeue (vi)enqueue ‘d’
(vii) enqueue ‘e’ (viii)dequeue (ix)dequeue (x)dequeue (xi)dequeue

0 1 2 3
(i)
(ii) a
(iii) a b
(iv) a b c
(v) b c
(vi) b c d
(vii) b c d(OVERFLOW)
(viii) c d
(ix) d
(x)
(xi) UNDERFLOW

11/7/2020
PROGRAM TO IMPLEMENT QUEUE OPERATIONS:
def cls():
print("\n"*100)
def isEmpty(qu):
if qu==[ ]:
return True
else:
return False
def Enqueue(qu,item):
qu.append(item)
if len(qu)==1:
front=rear=0
else:
rear=len(qu)-1

def Dequeue(qu):
if isEmpty(qu):
return "Underflow"
else:
item=qu.pop(0)
if len(qu)==0:
front=rear=None
return item
def Peek(qu):
if isEmpty(qu):
return "Underflow"
else:
front=0
return qu[front]
def Display(qu):
if isEmpty(qu):
print("Queue Empty")
elif len(qu)==1:
print(qu[0],'<==front rear')
else:
front=0
rear=len(qu)-1
print(qu[front],"<==front")
for a in range(1,rear):
print(qu[a])
print(qu[rear],"<==rear")

queue= [ ]
front=None

while True:
print("The Queue Operations are:")
print("1.Enqueue")
print("2.Qequeue")
print("3.Peek")
print("4.Display")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
Enqueue(queue,item)
input("press ENTER to continue")
elif ch==2:
item=Dequeue(queue)
if item=="Underflow":
print("Underflow!EmptyQueue")
else:
print("Dequeue-ed item is",item)
input("press ENTER to continue")
elif ch==3:
item=Peek(queue)
if item=="Underflow":
print("Queue is Empty")
else:
print("Frontmost item is",item)
elif ch==4:
Display(queue)
input("press ENTER to continue")
elif ch==5:
break
else:
print("Invalid choice")
input("press ENTER to continue")

13/7/2020
Types of queues:
1)Circular queues:
Circular queues are the queues implemented in circular form rather than a straight line.

2)Deque (Double-ended queue):


These are refined queues in which elements can be added or removed at either end but not in the middle. There
are two variations of a deque:
1)an input restricted deque: insertion=one end ; deletion=both end
2)an output restricted deque: insertion=both end; deletion=one end

APPLICATIONS OF STACK:
1)Reverse of a sequence
2)Infix to postfix conversion

APPLICATIONS OF QUEUE:
1)Resource sharing

OPERATIONS OF DATA STRUCTURES:


1)Insertion
2)Deletion
3)Searching
4)Traversal
5)Sorting
6)Merging
15/7/2020
Eg: implementation of list as stack:
s=[ ]

while True:
print("1.Push")
print("2.Pop")
print("3.Dispaly")
ch= int(input("Enter your choice(1-3):"))
if (ch==1):
a=input("Enter any number:")
s.append(a)
elif (ch==2):
if (s== [ ]):
print("Stack Empty")
else:
print("Deleted element is:",s.pop())
elif (ch==3):
l=len(s)
for i in range(l-1,-1,-1):
print(s[i])
print(s.reverse())
else:
print("Invalid Choice")
input("press Enter to continue")

16/7/2020
Eg: Implementing list as a queue
a=[ ]

while True:
print("1.Insert")
print("2.Delete")
print("3.Dispaly")
ch= int(input("Enter your choice(1-3):"))
if (ch==1):
b=input("Enter any number:")
sa.append(b)
elif (ch==2):
if (a== [ ]):
print("Queue is Empty")
else:
print("Deleted element is:",a.pop())
elif (ch==3):
l=len(a)
for i in range(0,1):
print(a[i])
else:
print("Invalid Choice")
input("press Enter to continue")
1)Two functions where for Fahrenheit and Celsius:
celsius=(x-32)*(5/9)
fahreheit=(y*(9/5))+32

def celsius():
x=int(input("Enter the value to convert into celsius:"))
c=(x-32)*(5/9)
print("fahrenheit==>celisius=",c)

def fahrenheit():
y=int(input("Enter the value to convert into fahrenheit:"))
f=(y*(9/5))+32
print("celsius==>fahrenheit=",f)

print("The operations are:")


print("1.fahrenheit==>celsius")
print("2.celsius==>fahrenheit")
ch=int(input("Enter your choice(1-2):"))
if (ch==1):
celsius()
elif (ch==2):
fahrenheit()
else:
print("Invalid choice")

2)
Eg: a=1
def f():
a=10
print(a)
output : 1

convert the following for loop into while loop:


for k in range(10,20,5):
print(k)

 for k in range(10,20):
while k % 5 == 0:
print(k)

20/7/2020
1)What are two types of HTTP requests?

HTTP requests are used on web by web clients for communicating with web servers. HTTP requests are
made in two forms:
(i)GET REQUEST: This HTTP request is made to request data from the server. This request sends a URL
to the webserver and the webserver returns the asked webpage’s HTML, which the web client displays
in the browser as a webpage.
(ii)POST REQUEST: This HTTP request is made to submit data to be processed to the webserver. This
request is made by the web clients when it has data(filled via forms or for upload), which the
webserver has to process. The POST request carries the data from web client to the webserver.

10)You have created a DJANGO project named Easy all


(i) Register (ii)sell (iii)work
What will be the contents of DJANGO project folder only list the folders, do not list any fill inside app
folders.

Easy all

Easy all

Register

Sell

Work

Manage.py

ii)Name the files that are found in project web application folder
ans) __init__.py settings.py urls.py wsg.py

21/7/2020
1)What is the command to install Django?
Ans: pip install Django

2)What is the command to create a project?


Ans: django-admin startproject<project name>

3)Which of the following is a django configuration files?


(ii)settings.py

4)This file is used to define database model:


Ans: models.py
5)Which file is used to manage django project and administrative tasks are performed by it?
Ans: manage.py

6)Django architecture consists of models, views and template.


(i)models
(ii)views
(iii)template
(iv)all of these

7)What is the full form of CSV?


Ans: comma separated value

8)What is the full form of PIP?


Ans: pip install packages/ pip install python

9)Whenever a web client have to access a webpage, it makes a HTTP GET request and sends URL of the
webpage.

10)The default port in Django server is localhost.

11)What is the full form of HTTP?


Ans: HTTP- Hypertext Transfer protocol

27/7/2020

Library refers to a collection of modules


 Python Standard Library
 Math module
 Cmath module
 Random module
 Statistics module
 Urllib module
Numpy library
Scipy library
Tkinter library
Matplotlib library

The act of partitioning a program into individual components(known as modules) is called as


modularity. It is a separate unit. The justification is:
It reduces its complexity to some degree and
It creates a no. of well-defined, documented boundaries within the program.

Docstrings of modules: help<module-name>


Defined names: dir()

Importing modules in a python:


(i)To import entire module: import <module>
(ii)To import selected objects from a module: from <module> import <object>

28/7/2020
Random module
Command: import random

Some most common number generator functions in random module are:


(i)random()
(ii)randint(a,b)
(iii)random.uniform(a,b)
(iv)random.randrange(stop)
(v)random.randrange(start,stop[,stop])

Exercise 4.2
What could be the minimum possible and maximum possible numbers by following code?
import random
print(random.randint(3,10)-3)
Ans: maximum possible number=7
Minimum possible number=0

29/7/2020
Urllib functions
(i)urllib.request.urlope(<URL>)
(ii)<urlopen’s return val>.read()
(iii)<urlopen’s return val>.getcode()
(iv)<urlopen’s return val>.headers
(v)<urlopen’s return val>.info()
(vi)<copy>.geturl()

import webbrowser

Program to get HTTP request information from the given URL and open it within the python
program.

import urllib
import webbrowser
import urllib.request
weburl=urllib.request.urlopen('http://www.google.com')
html=weburl.read()
data=weburl.getcode()
url=weburl.geturl()
hd=weburl.headers
inf=weburl.info
print("The URL is",url)
print("HTTP Status code is:",data)
print("Headers returned \n",hd)
print("the info() returned : \n",inf)
print("NOW opening the URL",url)
webbrowser.ope_new(url)

Program to open a webpage using urllib library

import urllib.request
Data=urllib.request.urlopen(‘http://www.google.com’)
Print(Data.read())

30/7/2020
Write a program in python that calculates the following:
(a)Area of circle
(b)Circumference of circle
(c)Area of rectangle
(d)Perimeter of rectangle
Create respective modules for each of the following operation and call them separately using a menu
driver program.

CIRCLE MODULE:
import math
def area(radius):
return math.pi*radius **2
def circumference(radius):
return 2*math.pi*radius

RECTANGLE MODULE:
import math
def area(x,y):
return x*y
def rectangle(x,y):
return 2*(x+y)

__mainprogram__
import circle
import rectangle

#the display menu function displays menu


#def displaymenu
while True:
print("MENU")
print("1.AREA OF CIRCLE")
print("2.CIRCUMFERENCE OF CIRCLE")
print("3.AREA OF RECTANGLE")
print("4.PERIMETER OF RECTANGLE")
print("5.quit")
x=int(input("enter your choice:"))
if(x==1):
radius=int(input("enter the circle's radius:"))
print("the area is",circle.area(radius))
elif(x==2):
radius=int(input("enter the circles radius:"))
print("the circumference of circle is",circle.circumference(radius))
elif(x==3):
width=int(input("enter the width:"))
length=int(input("enter the length:"))
print("the area of rectangle is",rectangles.area(width,length))
elif(x==4):
width=int(input("enter the width:"))
length=int(input("enter the length:"))
print("the area is ",rectangle.perimeter(width,length))

elif(x==5):
exit()

SECOND PROGRAM:

#rect.py
class rectangle:
def __init__(self):
print("rectangle")
def area(self,length,width):
self.l=length
self.w=width
print("area of rectangle is :",self.l*self.w)

#sq.py
class square:
def __init__(self):
print("square")
def area(self,side):
self.a=side
print("area of square is:",self.a*self.a)

#tri.py
class triangle:
def __init__(self):
print("triangle")
def area(self,base,height):
self.b=base
self.h=height
ar=(1/2)*self.b*self.h
print("area of triangle is:",ar)

#main.py
from module import rect
from module import sq
from module import tri

r=rect.rectangle( )#create an object r for rectangle class


r.area(10,20)#call the module area ( ) of rectangle class by passing argument
s=sq.square( )#create an object s for square class
s.area(10)#call the module arear( ) of square class by passing argument
t=tri.triangle( )#create the module t for triangle class
t.area(6,8)#call the module area ( ) of triangle class by passing argument

3/8/2020

OBJECTS AND CLASS METHODS


1)Class Basics:
Class ClassName(object):

2)Creating a new instance of a class:

Newobject=ClassName()

Therefore class car(object):


Pass
My_car=car()

variables used are known as member variables.


Functions used are known as member Functions.

Initializing a Class:
There is a special function named __init__() that gets called whenever we create a new instance of a
class. It exists by default even though we don’t see it. However we can define our own __init__()
function inside the class,

self.new_variable=new_variable
Model=”Delorean”
Color=”silver”
Mpg=88

class car(object):
Condition=”new”
def __init__(self,model,color,mpg):
self.model=model
self.color=color
self.mpg=mpg
my_car=car(“Delorean”,”silver”,88)
my_car.condition

4/8/2020

1)We can use python source file as a module by exciting an import statement.

2)dir() function when applied to a module gives us the name of all that is defined in the module.

3)What is the use of file __init__.py in a package?


Ans: for initializing a class

4)Differentiate between the statements


(a)import x
(b)from x import *
(c)from x import a,b,c

Ans: (a) is used for importing a module.


(b)Is used for importing all objects in a module.
(c)is used for importing particular objects in a module.

5/8/2020
1)What is possible outputs are expected to be displayed on at the time of execution of the program
from the following code:

import random
ar=[20,30,40,50,60,70]
from= random.randint(1,3)
to= random.randint(2,4)
for k in range(from,to+1):
print(ar[k],end=”#”)

Ans: 30#40#50#