You are on page 1of 48

Course File On

WEB TECHNOLOGIES

By

NOORE ILAHI
Assistant Professor
Computer Science and Engineering
Global Institute Of Engineering and Technology
2019-2020

HOD Principal
CSE GIET
GLOBAL INSTITUTE OF ENGINEERING AND TECHNOLOGY

COURSE FILE

Subject : WEB TECHNOLOGIES


Name : NOORE ILAHI
Designation : Assistant Professor
Regulation /Course Code : R 18 /CS504PC
Year / Semester : III / I
Department : CSE
Academic Year : 2020-21

S. No Topic Page No.


1 Cover Page

2 Vision of the Department

3 Mission of the Department

4 PEO‟s , PO‟s and PSO‟s

5 Syllabus Copy

6 Course Objectives and Outcomes

7 CO and PO Mapping

8 Pre Requisites if any

9 Brief notes on the importance of the course

10 Instructional Learning Outcomes

11 Course Information Sheet


a. Course Description
b. b. Syllabus
c. Gaps in Syllabus
d. Topics beyond the Syllabus
e. Web Sources and References
f. Delivery/Instructional Methodologies
g. Assessment Methodologies-Direct
h. Assessment Methodologies-Indirect
i. Text Books and Reference Books
12 Micro Lesson Plan

13 Teaching Schedule
14 Mid Descriptive and Quiz Question Papers with Answers
15 University Previous Question Papers
16 Assignment Topics
17 Unit wise Question Bank
2.VISION
The vision of the department is to produce professional computer science engineers who can
meet the expectations of the globe and contributes to the advancements of engineering and technology
which involves creativity and innovation by providing an excellent learning environment with best
quality facilities. .

3. MISSION

1. To provide the students with a practical and qualitative education in a modern technical
environment that will help to improve their abilities and skills in solving programming problems
effectively with different ideas and knowledge.
2. To infuse the scientific temper in the students towards the research and development in
Computer Science and Engineering trends.
3. To mould the graduates to assume leadership roles by possessing good communication skills, an
appreciation for their social and ethical responsibility in a global setting, and the ability to work
effectively as team members.
4. PROGRAM EDUCATIONAL OBJECTIVES, PROGRAM OUTCOMES AND
PROGRAM SPECIFICS OTCOMES

PROGRAM EDUCATIONAL OBJECTIVES

PEO 1. To provide graduates with a good foundation in mathematics, sciences and engineering
fundamentals required to solve engineering problems that will facilitate them to find employment in
MNCs and / or to pursue postgraduate studies with an appreciation for lifelong learning.
PEO 2. To provide graduates with analytical and problem-solving skills to design algorithms, other
hardware / software systems, and inculcate professional ethics, interpersonal skills to work in a multi-
cultural team.
PEO 3. To facilitate graduates to get familiarized with the art software / hardware tools, imbibing
creativity and innovation that would enable them to develop cutting-edge technologies of multi-
disciplinary nature for societal development.
PEO 4. To provide a modern environment to develop professional skills that prepare them for
immediate employment and for life-long learning in advanced areas of computer science and related
fields.
PROGRAM OUTCOMES
PO 1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering problems.
PO 2: Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural science and engineering sciences.

PO 3: Design/development of solutions: design solutions for complex engineering problems and


design system components or processes that meet the specified needs with appropriate consideration
for the public health and safety, and the cultural, societal and environmental considerations.

PO 4: Conduct investigations of complex problems: use research based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO 5: Modern tool usage: create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.

PO 6: The engineer and society: apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.

PO 7: Environment sustainability: understand the impact of the professional engineering solutions


in the societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.

PO 8: Ethics: apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO 9: Individual and team work: function effectively as an individual and as a member or leader in
diverse teams, and in multidisciplinary settings.

PO 10: Communication: communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.

PO 11: Project management and finance: demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.

PO 12: Lifelong learning: recognize the need for, and have the preparation and ability to engage in
independent and lifelong learning in the broader context of technological change.

PROGRAM SPECIFIC OUTCOMES

PSO 1: An Ability to Apply the fundamentals of mathematics, Computer Science and Engineering
Knowledge to analyze and develop computer programs in the areas related to Algorithms, System
Software, Web Designing, Networking and Data mining for efficient Design of computer based system
to deal with Real time Problems.

PSO 2: Ability to implement the Professional Engineering solutions for the betterment of Society, and
able to communicate with professional Ethics effectively.

5.SYLLABUS COPY
UNIT - I
Introduction to PHP: Declaring variables, data types, arrays, strings, operators, expressions, control
structures, functions, Reading data from web form controls like text boxes, radio buttons, lists etc.,
Handling File Uploads, Connecting to database (MySQL as reference), executing simple queries,
handling results, Handling sessions and cookies
File Handling in PHP: File operations like opening, closing, reading, writing, appending, deleting etc.
on text and binary files, listing directories

UNIT - II
HTML Common tags- List, Tables, images, forms, Frames; Cascading Style sheets; XML:
Introduction to XML, Defining XML tags, their attributes and values, Document Type Definition,
XML Schemes, Document Object Model, XHTML Parsing XML Data – DOM and SAX Parsers in
java

UNIT - III
Introduction to Servlets: Common Gateway Interface (CGI), Lifecycle of a Servlet, deploying a
servlet, The Servlet API, Reading Servlet parameters, Reading Initialization parameters, Handling Http
Request & Responses, Using Cookies and Sessions, connecting to a database using JDBC.

UNIT - IV
Introduction to JSP: The Anatomy of a JSP Page, JSP Processing, Declarations, Directives,
Expressions, Code Snippets, implicit objects, Using Beans in JSP Pages, Using Cookies and session
for session tracking, connecting to database in JSP.

UNIT- V
Client-side Scripting: Introduction to Javascript, Javascript language – declaring variables, scope of
variables, functions. event handlers (onclick, onsubmit etc.), Document Object Model, Form
validation.

TEXT BOOKS:
1. Web Technologies, Uttam K Roy, Oxford University Press
2. The Complete Reference PHP – Steven Holzner, Tata McGraw-Hill
6.COURSE OBJECTIVES AND COURSE OUTCOMES
(A)COURSE OBJECTIVES
At the end of the course, the students will be able to:
To introduce PHP language for server-side scripting
 To introduce XML and processing of XML Data with Java
 To introduce Server-side programming with Java Servlets and JSP
 To introduce Client-side scripting with JavaScript and AJAX.
(B)COURSE OUTCOMES:

After completing this course, the student must demonstrate the knowledge and able to:

CO1: To explain server side scripting and make use of PHP.

CO2: To define XML and choose appropriate parser techniques (DOM and SAX).

CO3: To demonstrate Server side programming and build applications with java Servlets.

CO4: To demonstrate Server side programming and build applications with JSP’s

CO5: To define client side scripting and make use of JavaScript to validate at client side.

7. CO’S, PO’S MAPPING AND CO AND PSO MAPPING


CO/PO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 2 2 3

CO2 3 3 3 3

CO3 3 3 3 2 1 3 3

CO4 3 2 3 2 3 2 1 3 3

CO5 3 2 3 2 3 2 1 3 3

Where
1. Low
2. Medium
3. High

8
CO and PSO Mapping:

CO/ PSO1 PSO2


PO
CO1 3 3

CO2 2 3

CO3 2 3

CO4 3 2

CO5 3 2

Where
1. Low
2. Medium
3. High

8.PRE REQUISITIES IF ANY


The prerequisite for learning Web Technologies is basic knowledge of Internet concepts like Server side and
client side, Communication between Client and Server

9. BRIEF NOTES ON THE IMPORTANCE OF THE COURSE

Web Technology refers to the various tools and techniques that are utilized in the process of communication
between different types of devices over the internet. A web browser is used to access web pages. Web browsers
can be defined as programs that display text, data, pictures, animation, and video on the Internet. Hyperlinked
resources on the World Wide Web can be accessed using software interfaces provided by Web browsers.

10.INSTRUCTIONAL LEARNING OUTCOMES


At the end of the course, the students are able to achieve the following course learning outcomes:

Lecture Topic to be covered Topic Outcome


No.
L1 Over view of course Examine the course objectives, outcomes,
assessment methods, grading policy and basic
ground rules for the subject
L2 Introduction to PHP: Declaring variables
L3 data types, ,
L4 arrays
L5 strings
L6 operators

9
Lecture Topic to be covered Topic Outcome
No.
L7 expressions, ,
L8 control structures
L9 functions
L10
Reading data from web form controls
L11 like text boxes,radio buttons,
L12 lists
L13 Handling File Uploads.
Connecting to database (MySQL as
L14 reference)
L16 executing simple queries,
L17 Handling sessions and cookies
L18 File Handling in PHP: File operations like
opening, closing on text and binary files
L19 File operations like reading, writing on text
and binary files
L20 File operations like appending, deleting on
text and binary files
L21 listing directories.
L22 HTML Common tags
L23 List
L24 Tables
L25 Images,
L26 Forms
L27 Frames
L28 Cascading Style sheets;
L29 XML: Introduction to XML
Defining XML tags, their attributes and
values
L30
L31 Document Type Definition
L32 XML Schemes
L33 Document Object Model,
XHTML Parsing XML Data – DOM
L34 Parsers in java
XHTML Parsing XML Data –SAX
L35 Parsers in java
L36 UNIT-III .
Introduction to Servlets: Common
Gateway Interface (CGt),
L37 Life cycle of a Servlet
L38 deploying a servlet
10
Lecture Topic to be covered Topic Outcome
No.
MID EXAM 1
L39 The Servlet API,
L40 Reading Servlet parameters
L41 Reading Initialization parameters,
L42 Handling Http Request & Responses,
L43 Using Cookies and Sessions
L44 connecting to a database using JDBC
UNIT-IV
L45 Introduction to JSP
The Anatomy of a JSP Page,
L46
L47 JSP Processing
Declarations,
L48
Directives,
L59
L50 Expressions
L51 Code Snippets
L52 Implicit objects,
L53 Using Beans in JSP Pages
Using Cookies and session for session
L54 tracking
L55 connecting to database in JSP.
UNIT-5
L56 Introduction to Client-side Scripting
L57 Introduction to Javascript
L58 Javascript language – declaring variables
L59 scope of variables
L60 functions.
L61 event handlers (onclick, onsubmit etc.)
L62 Document Object Model,
L63 Form validation.
II MID EXAMINATION

11. COURSE INFORMATION SHEET (CIS)

11
(A)COURSE DESCRIPTION

PROGRAMME: B. TECH DEGREE: B.TECH

(Computer Science and Engineering)

COURSE: WEB TECHNOLOGIES YEAR: III SEM: I CREDITS: 3

COURSE CODE : CS504PC COURSE TYPE : CORE

REGULATION : R18

COURSE AREA/DOMAIN : CSE/WEB CONTACT HOUR S: 3+0 (L+T)) hours/Week.


DESIGNING

(B)SYLLABUS

Uni Details
Hours
t
Introduction to PHP: Declaring variables, data types, arrays, strings, operators,
expressions, control structures, functions, Reading data from web form controls like text
boxes, radio buttons, lists etc., Handling File Uploads. Connecting to database (MySQL as
I
reference), executing simple queries, handling results, Handling sessions and cookies File
Handling in PHP: File operations like opening, closing, reading, writing, appending,
deleting etc. on text and binary files, listing directories
HTML Common tags- List, Tables, images, forms, Frames; Cascading Style sheets;
XML: Introduction to XML, Defining XML tags, their attributes and values,
II Document Type Definition, XML Schemes, Document Object Model, XHTML
Parsing XML Data – DOM and SAX Parsers in java.
Introduction to Servlets: Common Gateway Interface (CGt), Life cycle of a Servlet,
deploying a servlet, The Servlet API, Reading Servlet parameters, Reading
III Initialization parameters, Handling Http Request & Responses, Using Cookies and
Sessions, connecting to a database using JDBC.
Introduction to JSP: The Anatomy of a JSP Page, JSP Processing, Declarations,
IV Directives, Expressions, Code Snippets, implicit objects, Using Beans in JSP Pages,
Using Cookies and session for session tracking, connecting to database in JSP.
Client-side Scripting: Introduction to Javascript, Javascript language – declaring
V variables, scope of variables, functions. event handlers (onclick, onsubmit etc.),
Document Object Model, Form validation
Contact classes for syllabus coverage
Lectures beyond syllabus
Tutorial classes
Classes for gaps & Add-on classes
Total No. of classes

( C) GAPS IN SYLLABUS

12
S.N Topic Propose Action No. of classes
1

(D) TOPICS BEYOND SYLLABUS

S.N. Topic Propose Action No. of Classes

(E) WEB SOURCE REFERENCES

Sl. No. Name of book/ website

1
2
3

(F) DELIVERY?INSTRUCTIONAL METHODOLOGIES

 CHALK & TALK  STUD. ASSIGNMENT  WEB RESOURCES

 LCD/SMART  STUD. SEMINARS ☐ ADD-ON COURSES


BOARDS

(G) ASSESSMENT METHODOLOGIES- DIRECT

  Stud. Seminars  Tests/Model  Univ. Examination


Assignments Exams

 Stud. Lab  Stud. Viva ☐ Mini/Major ☐ Certifications


Practices Projects

☐ Add-On ☐ Others
Courses

13
(H) ASSESSMENT METHODOLOGIES – INDIRECT

 Assessment Of Course Outcomes  Student Feedback On

(By Feedback, Once) Faculty (Twice)

☐Assessment Of Mini/Major Projects By ☐ Others


Ext. Experts

(I) TEXTBOOKS AND REFERENCES

Text Book

1. Web Technologies, Uttam K Roy, Oxford University Press

2. The Complete Reference PHP — Steven Holzner, Tata McGraw-Hill

12. MICRO LESSION PLAN

Lecture Topic to be covered Planned Date Actual Date


No.
L1 Over view of course
L2 Introduction to PHP:
L3 Declaring variables
L4 data types, ,
L5 arrays
L6 strings
L7 operators
L8 expressions, ,
L9 control structures
L10 functions
Reading data from web form controls
L11 like text boxes, radio buttons,
L12 lists
L13 Handling File Uploads.
Connecting to database (MySQL as
L14 reference)
L15 executing simple queries,
L16 Handling sessions and cookies
L17 File Handling in PHP: File operations like
opening, closing on text and binary files

14
Lecture Topic to be covered Planned Date Actual Date
No.
L18 File operations like reading, writing on text
and binary files
L19 File operations like appending, deleting on
text and binary files
L20 Listing directories.
L21 HTML Common tags
L22 List
L23 Tables
L24 Images,
L25 Forms
L26 Frames
L27 Cascading Style sheets;
L28 XML: Introduction to XML
Defining XML tags, their attributes and
values
L29
L30 Document Type Definition
L31 XML Schemes
L32 Document Object Model,
XHTML Parsing XML Data – DOM
L33 Parsers in java
XHTML Parsing XML Data –SAX
L34 Parsers in java
UNIT-III
Introduction To Servlets: Common
L35 Gateway Interface (CGI).
L36 Life Cycle Of A Servlet
L37 Deploying A Servlet
MID EXAM 1
L38 The Servlet API
L39 Reading Servlet Parameters
L40 Reading Initialization Parameters,
L41 Handling Http Request & Responses,
L42 Using Cookies And Sessions
L43 Connecting To A Database Using JDBC
Unit-IV
L44 Introduction To JSP
The Anatomy Of A JSP Page,
L45
L46 JSP Processing
L47 Declarations
L48 Directives
15
Lecture Topic to be covered Planned Date Actual Date
No.

L59 Expressions
L50 Code Snippets
L51 Implicit Objects,
L52 Using Beans In JSP Pages
Using Cookies And Session For Session
L53 Tracking
L54 Connecting To Database In JSP
Unit-5
L55 Introduction To Client-Side Scripting
L56 Introduction To JavaScript
JavaScript Language – Declaring
L57 Variables
L58 Scope Of Variables
L59 Functions.
L60 Event Handlers (Onclick, Onsubmit Etc.)
L61 Document Object Model,
L62 Form Validation.
MID II EXAMINATION

16
13.TEACHING SCHEDULE

Subject Data Warehousing and Data Mining


Text Books (to be purchased by the Students)
Book 1

Reference Books
Chapters nos No of
Unit Topic classes
Book 1

II

III

IV

Contact classes for syllabus coverage

Lectures beyond syllabus

Tutorial classes

Classes for gaps & Add-on classes

Total No. of classes

14. MID 1 DESCRIPTIVE AND QUIZ QUESTIONS WITH ANSWERS

17
Global Institute of Engineering &Technology College Code

(Approved by AICTE, Affiliated to JNTUH)


U6
Chilkur (Vil), Moinabad (Mdl), RR District

Name of the Exam: I Mid Examinations Marks: 10

Year-Sem & Branch: IV-I & CSE Duration: 60 Min

Date & 11-09-2019 &


Subject: Python Programming
Session FN

Answer ANY TWO of the following Questions 2X5=10

BLOOMS
Q.NO QUESTION CO MAPPING
TAXONOMY

Explain Modules and built in functions with


1 CO 1 Apply
syntax and example?

Explain in detail about Sequence data type of


Analyze
2 the following? CO 1
a)Set types
b)Tuples
3 a) What is Exception in python? CO 2 Apply
b)Explain Detecting and Handling Exception?

CO 3 Analyze
4 a)Explain Regular Expressions ?
b)Define thread and process in python?

18
MID I DESCRIPTIVE QUESTION AND ANSWERS

1. Explain Modules and built in functions with syntax and example?

Ans: A module is a file containing Python definitions and statements. A module can define functions, classes
and variables. A module can also include runnable code. Grouping related code into a module makes the code
easier to understand and use. Python Built-In Functions.

def add(x, y):


return (x+y)

def subtract(x, y):


return (x-y)
1. abs()

The abs() is one of the most popular Python built-in functions, which returns the absolute value of a number. A
negative value’s absolute is that value is positive.

>>> abs(-7)

2. all()

The all() function takes a container as an argument. This Built in Functions returns True if all values in a
python iterable have a Boolean value of True. An empty value has a Boolean value of False.

>>> all({'*','',''})

False

3. any()

Like all(), it takes one argument and returns True if, even one value in the iterable has a Boolean value of True.

>>> any((1,0,0))

True

4. ascii()

It is important Python built-in functions, returns a printable representation of a python object (like a string or
a Python list). Let’s take a Romanian character.

>>> ascii('ș')

“‘\\u0219′”

Since this was a non-ASCII character in python, the interpreter added a backslash (\) and escaped it using
another backslash.

>>> ascii('ușor')

“‘u\\u0219or'”

19
5. bin()

bin() converts an integer to a binary string. We have seen this and other functions in our article on Python
Numbers.

>>> bin(7)

‘0b111’

6. bool()

bool() converts a value to Boolean.

>>> bool(0.5)

True

7. bytearray()

bytearray() returns a python array of a given byte size.

>>> a=bytearray(4)

>>> a

bytearray(b’\x00\x00\x00\x00′)

>>> a.append(1)

>>> a

8. bytes()

bytes() returns an immutable bytes object.

>>> bytes(5)

b’\x00\x00\x00\x00\x00′

9. callable()

callable() tells us if an object can be called.

>>> callable([1,2,3])

False

A function is callable, a list is not. Even the callable() python Built In function is callable.

10. chr()

chr() Built In function returns the character in python for an ASCII value.

>>> chr(65)

‘A’

20
2. Explain in detail about Sequence data type of the following?
a)Set types b)Tuples

Ans:
a)Set Types:
A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
Example

Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)
Access Items:

cannot access items in a set by referring to an index, since sets are unordered the items has no index. But can
loop through the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.

Example:

Loop through the set, and print the values:

thisset = {"apple", "banana", "cherry"}


for x in thisset:
print(x)

Add Items:
To add one item to a set use the add() method.
To add more than one item to a set use the update() method.
Example

Add an item to a set, using the add() method:


thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)

Get the Length of a Set:


To determine how many items a set has, use the len() method.
Example

Get the number of items in a set:


thisset = {"apple", "banana", "cherry"}
print(len(thisset))

Remove Item:
To remove an item in a set, use the remove(), or the discard() method.
Example:

Remove "banana" by using the remove() method:

21
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Join Two Sets:

There are several ways to join two or more sets in Python. the union() method that returns a new set containing
all items from both sets, or the update() method that inserts all the items from one set into another:

Example

The union() method returns a new set with all items from both sets:

set1 = {"a", "b" , "c"}


set2 = {1, 2, 3}
set3 = set1.union(set2)
print(set3)

The set() Constructor:


It is also possible to use the set() constructor to make a set.
Example
Using the set() constructor to make a set:
thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
print(thisset)

b)Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets.

Example

Create a Tuple

thistuple = ("apple", "banana", "cherry")


print(thistuple)
Access Tuple Items:

You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is
called.But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back
into a tuple.

Example

Convert the tuple into a list to be able to change it:

22
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)
print(x)

Tuple Length:

To determine how many items a tuple has, use the len() method:

Example

Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Remove Items

Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:

Example

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists
Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description

count() Returns the number of times a specified value


occurs in a tuple

index() Searches the tuple for a specified value and returns


the position of where it was found

3.a) What is Exception in python?


b) Explain Detecting and Handling Exception?

Ans: a)An exception is an event, which occurs during the execution of a program that disrupts the normal flow
of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it
raises an exception. An exception is a Python object that represents an error.
Python provides two very important features to handle any unexpected error in your Python programs and to
add debugging capabilities in them
Exception Handling -Here is a list standard Exceptions available in Python: Standard Exceptions.
Assertions − This would be covered in Assertions in Python tutorial.

23
List of Standard Exceptions
Sr.No. Exception Name & Description

1 Exception
Base class for all exceptions

2 StopIteration
Raised when the next() method of an iterator does not
point to any object.

3 SystemExit
Raised by the sys.exit() function.

4 StandardError
Base class for all built-in exceptions except StopIteration
and SystemExit.

5 ArithmeticError
Base class for all errors that occur for numeric calculation.

b) Explain Detecting and Handling Exception?

Exception handling in python


If the python program contains suspicious code that may throw the exception, we must place that code in
the try block. The try block must be followed with the except statement which contains a block of code
that will be executed if there is some exception in the try block.
Syntax
try:
#block of code

except Exception1:
#block of code

except Exception2:
#block of code

#other code

We can also use the else statement with the try-except statement in which, we can place the code which
will be executed in the scenario if no exception occurs in the try block.

The syntax to use the else statement with the try-except statement is given below.
try:
#block of code

except Exception1:
#block of code

else:
#this code executes if no except block is executed

24
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
else:
print("Hi I am else block")

Output:
Enter a:10
Enter b:2
a/b = 5

The except statement with no exception


Python provides the flexibility not to specify the name of exception with the except statement.
Consider the following example.
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")

Output:
Enter a:10
Enter b:0
can't divide by zero

Python facilitates us to not specify the exception with the except statement.
We can declare multiple exceptions in the except statement since the try block may contain the statements
which throw the different type of exceptions.
We can also specify an else block along with the try-except statement which will be executed if no
exception is raised in the try block.

The statements that don't throw the exception should be placed inside the else block.
Example
try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()
Output:
25
File not found
Declaring multiple exceptions
The python allows us to declare the multiple exceptions with the except clause. Declaring multiple
exceptions is useful in the cases where a try block throws multiple exceptions.
Syntax
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code
Example
try:
a=10/0;
except ArithmeticError,StandardError:
print "Arithmetic Exception"
else:
print "Successfully Done"
Output:
Arithmetic Exception

The finally block


We can use the finally block with the try block in which, we can pace the important code which must be
executed before the try statement throws an exception.
The syntax to use the finally block is given below.
syntax
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

Example
try:
fileptr = open("file.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")

Output:
file closed
Error

Raising exceptions
An exception can be raised by using the raise clause in python. The syntax to use the raise statement is
given below.

26
syntax
raise Exception_class,<value>
Points to remember
To raise an exception, raise statement is used. The exception class name follows it.
An exception can be provided with a value that can be given in the parenthesis.
To access the value "as" keyword is used. "e" is used as a reference variable which stores the value of the
exception.
Example
try:
age = int(input("Enter the age?"))
if age<18:
raise ValueError;
else:
print("the age is valid")
except ValueError:
print("The age is not valid")
Output:
Enter the age?17
The age is not valid
Example
try:
a = int(input("Enter a?"))
b = int(input("Enter b?"))
if b is 0:
raise ArithmeticError;
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")
Output:
Enter a?10
Enter b?0
The value of b can't be 0

Custom Exception
The python allows us to create our exceptions that can be raised from the program and caught using the
except clause. However, we suggest you read this section after visiting the Python object and classes.
Consider the following example.
Example
class ErrorInCode(Exception):
def __init__(self, data):
self.data = data
def __str__(self):
return repr(self.data)

try:
raise ErrorInCode(2000)
except ErrorInCode as ae:
print("Received error:", ae.data)

Output:
Received error: 2000

27
4.a) Explain Regular Expressions ?
b) Define thread and process in python?

Ans:a) Regular Expressions:


A regular expression is a special sequence of characters that helps you match or find other strings or sets of
strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.
The Python module re provides full support for Perl-like regular expressions in Python. The re module raises
the exception re.error if an error occurs while compiling or using a regular expression.
We would cover two important functions, which would be used to handle regular expressions. But a small
thing first: There are various characters, which would have special meaning when they are used in regular
expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings
as r'expression'.
Regular Expression Patterns:
Except for control characters, (+ ? . * ^ $ ( ) [ ] { } | \), all characters match themselves. You can escape a
control character by preceding it with a backslash.
Following table lists the regular expression syntax that is available in Python −
Sr.No Pattern & Description
.

1 ^
Matches beginning of line. 4. a)Explain Regular Expressions ?

2 $
Matches end of line.

3 .
Matches any single character except newline. Using m option
allows it to match newline as well.

4 [...]
Matches any single character in brackets.

5 [^...]
Matches any single character not in brackets

6 re*
Matches 0 or more occurrences of preceding expression.

7 re+
Matches 1 or more occurrence of preceding expression.

8 re?
Matches 0 or 1 occurrence of preceding expression.

9 re{ n}
Matches exactly n number of occurrences of preceding
expression.

10 re{ n,}
Matches n or more occurrences of preceding expression.

28
4.b) Define thread and process in python?
Ans: In computing, a process is an instance of a computer program that is being executed. Any process has 3
basic components:
 An executable program.
 The associated data needed by the program (variables, work space, buffers, etc.)
 The execution context of the program (State of process)
A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of
processing that can be performed in an OS (Operating System).
In simple words, a thread is a sequence of such instructions within a program that can be executed
independently of other code. For simplicity, you can assume that a thread is simply a subset of a process!
A thread contains all this information in a Thread Control Block (TCB):
 Thread Identifier: Unique id (TID) is assigned to every new thread
 Stack pointer: Points to thread’s stack in the process. Stack contains the local variables under thread’s
scope.
 Program counter: a register which stores the address of the instruction currently being executed by
thread.
 Thread state: can be running, ready, waiting, start or done.
 Thread’s register set: registers assigned to thread for computations.
 Parent process Pointer: A pointer to the Process control block (PCB) of the process that the thread
lives on.

29
MID 1 OBJECTIVE QUESTION PAPER

Multiple choice question

1. In python which keyword is used to start the function [ ]


a)function b)def c)try d)import

2. which function is used to open the file for reading in python


a) fopen(filename,mode) b) open(filename,mode) c)f_open(filename,mode) [ ]
d) open_file(filename,mode)

3.What is the return type of function id [ ]


a)float b)bool c) int d) dict

4.Which of the following is not a predefined data type in python [ ]


a)List b) class c)Dict d) Tuple

5.List is [12,5,3,76,30], List[-1] is [ ]


a)0 b)12 c) 30 d)error

6.Which data type is used to store values in key & value format [ ]
a) List b) String c) Set d) Dictionary

7. which of the following has more precedence [ ]


a) + b) / c) - d) ( )

8. Output for:
name=”helloworld”
print(type(name)) [ ]
a)helloworld b)name=”helloworld” c) <class ‘str’> d) str

9. Which of the following is used for comment in python [ ]


a) # b) % c) // d) **

10. python is said to be [ ]


a) readable language b)scrip-table language c)writable d)bug-able language

Fill in the blanks:

11._____________ is the order in which operators are computed.

12. _______________is used to convert data from one type to another.

13.An _____________is an error that happens during execution of program.

30
14.______________ allows to access,manipulate and all user accessable files.

15. File consisting of python code is called ________________.

16. A__________ is an entity within a process that can be scheduled for execution.

17._____________ functions are used to open and close a file in python

18. Python is _____________________ language.

19. Syntax to open a file in read mode_________________.

20.Access modifier r+w is used to open a file for____________.

Key:

S.No MCQ Fill in Blanks

10

31
MID II DESCRIPTIVE AND QUIZ QUESTIONS WITH ANSWERS
Global Institute of Engineering &Technology College Code

(Approved by AICTE, Affiliated to JNTUH)


U6
Chilkur (Vil), Moinabad (Mdl), RR District

Name of the Exam: II Mid Examinations Marks: 10

Year-Sem & Branch: IV-I & CSE Duration: 60 Min

Date & 21-11-2019 &


Subject: Python Programming
Session FN

Answer ANY TWO of the following Questions 2X5=10

BLOOMS
Q.NO QUESTION CO MAPPING
TAXONOMY

Design Simple web clients in python by web


1 5 Create
surfing.

Relate Multithreading and Global interpreter


2 lock 5 Analyze

Examine CGI-Helping Servers Process Client


3 5 Apply
Data?

Develop python Database Application


4 5 create
Programmer’s interface(DB-API)

32
1. Design Simple web clients in python by web surfing.

Ans) Simple Web surfing involves using Web addresses called URLs (Uniform Resource Locators). Such
addresses are used to locate a document on the Web or to call a CGI program to generate a document for your
client. URLs are part of a larger set of identifiers known as URIs (Uniform Resource Identifiers). This superset
was created in anticipation of other naming conventions that have yet to be developed. A URL is simply a URI
which uses an existing protocol or scheme (i.e., http, ftp, etc.) as part of its addressing. To complete this
picture, we'll add that non-URL URIs are sometimes known as URNs (Uniform Resource Names), but because
URLs are the only URIs in use today, you really don't hear much about URIs or URNs, save perhaps as XML
identifiers. Like street addresses, Web addresses have some structure. An American street address usually is of
the form "number street designation," i.e., 123 Main Street. It differs from other countries, which have their
own rules. A URL uses the format:

prot_sch://net_loc/path;params?query#frag

Web Address Components

33
URL Component Description

prot_sch Network protocol or download scheme

net_loc Location of server (and perhaps user information)

path Slash ( / )delimited path to file or CGI application

params Optional parameters

query Ampersand ( & )delimited set of "key=value" pairs

frag Fragment to a specific anchor within document

file:///D|/1/0132269937/ch20lev1sec2.html (1 von 12) [13.11.2007 16:25:05]

Web Surfing with Python: Creating Simple Web Clients net_loc can be broken down into several more
components, some required, others optional.

The net_loc string looks like this: user:passwd@host:port

Network Location Components

net_loc Component Description

user User name or login

passwd User password

host Name or address of machine running Web server [required]

port Port number (if not 80, the default)

Of the four, the host name is the most important. The port number is necessary only if the Web server is
running on a different port number from the default. (If you aren't sure what a port number is, go back to
Chapter 16.) User names and perhaps passwords are used only when making FTP connections, and even then
they usually aren't necessary because the majority of such connections are "anonymous." Python supplies two
different modules, each dealing with URLs in completely different functionality and capacities. One is
urlparse, and the other is urllib. We will briefly introduce some of their functions.

2. Relate Multithreading and Global interpreter lock?

Ans: The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one
thread to hold the control of the Python interpreter.

This means that only one thread can be in a state of execution at any point in time. The impact of the GIL isn’t
visible to developers who execute single-threaded programs, but it can be a performance bottleneck in CPU-
bound and multi-threaded code.

Since the GIL allows only one thread to execute at a time even in a multi-threaded architecture with more than
one CPU core, the GIL has gained a reputation as an “infamous” feature of Python.

34
Python uses reference counting for memory management. It means that objects created in Python have a
reference count variable that keeps track of the number of references that point to the object. When this count
reaches zero, the memory occupied by the object is released.

Let’s take a look at a brief code example to demonstrate how reference counting works:

>>>

>>> import sys

>>> a = []

>>> b = a

>>> sys.getrefcount(a)

In the above example, the reference count for the empty list object [] was 3. The list object was referenced
by a, b and the argument passed to sys.getrefcount().

Back to the GIL:

The problem was that this reference count variable needed protection from race conditions where two threads
increase or decrease its value simultaneously. If this happens, it can cause either leaked memory that is never
released or, even worse, incorrectly release the memory while a reference to that object still exists. This can
can cause crashes or other “weird” bugs in your Python programs.

This reference count variable can be kept safe by adding locks to all data structures that are shared across
threads so that they are not modified inconsistently.

But adding a lock to each object or groups of objects means multiple locks will exist which can cause another
problem—Deadlocks (deadlocks can only happen if there is more than one lock). Another side effect would be
decreased performance caused by the repeated acquisition and release of locks.

The GIL is a single lock on the interpreter itself which adds a rule that execution of any Python bytecode
requires acquiring the interpreter lock. This prevents deadlocks (as there is only one lock) and doesn’t
introduce much performance overhead. But it effectively makes any CPU-bound Python program single-
threaded.

The GIL, although used by interpreters for other languages like Ruby, is not the only solution to this problem.
Some languages avoid the requirement of a GIL for thread-safe memory management by using approaches
other than reference counting, such as garbage collection.

On the other hand, this means that those languages often have to compensate for the loss of single threaded
performance benefits of a GIL by adding other performance boosting features like JIT compilers.

The impact on multi-threaded Python programs

When you look at a typical Python program—or any computer program for that matter—there’s a difference
between those that are CPU-bound in their performance and those that are I/O-bound.

35
CPU-bound programs are those that are pushing the CPU to its limit. This includes programs that do
mathematical computations like matrix multiplications, searching, image processing, etc.

I/O-bound programs are the ones that spend time waiting for Input/Output which can come from a user, file,
database, network, etc. I/O-bound programs sometimes have to wait for a significant amount of time till they
get what they need from the source due to the fact that the source may need to do its own processing before the
input/output is ready, for example, a user thinking about what to enter into an input prompt or a database query
running in its own process.

3. Examine CGI-Helping Servers Process Client Data?

Ans: CGI applications that create the HTML are usually written in one of many higher-level programming
languages that have the ability to accept user data, process it, and return HTML back to the server. Currently
used programming languages include Perl, PHP, C/C++, or Python, to name a few. Before we take a look at
CGI, we have to provide the caveat that the typical production Web application is no longer being done in CGI
anymore. Because of its significant limitations and limited ability to allow Web servers to process an abundant
number of simultaneous clients, CGI is a dinosaur. Mission-critical Web services rely on compiled languages
like C/C++ to scale. A modern-day Web server is typically composed of Apache and integrated components
for database access (MySQL or PostgreSQL), Java (Tomcat), PHP, and various modules for Perl, Python, and
SSL/security. However, if you are working on small personal Web sites or ones for small organizations and do
not need the power and complexity required by mission critical Web services, CGI is the perfect tool for your
simple Web sites.

Building CGI Applications:


Setting Up a Web Server: first install a Web server,
configure it for handling Python CGI requests, and then give the Web server access to your CGI scripts.
Some of these tasks may require assistance from your system administrator.
If you want to just start up the most basic Web server, just execute it directly with Python:

$ python -m CGIHTTPServer

This will start a Web server on port 8000 on your current machine from the current directory.
Then you can just create a Cgi-bin right underneath the directory from which you started the server and put
your Python CGI scripts in there.
Put some HTML files in that directory and perhaps some .py CGI scripts in Cgi-bin, and you are ready to
"surf" directly to this Web site with addresses looking something like these:
http://localhost:8000/friends.htm
http://localhost:8000/cgi-bin/friends2.py
36
Creating the Form Page:
Static Form Web Page (friends.htm)
<HTML><HEAD><TITLE>
2 Friends CGI Demo (static screen)
3 </TITLE></HEAD>
4 <BODY><H3>Friends list for: <I>NEW USER</I></H3>
5 <FORM ACTION="/cgi-bin/friends1.py">
6 <B>Enter your Name:</B>
7 <INPUT TYPE=text NAME=person VALUE="NEW USER" SIZE=15>
8 <P><B>How many friends do you have?</B>
9 <INPUT TYPE=radio NAME=howmany VALUE="0" CHECKED> 0
10 <INPUT TYPE=radio NAME=howmany VALUE="10"> 10
11 <INPUT TYPE=radio NAME=howmany VALUE="25"> 25
12 <INPUT TYPE=radio NAME=howmany VALUE="50"> 50
13 <INPUT TYPE=radio NAME=howmany VALUE="100"> 100
14 <P><INPUT TYPE=submit></FORM></BODY></HTML>

37
4. Develop python Database Application Programmer’s interface(DB-API)?

Ans: The API is a specification that states a set of required objects and database access mechanisms to provide
consistent access across the various database adapters and underlying database systems. Like most community-
based efforts, the API was driven by strong need.
Module Attributes

The DB-API specification mandates that the features and attributes listed below must be supplied.
A DBAPI- compliant module must define the global attributes as shown

DB-API Module Attributes

Attribute Description
apilevel Version of DB-API module is compliant with
threadsafety Level of thread safety of this module
paramstyle SQL statement parameter style of this module
Connect() Connect() function
DB-API Exception Classes
Exception Description
Warning Root warning exception class
Error Root error exception class
InterfaceError Database interface (not database) error
DatabaseError Database error
DataError Problems with the processed data
OperationalError Error during database operation execution
IntegrityError Database relational integrity error
InternalError Error that occurs within the database
ProgrammingError SQL command failed
38
NotSupportedError Unsupported operation occurred

Connection Objects:

Connections are how your application gets to talk to the database. They represent the fundamental
communication mechanism by which commands are sent to the server and results returned. Once a
connection has been established (or a pool of connections), you create cursors to send requests to and
receive replies from the database.

Methods

Connection objects are not required to have any data attributes but should define the methods shown in
Connection Object Methods
Method Name Description
close() Close database connection
commit() Commit current transaction
rollback() Cancel current transaction
cursor() Create (and return) a cursor or cursor-like object using this connection

errorhandler(cxn, cur, errcls, errval) Serves as a handler for given connection cursor

When close() is used, the same connection cannot be used again without running into an exception.

Cursor Objects

Once you have a connection, you can start talking to the database. As we mentioned above in the
introductory section, a cursor lets a user issue database commands and retrieve rows resulting from
queries. A Python DB-API cursor object functions as a cursor for you, even if cursors are not supported
in the database. In this case, the database adapter creator must implement CURSOR objects so that they
act like cursors. This keeps your Python code consistent when you switch between database systems
that have or do not have cursor support.
Once you have created a cursor, you can execute a query or command (or multiple queries and
commands) and retrieve one or more rows from the results set.
shows data attributes and methods that cursor objects have.

Cursor Object Attributes

Object Attribute Description


arraysize Number of rows to fetch at a time with fetch many(); defaultsto 1
connection Connection that created this cursor (optional)
description Returns cursor activity (7-item tuples):(name, type_code, display_size,
internal_ size, precision, scale, null_ok);
only name and type_code are required
lastrowid Row ID of last modified row (optional; if row IDs not supported, default to None)
rowcount Number of rows that the last execute*() produced or affected

39
MID II OBJECTIVE QUESTION PAPER

CHOOSE THE CORRECT ANSWERS:

1. Which module in Python supports regular expressions [ ]


a) re
b) regex
c) pyregex
d) none of the mentioned

2 What does the function re.match do [ ]

a) matches a pattern at the start of the string


b) matches a pattern at any position in the string
c) such a function does not exist
d) none of the mentioned

3. What will be the output of the following Python code? [ ]

sentence = 'we are humans'

matched = re.match(r'(.*) (.*?) (.*)', sentence)

print(matched.groups())

a) (‘we’, ‘are’, ‘humans’)


b) (we, are, humans)
c) (‘we’, ‘humans’)
d) ‘we are humans’

4. ________ matches the start of the string. [ ]


________ matches the end of the string.
a) ‘^’, ‘$’
b) ‘$’, ‘^’
c) ‘$’, ‘?’
d) ‘?’, ‘^’

5. What will be the output of the following Python code? [ ]

import re

re.ASCII

a) 8
b) 32
c) 64
d) 256

6. The expression a{5} will match _____________ characters with the previous regular expression.
[ ]

40
a) 5 or less
b) exactly 5
c) 5 or more
d) exactly 4

7. The character Dot (that is, ‘.’) in the default mode, matches any character other than _____________
[ ]
a) caret
b) ampersand
c) percentage symbol
d) newline

8. What will be the output of the following Python function? [ ]

re.findall("hello world", "hello", 1)

a) [“hello”]
b) [ ]
c) hello
d) hello world

9. Which of the following functions results in case insensitive matching? [ ]


a) re.A
b) re.U
c) re.I
d) re.X

100. What will be the output of the following Python code? [ ]

sentence = 'horses are fast'

regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')

matched = re.search(regex, sentence)

print(matched.group(2))

a) {‘animal’: ‘horses’, ‘verb’: ‘are’, ‘adjective’: ‘fast’}


b) (‘horses’, ‘are’, ‘fast’)
c) ‘horses are fast’
d) ‘are’

FILL IN THE BLANKS

1. ____________are basic web clients.

2. A _________________is a collection of instances of the components like buttons,checkboxes,menus etc.

3. A_________ is used to make sure that only one thread has access to a particular resource at a given time.

4. Canvas is used to _______________

5.___________module is the commonly used for developing GUI


41
6._________________ is a set of standars that define a standard way of passing information.

7.CGI stands foer___________________

8.Simple web surfing involves using web addresses called _____________

9.Widgets are_________________

10. A________________is a unwanted state of program which occurs when a system performs two or more
operations simultaneously.

Key:

S.No MCQ Fill in Blanks

10

42
15.PREVIOUS QUESTION PAPER

43
44
45
46
16.ASSIGNMENT TOPICS

MID 1

1. Explain Modules and built in functions with syntax and example?

2. Explain in detail about Sequence data type of the set Types and Tuples

3. Explain Exceprtion Handling?

4. Explain Regular Expressions?

MID 2

1. Design Simple web clients in python by web surfing.

2. Relate Multithreading and Global interpreter lock


3. Examine CGI-Helping Servers Process Client Data?

4. Develop python Database Application Programmer’s interface(DB-API)

47
17.UNIT WISE QUESTION BANK

48

You might also like