0% found this document useful (0 votes)
12 views68 pages

Python

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

Python

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

III B.

Sc SEMESTER V Application Development using Python

B.Sc (V Semester)
Application Development using Python

UNIT-I

Python basics, Objects – Python Objects, Standard Types, Other Built-in Types, Internal Types,
Standard Type Operators, Standard Type Built-in Functions, Categorizing the Standard Types,
Unsupported Types.
Numbers – Introduction to Numbers, Integers, Floating Point Real Numbers, Complex
Numbers, Operators, Built-in Functions.
Sequences – Strings, Lists, and Tuples, Dictionaries and Set Types.
Control Flow, Truthiness, Sorting, List Comprehensions, Generators and Iterators.

UNIT-II

Files – File Objects, File Built-in Function ( open()), File Built-in Methods, File Built-in
Attributes, Standard Files, Command-line Arguments, File System, File Execution.

Exceptions – Exceptions in Python, Detecting and Handling Exceptions, Context Management,


Exceptions as Strings, Raising Exceptions, Assertions, Standard Exceptions.

Modules – Modules and Files, Namespaces, Importing Modules, Importing Module Attributes,
Module Built-in Functions, Packages.

UNIT-III

Regular Expressions – Introduction, Special Symbols and Characters, re and Python.

Multithreaded Programming – Introduction, Threads and Processes, Python Threads, and the
Global Interpreter Lock, Thread Module, Threading Module.

UNIT-IV

GUI Programming: Introduction, Tkinter and Python Programming, Brief Tour of Other GUIs.
Web Programming: Introduction, Web Surfing with Python, Creating Simple Web Clients,
Advanced Web Clients, CGI-Helping Servers Process Client Data, Building CGI Application,
Advanced CGI, Web (HTTP) Servers.

UNIT-V

Database Programming: Introduction, Python Database Application Programmer’s Interface


(DBAPI), Object Relational Managers (ORMs).

Text Book(s)
1. Core Python Programming, Wesley J. Chun, Second Edition, Pearson.
2. Think Python, Allen Downey, Green Tea Press.

Zenex Vision Degree College Phno:9515786774, 965250444. 1


III B.Sc SEMESTER V Application Development using Python

UNIT-I

INTRODUCTION

 Python is a general-purpose interpreted, interactive, object-oriented, and high-


level programming language. It was created by Guido van Rossum during 1985-
1990. Like Perl, Python source code is also available under the GNU General
Public License (GPL).
 It supports Object Oriented programming approach to develop applications. It is
simple and easy to learn and provides lots of high-level data structures.
 Python is easy to learn yet powerful and versatile scripting language, which
makes it attractive for Application Development
 It is used to create web applications and workflows
 Python can connect to database systems. It can also read and modify files.
 It is used to handle big data and perform complex mathematics.
 It can be used for rapid prototyping, or for production-ready software
development.

FEATURES

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon
as it is written.
 Python can be treated in a procedural way, an object-oriented way or a functional
way.

 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope
of loops, functions and classes. Other programming languages often use curly-
brackets for this purpose.

Zenex Vision Degree College Phno:9515786774, 965250444. 2


III B.Sc SEMESTER V Application Development using Python

STANDARD TYPES

Python's standard types, also referred to as built-in data types, categorize various kinds of
data that can be manipulated within the language. Every piece of data in Python is an
object, and these standard types represent the classes from which these objects are
instantiated.
Numeric types:
 int: Represents integer numbers (e.g., 5, -100).
 float: Represents floating-point numbers (e.g., 3.14, 2.0).
 complex: Represents complex numbers (e.g., 3 + 4j).

Sequence types:
 str: Represents sequences of characters (text) (e.g., "hello", 'Python').
 list: Represents ordered, mutable sequences of items (e.g., [1, 2, "three"]).
 tuple: Represents ordered, immutable sequences of items (e.g., (1, 2, "three")).
 range: Represents an immutable sequence of numbers, often used in loops
(e.g., range(5)).

Mapping type:
 dict: Represents unordered collections of key-value pairs (e.g., {"name": "Alice",
"age": 30}).

Set types:
 set: Represents unordered collections of unique, mutable items (e.g., {1, 2, 3}).
 frozenset: Represents unordered collections of unique, immutable items.

Boolean type:
 bool: Represents truth values, either True or False.

Binary types:
 bytes: Represents immutable sequences of bytes.
 bytearray: Represents mutable sequences of bytes.
 memoryview: Provides a memory-efficient way to access the memory of other
binary objects.

Zenex Vision Degree College Phno:9515786774, 965250444. 3


III B.Sc SEMESTER V Application Development using Python

BUILT-IN TYPES

Modules

The only special operation on a module is attribute access: m.name, where m is a module
and name accesses a name defined in m’s symbol table. Module attributes can be
assigned to

Classes and Class Instances


Functions

Function objects are created by function definitions. The only operation on a function
object is to call it: func(argument-list).

There are really two flavors of function objects: built-in functions and user-defined
functions. Both support the same operation (to call the function), but the implementation
is different, hence the different object types.

Methods

Methods are functions that are called using the attribute notation. There are two
flavors: built-in methods (such as append() on lists) and class instance method

Code Objects

Code objects are used by the implementation to represent “pseudo-compiled” executable


Python code such as a function body. They differ from function objects because they
don’t contain a reference to their global execution environment. Code objects are
returned by the built-in compile() function and can be extracted from function objects
through their code attribute.

A code object can be executed or evaluated by passing it to the exec() or eval() built-in
functions.

Type Objects

Type objects represent the various object types. An object’s type is accessed by the built-
in function type(). There are no special operations on types. The standard
module types defines names for all standard built-in types.

Types are written like this: <class 'int'>.

Zenex Vision Degree College Phno:9515786774, 965250444. 4


III B.Sc SEMESTER V Application Development using Python

The Null Object

Returned by functions that don’t explicitly return a value. It supports no special


operations. There is exactly one null object, named None (a built-in name). type(None)
() produces the same singleton.

It is written as None.

The Ellipsis Object

 Commonly used by slicing.


 It supports no special operations.

There is exactly one ellipsis object, named Ellipsis (a built-in name). type(Ellipsis)
() produces the Ellipsis singleton.

The NotImplemented Object

Returned from comparisons and binary operations when they are asked to operate on
types they don’t support.It is written as NotImplemented.

Internal Objects
It defines about stack frame objects, traceback objects and slice objects

INTERNAL TYPES

In Python, "internal types" generally refer to objects that are part of the interpreter's
internal workings and are not commonly manipulated directly by typical application
programmers. These types are distinct from the standard built-in data types like integers,
strings, lists, or dictionaries.
The most prominent internal types include:
 Code Objects:
These represent byte-compiled executable pieces of Python source code. They are
typically created by the compile() built-in function or found as attributes of function
objects (e.g., function.__code__). Code objects encapsulate the instructions but do not
contain execution environment details.
 Frame Objects:
A frame object represents an execution frame in the Python call stack. It holds
information about the state of a function's execution, including local variables, global

Zenex Vision Degree College Phno:9515786774, 965250444. 5


III B.Sc SEMESTER V Application Development using Python

variables, and the code object being executed within that frame. They can be accessed
through modules like sys or inspect.
 Traceback Objects:
These objects are created when an exception occurs and contain information about the
call stack at the time of the exception, allowing for debugging and error reporting.
 Slice Objects:
Created when using the slicing syntax (e.g., [start:stop:step]), these objects encapsulate
the start, stop, and step values used for sequence slicing.
 Ellipsis Object:
Represented by ..., this is a singleton object primarily used in numerical computing
libraries like NumPy for advanced indexing and in type hints to indicate an arbitrary
number of arguments or dimensions.
 Type Objects:
The type object itself represents the type of an object. For example, type(1) returns
the int type object. Type objects are callable and can be used to create new instances of
that type.
While these internal types are fundamental to Python's operation, direct interaction with
them is usually reserved for advanced tasks like introspection, debugging, or building
custom tools that manipulate the interpreter's behavior.
STANDARD TYPE OPERATORS
Python includes several categories of standard operators used to perform operations on
variables and values. These categories are:
1. Arithmetic Operators:
Used for mathematical calculations.
 + (Addition)
 - (Subtraction)
 * (Multiplication)
 / (Division - returns float)
 // (Floor Division - returns integer)
 % (Modulus - returns remainder)
 ** (Exponentiation)

2. Assignment Operators:
Used to assign values to variables.

Zenex Vision Degree College Phno:9515786774, 965250444. 6


III B.Sc SEMESTER V Application Development using Python

= (Assignment), += (Addition assignment), -= (Subtraction assignment), *=


(Multiplication assignment), /= (Division assignment), //= (Floor division assignment),
%= (Modulus assignment), and **= (Exponentiation assignment).
3. Comparison (Relational) Operators:
Used to compare two values and return a Boolean result (True or False).
 == (Equal to)
 != (Not equal to)
 > (Greater than)
 < (Less than)
 >= (Greater than or equal to)
 <= (Less than or equal to)

4. Logical Operators:
Used to combine conditional statements. and (Logical AND), or (Logical OR), and not
(Logical NOT).
5. Identity Operators:
Used to check if two variables refer to the same object in memory. is and is not.
6. Membership Operators:
Used to check if a value is present within a sequence (e.g., string, list, tuple). in and not
in.
7. Bitwise Operators:
Used to perform operations on the individual bits of integer operands.
& (Bitwise AND), | (Bitwise OR), ^ (Bitwise XOR), ~ (Bitwise NOT), << (Left shift),
and >> (Right shift).
BUILT-IN FUNCTIONS
Python includes a set of "standard type built-in functions" that operate on various
fundamental data types and are always available for use without requiring any
imports. These functions provide core functionalities for working with numbers, strings,
collections, and other basic object types.
Type Conversion and Representation:
 int(), float(), str(), list(), tuple(), dict(), set(): Used to convert values to their
respective data types or create new instances of these types.
 bool(): Converts a value to its boolean equivalent.

Zenex Vision Degree College Phno:9515786774, 965250444. 7


III B.Sc SEMESTER V Application Development using Python

 repr(): Returns a "developer-friendly" string representation of an object.


 type(): Returns the type of an object.

Mathematical Operations:
 abs(): Returns the absolute value of a number.
 min(), max(): Return the minimum or maximum value from an iterable.
 sum(): Calculates the sum of elements in an iterable.
 round(): Rounds a number to a specified number of decimal places.
 pow(): Returns the result of a number raised to a power.

Collection Operations:
 len(): Returns the number of items in an object (e.g., length of a string, number
of elements in a list).
 sorted(): Returns a new sorted list from the elements of an iterable.
 reversed(): Returns a reverse iterator.
 enumerate(): Adds a counter to an iterable, returning an enumerate object.
 zip(): Combines multiple iterables element-wise.

Utility Functions:
 print(): Outputs data to the console.
 input(): Reads input from the user.
 help(): Provides help information about an object.
 dir(): Returns a list of names in the current scope or attributes of an object.
 These are just a few examples, as Python offers a comprehensive set of built-in
functions to streamline common programming tasks across its standard data types.
CATEGORIZIING THE STANDARD TYPE
Python's standard built-in types can be categorized into several main groups based on
their characteristics and how they store and manage data.
 Numeric Types:
These represent numerical values.
int: Integers (whole numbers, positive, negative, and zero).
float: Floating-point numbers (numbers with decimal points).
complex: Complex numbers, consisting of a real and an imaginary part (e.g., 3 +
4j).

Sequence Types:
These represent ordered collections of items.

Zenex Vision Degree College Phno:9515786774, 965250444. 8


III B.Sc SEMESTER V Application Development using Python

 str: Strings (sequences of Unicode characters). Strings are immutable.


 list: Lists (ordered, mutable collections of items). Items can be of different data
types.
 tuple: Tuples (ordered, immutable collections of items). Similar to lists but
cannot be modified after creation.
 range: Immutable sequences of numbers, often used in loops.

Mapping Types:
These represent collections of key-value pairs.
 dict: Dictionaries (unordered, mutable collections of unique keys mapped
to values).

Set Types:
These represent unordered collections of unique elements.
 set: Sets (unordered, mutable collections of unique elements).
 frozenset: Immutable versions of sets.

Boolean Type:
 bool: Represents truth values, either True or False.

Binary Types:
These handle binary data.
 bytes: Immutable sequences of bytes.
 bytearray: Mutable sequences of bytes.
 memoryview: Provides a "view" into another object's memory, allowing
access to its binary data without copying.

None Type:
 NoneType: Represents the absence of a value. The sole value of this type
is None.

UNSUPPORTED TYPES

In Python, the concept of "unsupported types" typically refers to situations where an


operation is attempted on data types that are not compatible with that operation, leading
to a TypeError. Python is a strongly typed language, meaning that the type of a variable is
important, and operations are generally type-specific.

Zenex Vision Degree College Phno:9515786774, 965250444. 9


III B.Sc SEMESTER V Application Development using Python

 Unsupported Operations between Different Data Types:

Arithmetic operations: Attempting to perform arithmetic operations (like +, -, *, /)


between incompatible types, such as adding a string and an integer.

Logical operations:
Applying logical operators (and, or, not) in ways that are not intended for certain data
types, although Python often handles truthiness for various types.
Comparison operations:
While many types can be compared, some comparisons between fundamentally
different types might lead to unexpected behavior or errors in specific contexts.

Operations on NoneType:

o None is a special constant representing the absence of a value. Operations


on NoneType with other types (e.g., arithmetic with numbers or concatenation with
strings) are generally unsupported.

 Incorrect Use of Methods or Functions:


o Calling a method without parentheses when it's meant to return a value, causing the
method object itself to be used in an operation, rather than its return value.
Python

Misunderstanding Container Operations:


o Attempting to perform operations like subtraction directly on lists or other sequence
types when such operations are not defined for them in Python's built-in behavior.
Python

Resolution:
To resolve "unsupported types" errors, it is crucial to ensure that the data types involved
in an operation are compatible. This often involves:
 Type Conversion (Casting): Explicitly converting data from one type to another
(e.g., int(), str(), float()).
 Data Validation: Checking the type of variables before performing operations.
 Debugging: Tracing the origin of variables to understand their type and why they
might be incompatible.

INTRODUCTION TO NUMBERS

Zenex Vision Degree College Phno:9515786774, 965250444. 10


III B.Sc SEMESTER V Application Development using Python

Numbers are fundamental data types in Python used to store numeric values and perform
mathematical operations. Python supports three primary numeric types:

 Integers (int):

Represent whole numbers, both positive and negative, without any decimal point.

Ex
x = 10
print(type(x))
# Output: <class 'int'>

 Floating-point numbers (float):

Represent numbers with a decimal point or in scientific notation.

Ex
x = 1.23
print(type(x))
# Output: <class 'float'>

Complex numbers (complex):

The 'complex' type of number indicates that it contains both an imaginary and real
component.

Ex

x = a+2b
print(type(x))

# Output: <class 'complex'>

OPERATORS

Operators are used to perform operations on variables and values.

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators

Zenex Vision Degree College Phno:9515786774, 965250444. 11


III B.Sc SEMESTER V Application Development using Python

 Identity operators
 Membership operators
 Bitwise operators

 Arithmetic Operators:-Used for mathematical operations.


 + (Addition)
 -(Subtraction)
 (Multiplication)
 / (Division)
 % (Modulus - returns the remainder of a division)
 ** (Exponentiation - raises the first operand to the power of the second)
 // (Floor Division - divides and returns the integer part of the quotient)

 Assignment Operators:-Used to assign values to variables.


 = (Assignment)
 +=, -=, *=, /=, %=, **=, //= (Combined arithmetic and assignment)

 Comparison Operators:-Used to compare two values and return a Boolean


result (True or False).
 == (Equal to)
 != (Not equal to)
 (Greater than)
 < (Less than)
 >= (Greater than or equal to)
 <= (Less than or equal to)

 Logical Operators:-Used to combine conditional statements.


 and (Logical AND)
 or (Logical OR)
 not (Logical NOT)

 Bitwise Operators:-Used to perform operations at the binary (bit) level on


integers.
 & (Bitwise AND)
 | (Bitwise OR)
 ^ (Bitwise XOR)
 ~ (Bitwise NOT)
 << (Left shift)
 >> (Right shift)

Zenex Vision Degree College Phno:9515786774, 965250444. 12


III B.Sc SEMESTER V Application Development using Python

 Membership Operators:-Used to test whether a value exists within a sequence


(e.g., string, list, tuple).

 in
 not in

 Identity Operators:-Used to check if two variables refer to the exact same


object in memory.
 is
 is not

BUILT-IN FUNCTIONS
Type Conversion:
 int(): Converts a value to an integer.
 float(): Converts a value to a floating-point number.
 str(): Converts a value to a string.
 list(), tuple(), dict(), set(): Convert iterables to their respective collection types.

Mathematical Operations:
 abs(): Returns the absolute value of a number.
 min(): Returns the smallest item in an iterable or the smallest of two or more
arguments.
 max(): Returns the largest item in an iterable or the largest of two or more
arguments.
 sum(): Calculates the sum of all items in an iterable.
 round(): Rounds a number to a specified number of decimal places.
 pow(): Returns the result of a number raised to a power.

Iterables and Iterators:


 len(): Returns the number of items in an object (e.g., string, list, tuple).
 range(): Generates a sequence of numbers.
 sorted(): Returns a new sorted list from the items in an iterable.
 reversed(): Returns a reversed iterator.
 enumerate(): Adds a counter to an iterable and returns it as an enumerate object.
 zip(): Combines multiple iterables into an iterator of tuples.

Input/Output:
 print(): Prints objects to the console.
 input(): Reads input from the user.

Zenex Vision Degree College Phno:9515786774, 965250444. 13


III B.Sc SEMESTER V Application Development using Python

Object Inspection and Manipulation:

 type(): Returns the type of an object.


 isinstance(): Checks if an object is an instance of a specified class.
 hasattr(), getattr(), setattr(), delattr(): Functions for attribute handling.

SEQUENCES

Strings

Strings in python are denoted by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
Ex
a = "Hello"
print(a)
List
o Lists are used to store multiple items in a single variable.
o Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
o Lists are created using square brackets:
o List items are ordered, changeable, and allow duplicate values.
Ex
List1=[“abc”,23,’Male’]
print(a[2])
#Output: Male
Tuple

o Tuples are used to store multiple items in a single variable.


o Tuple is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Set, and Dictionary, all with different qualities and usage.
o A tuple is a collection which is ordered and unchangeable.
o Tuples are written with round brackets.
Ex
a = ("apple", "banana", "cherry")
print(a)
#Output:”apple”,”banana”,”cherry”

Dictionaries

o Dictionaries are used to store data values in key:value pairs.

Zenex Vision Degree College Phno:9515786774, 965250444. 14


III B.Sc SEMESTER V Application Development using Python

o A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.
o Dictionaries are written with curly brackets, and have keys and values:

Ex
x = {"brand": "Ford","model": "Mustang","year": 1964}
print(x)
#Output:{“brand": "Ford", "model": "Mustang", "year": 1964}

Set types

o Sets are used to store multiple items in a single variable.


o Set is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
o A set is a collection which is unordered, unchangeable*, and unindexed.
o Sets are written with curly brackets.

Ex

a = {1,2,3,3}
print(a)

#Output:{1,2,3}

CONTROL FLOW

Control flow in Python dictates the order in which instructions within a program are
executed. It allows for dynamic and responsive programs by enabling conditional
execution and repetitive tasks.
The main control flow constructs in Python include:
CONDITIONAL STATEMENTS (SELECTION):
These allow different blocks of code to be executed based on whether a certain
condition is true or false.
 if: Executes a block of code only if the condition is true.
 if-else: Executes one block if the condition is true, and another if it's false.
 if-elif-else: Handles multiple conditions, checking them sequentially.

Ex
marks=80

Zenex Vision Degree College Phno:9515786774, 965250444. 15


III B.Sc SEMESTER V Application Development using Python

result=””
If marks < 30:
result=”Failed”
eleif marks > 70:
result = “first division”
else:
result = “Passed”
print(result)
Output: first division

 match-case: A more recent addition for pattern matching and executing code based
on matching patterns.

Ex
defcheckVowel(n):
match n:
case ’a’: return ‘Vowel’
case ’e’: return ‘Vowel’
case ’i’: return ‘Vowel’
case ’o’: return ‘Vowel’
case ’u’: return ‘Vowel’
case _: return ‘not a Vowel’
print(checkVowel(‘a’))
print(checkVowel(‘e’))
print(checkVowel(‘m’))

Output: Vowel
Vowel
Not a Vowel

LOOPS (REPETITION):
 for loop: Iterates over a sequence (e.g., list, tuple, string, range) for each item.
Ex
numbers = [1,2,3,4,]
for x in numbers:
print(x)
Output: 1
2
3
4

Zenex Vision Degree College Phno:9515786774, 965250444. 16


III B.Sc SEMESTER V Application Development using Python

 while loop: Repeatedly executes a block of code as long as a given condition


remains true.
Ex
i=1
while i < =4:
print(i)
i+=1
Output: 1
2
3
4

Control Flow Keywords:


These modify the behavior of loops.
 break: Terminates the current loop and transfers control to the statement
immediately following the loop.
 continue: Skips the rest of the current iteration of the loop and proceeds to the next
iteration.
 pass: A null operation; it does nothing. It's often used as a placeholder where a
statement is syntactically required but no action is desired.

TRUTHINESS

In Python, "truthiness" refers to the concept that every object has an inherent Boolean
value when evaluated in a Boolean context, such as in if statements, while loops, or
Boolean operations (and, or, not). This means that objects are implicitly converted
to True or False based on certain rules.
Rules
Falsy Values:
 Numeric Zero: 0, 0.0, 0j (complex zero).
 Empty Sequences and Collections: Empty strings (""), empty lists
([]), empty tuples (()), empty dictionaries ({}), empty sets (set()).
 None: The None object explicitly represents the absence of a value
and is always falsy.
 False: The Boolean literal False.

Truthy Values:

Zenex Vision Degree College Phno:9515786774, 965250444. 17


III B.Sc SEMESTER V Application Development using Python

 Non-zero Numbers: Any number other than zero (e.g., 1, -5, 3.14).
 Non-empty Sequences and Collections: Any sequence or
collection containing at least one element (e.g., "hello", [1, 2], {'a':
1}).
 True: The Boolean literal True.
 Most Custom Objects: By default, instances of custom classes are
considered truthy unless they explicitly define
a __bool__ or __len__ method that returns a falsy value.
SORTING
Python provides two primary ways to sort data:
 list.sort() method: This method sorts a list in-place, meaning it modifies the original
list directly and returns None. It is a method of the list object.

Ex

list1 = [3, 1, 4, 1, 5, 9, 2, 6]
list1.sort()
print(list)

Output: [1, 1, 2, 3, 4, 5, 6, 9]

Ex
list1.sort(reverse=True)
print(list1)

Output: [9, 6, 5, 4, 3, 2, 1, 1]

 sorted() built-in function: This function takes any iterable (like a list, tuple, string,
etc.) and returns a new sorted list, leaving the original iterable unchanged.

Ex
tuple1 = (3, 1, 4, 1, 5)
sorted_list = sorted(tuple1)
print(sorted_list)

Output: [1, 1, 3, 4, 5]
print(tuple1)
Output: (3, 1, 4, 1, 5) (original tuple remains unchanged)

Zenex Vision Degree College Phno:9515786774, 965250444. 18


III B.Sc SEMESTER V Application Development using Python

LIST COMPREHENSION

List comprehension in Python offers a concise and efficient way to create new lists
based on existing iterables (like lists, tuples, strings, or ranges). It provides a more
compact and often more readable alternative to traditional for loops for list creation and
transformation.

Syntax
new_list=[expression for item in iterables if condition]

COMPONENTS
expression:
This is the operation or transformation applied to each item from the iterable. The result
of this expression for each item becomes an element in the new_list.
item:
This is a temporary variable that represents each element from the iterable during the
iteration.
iterable:
This is the source sequence (e.g., a list, tuple, range, or string) from which elements are
processed.
if condition (optional):
This is a filtering condition. If present, only items that satisfy this condition are
included in the new_list.

Ex
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [num for num in numbers if num % 2 == 0]

Output:even_numbers will be [2, 4, 6]

BENEFITS

Conciseness: Reduces the amount of code needed to create lists.


Readability: Often makes the code easier to understand, especially for simple
transformations and filtering.
Efficiency: Can be more performant than equivalent for loops in many cases due to
internal optimizations.

GENERATORS & ITERATORS

Zenex Vision Degree College Phno:9515786774, 965250444. 19


III B.Sc SEMESTER V Application Development using Python

A generator function is a special type of function that returns an iterator object. Instead of
using return to send back a single value, generator functions use yield to produce a series
of results over time. This allows the function to generate values and pause its execution
after each yield, maintaining its state between iterations.

Key characteristics of Python generators:

Lazy Evaluation:

Generators compute and yield values only when requested, rather than pre-calculating
and storing all values. This conserves memory, especially for large or infinite sequences.

yield keyword:

Generators are defined using the yield keyword instead of return. When a yield statement
is encountered, the generator pauses its execution, returns the yielded value, and saves its
state. When the generator is subsequently called (e.g., using next()), it resumes execution
from where it left off.

Iterator Protocol:

Generators automatically implement the iterator protocol, meaning they can be iterated
over using for loops or other iteration mechanisms.

Generator Expressions:

Similar to list comprehensions, generator expressions provide a concise way to create


generators. They use parentheses () instead of square brackets [].

Example:

def count_up_to(n):
i=0
while i <= n:
yield i
i += 1
gen= count_up_to(5)
for num in gen:
print(num)

Output

Zenex Vision Degree College Phno:9515786774, 965250444. 20


III B.Sc SEMESTER V Application Development using Python

1
2
3
4
5

Yield vs Return

Yield:

 is used in generator functions to provide a sequence of values over time.

 When yield is executed, it pauses the function, returns the current value and retains
the state of the function.

 This allows the function to continue from same point when called again, making it
ideal for generating large or complex sequences efficiently.

Return:

 is used to exit a function and return a final value.


 Once return is executed, function is terminated immediately and no state is
retained.
 This is suitable for cases where a single result is needed from a function.

Ex

def fun():

return 1 + 2 + 3

res = fun()

print(res)

Output: 6

ITERATORS

An iterator in Python is an object used to traverse through all the elements of a collection
(like lists, tuples, or dictionaries) one element at a time. It follows the iterator protocol,
which involves two key methods:

Zenex Vision Degree College Phno:9515786774, 965250444. 21


III B.Sc SEMESTER V Application Development using Python

 __iter__(): Returns the iterator object itself.

 __next__(): Returns the next value from the sequence. Raises StopIteration when
the sequence ends.

Characteristics

 Lazy Evaluation : Processes items only when needed, saving memory.

 Generator Integration : Pairs well with generators and functional tools.

 StatefulTraversal : Remembers position between calls.

 Uniform Looping : Works across data types with the same syntax.

 ComposableLogic : Easily build complex pipelines using tools like itertools.

Ex

mystr = "banana"
myit = iter(mystr)
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))
print(next(myit))

print(next(myit))

Output

Zenex Vision Degree College Phno:9515786774, 965250444. 22


III B.Sc SEMESTER V Application Development using Python

UNIT-II

FILE OPERATIONS

The file is a named location on the disk to store related information, as the file is having
some name and location, it is stored in the hard disk. In Python, file operation is
performed in the following order –

 Opening a file.
 Read or Write operation.
 Closing a file.

Opening a File Using the 'open()' function

To open a file for both reading and writing, we must use the built-in open() function.
The open() function uses two arguments. First is the name of the file and second is the
mode (reading or, writing).

Syntax

File_obj = open("filename", "mode")

Python File Modes

A file can be opened with a built-in function called open(). This function takes in the
file’s address and the access_mode and returns a file object. There are different types
of access_modes:

r: Opens a file for reading only


r+: Opens a file for both reading and writing
w: Opens a file for writing only

Zenex Vision Degree College Phno:9515786774, 965250444. 23


III B.Sc SEMESTER V Application Development using Python

w+: Open a file for writing and reading.


a: Opens a file for appending
a+: Opens a file for both appending and reading

read([size]): It reads the entire file and returns it contents in the form of a string.
Reads at most size bytes from the file. If the size argument is negative or omitted, read
all data until EOF is reached.

Example
f = open(__file__, 'r')

text = f.read(10)

print(text)
f.close()

readline([size]): It reads the first line of the file i.e till a newline character or an EOF
in case of a file having a single line and returns a string. If the size argument is present
and non-negative, it is a maximum byte count and an incomplete line may be returned.
An empty string is returned only when EOF is encountered immediately.

Example
f = open(__file__, 'r')

text = f.readline(20)
print(text)
f.close()

write(string): It writes the contents of string to the file. It has no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.

Example
f = open(__file__, 'w')
line = 'Welcome Geeks\n'

Zenex Vision Degree College Phno:9515786774, 965250444. 24


III B.Sc SEMESTER V Application Development using Python

f.write(line)
f.close()

FILE BUILT-IN METHODS

Python supports file handling and allows users to handle files i.e., to read and write files,
along with many other file handling options, to operate on files. For this, python provides
following built–in functions, those are

 close()
 read()
 readline()
 write()
 writelines()
 tell()
 seek()

close()

The close() method used to close the currently opened file, after which no more writing
or reading can be done.
Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() method to close a file.
Syntax:

Fileobject.close()

read()

The read () method is used to read the content from file. To read a file in Python, we must
open the file in reading mode.
Syntax:

Zenex Vision Degree College Phno:9515786774, 965250444. 25


III B.Sc SEMESTER V Application Development using Python

Fileobject.read([size])

readline()

Python facilitates us to read the file line by line by using a function readline(). The
readline() method reads the lines of the file from the beginning, i.e., if we use the
readline() method two times, then we can get the first two lines of the file.
Syntax:
Fileobject.readline()
fileptr.close();

write()

The write () method is used to write the content into file. To write some text to a file, we
need to open the file using the open method with one of the following access modes.
Syntax:
Fileobject.write(content)

writelines()

The writelines () method is used to write multiple lines of content into file. To write some
lines to a file
Syntax:
Fileobject.writelines(list)

File Positions

Methods that set or modify the current position within the file

tell()

Zenex Vision Degree College Phno:9515786774, 965250444. 26


III B.Sc SEMESTER V Application Development using Python

The tell() method returns the current file position in a file stream. You can change the
current file position with the seek() method.
Syntax:
Fileobject.tell()

seek()

The seek() method sets and returns the current file position in a file stream.
Syntax:
Fileobject.seek(offset)

FILE BUILT-IN ATRRIBUTES

In Python, when a file is opened using the open() built-in function, it returns a file
object. This file object possesses several built-in attributes that provide information about
the file and its state. These attributes are distinct from general file system attributes

 name: This attribute stores the name of the file, including its path if provided during
opening.

Example
file_object = open("example.txt", "r")
print(file_object.name)
file_object.close()

mode: This attribute indicates the access mode with which the file was opened

Example
file_object = open("example.txt", "w")
print(file_object.mode)
file_object.close()

 closed: This is a boolean attribute that indicates whether the file is currently closed
(True) or open (False).

Example

Zenex Vision Degree College Phno:9515786774, 965250444. 27


III B.Sc SEMESTER V Application Development using Python

file_object = open("example.txt", "r")


print(file_object.closed)
file_object.close()
print(file_object.closed)

 encoding: If the file is opened in text mode, this attribute specifies the encoding used
(e.g., 'utf-8', 'latin-1'). It is None for binary files.

Example

file_object = open("example.txt", "r", encoding="utf-8")


print(file_object.encoding)
file_object.close()

PYTHON SOURCE FILES (.PY):


These are the most common and fundamental "standard files" in Python. They are plain
text files containing Python code and typically have the .py extension. These files are
executed by the Python interpreter.
 Standard Data File Formats:
Python provides built-in or easily accessible modules to work with various standard
data file formats for storing and exchanging data. Examples include:
 Text Files: Basic text files, often with the .txt extension, are widely used for human-
readable data. Python's open() function handles these directly.
 CSV (Comma Separated Values) Files: Used for tabular data, where values are
separated by commas. The csv module in the standard library provides tools for reading
and writing these files.
 JSON (JavaScript Object Notation) Files: A lightweight data-interchange
format. The json module allows for easy serialization and deserialization of Python
objects to and from JSON.
 XML (Extensible Markup Language) Files: Another widely used format for
structured data. Python's xml.etree.ElementTree module is part of the standard library
for working with XML.

COMMAND LINE ARGUMENTS

Command Line Arguments provides a convenient way to accept some information at the
command line while running the program. We usually pass these values along with the
name of the Python script

Zenex Vision Degree College Phno:9515786774, 965250444. 28


III B.Sc SEMESTER V Application Development using Python

Syntax

python script.py arg1 arg2

Example

name = input(“Enter ur name:”)

print(“Hello {}. How are you?”.format(name))

To run above code

C:\Python311>python hello.py

ACCESSING COMMAND LINE ARGUMENTS:


The most fundamental way to access command line arguments in Python is through
the sys module, specifically sys.argv.
 sys.argv: This is a list containing all the command line arguments.
o sys.argv[0] always represents the name of the script being executed.
o Subsequent elements (sys.argv[1], sys.argv[2], etc.) represent the arguments passed by
the user.
Example(greet.py)
import sys
if len(sys.argv) > 1:
name = sys.argv[1]
print(f"Hello, {name}!")
else:
print("Please provide a name as a command line argument.")

To run the code

python greet.py Akhil

Output

Hello Akhil

FILE SYSTEM

Python offers robust capabilities for interacting with the underlying operating system's
file system through various built-in modules. The primary modules for file system
manipulation in Python are:

Zenex Vision Degree College Phno:9515786774, 965250444. 29


III B.Sc SEMESTER V Application Development using Python

 OS module:
This module provides a way of using operating system dependent functionality. It
includes functions for interacting with the file system, such as:
 Path
manipulation: os.path.join(), os.path.exists(), os.path.isdir(), os.path.isfile(), os.path.sp
lit(), os.path.basename(), os.path.dirname().
 Directory
operations: os.mkdir(), os.makedirs(), os.rmdir(), os.removedirs(), os.listdir(), os.getcw
d(), os.chdir().
 File operations: os.rename(), os.remove().
 Process management: os.system(), os.spawn().
 pathlib module:this module provides an object-oriented approach to file system paths,
offering a more modern and user-friendly interface compared to os.path. Key features
include:
 Representing paths as Path objects.
 Methods for checking file/directory existence (.exists(), .is_file(), .is_dir()),
creating/deleting (.mkdir(), .rmdir(), .unlink()), renaming (.rename()), and joining paths
(/ operator).
 shutil module:This module provides higher-level file operations, including:
 Copying files and directories: shutil.copy(), shutil.copyfile(), shutil.copytree().
 Moving files and directories: shutil.move().
 Deleting directory trees: shutil.rmtree().

Built-in open() function:


This fundamental function is used for opening files for reading, writing, or appending
data. It returns a file object that can be used to perform file I/O operations

Example

import os
from pathlib import Path
file_name_os = "my_text_file_os.txt"
with open(file_name_os, "w") as f:
f.write("Hello from os module!\n")
if os.path.exists(file_name_os):
print(f"File '{file_name_os}' exists.")

file_path_pathlib = Path("my_text_file_pathlib.txt")

Zenex Vision Degree College Phno:9515786774, 965250444. 30


III B.Sc SEMESTER V Application Development using Python

file_path_pathlib.write_text("Hello from pathlib module!\n")

if file_path_pathlib.is_file():
print(f"File '{file_path_pathlib.name}' exists.")

FILE EXECUTION

Running a Python file, also known as executing a Python script, can be achieved through
various methods depending on your environment.
1. Using the Command Line or Terminal:
This is the most common and fundamental way to run a Python file.
 Open a terminal or command prompt:
Navigate to the directory where your Python file (e.g., my_script.py) is saved.
 Execute the script:
Type python my_script.py and press Enter.
 On some systems, especially Linux, you might need to use python3
my_script.py if python defaults to an older version.
 On Windows, py my_script.py can often be used as an alternative to python.

2. Using an Integrated Development Environment (IDE) or Code Editor:


IDEs like PyCharm, VS Code, or Sublime Text provide built-in functionalities to run
Python files.
 Open the file: Open your Python file within the IDE or editor.
 Run command/button: Most IDEs offer a "Run" button (often a play icon) or a specific
command (e.g., "Run Python File in Terminal" in VS Code) that executes the active
Python file.
 Run selection/line: You can often select specific lines or blocks of code and run them
independently within the IDE's integrated terminal.
3. Using Online Platforms:
Several online platforms allow you to write and run Python code directly in your web
browser without local installation. Examples include Google Colab, Replit,
PythonAnywhere, and OnlineGDB.
 Create/Upload file: Create a new Python file or upload an existing one on the platform.

Zenex Vision Degree College Phno:9515786774, 965250444. 31


III B.Sc SEMESTER V Application Development using Python

 Run code: Use the platform's interface to execute the code.

EXCEPTIONS

Python Exception Handling handles errors that occur during the execution of a
program. Exception handling allows to respond to the error, instead of crashing the
running program. It enables you to catch and manage errors, making your code more
robust and user-friendly.
 Error: Errors are serious issues that a program should not try to handle. They are
usually problems in the code's logic or configuration and need to be fixed by the
programmer. Examples include syntax errors and memory errors.
 Exception: Exceptions are less severe than errors and can be handled by the
program. They occur due to situations like invalid input, missing files or network
issues.

Advantages of Exception Handling:


 Improved program reliability: By handling exceptions properly, you can prevent
your program from crashing or producing incorrect results due to unexpected errors
or input.
 Simplified error handling: Exception handling allows you to separate error
handling code from the main program logic, making it easier to read and maintain
your code.
 Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.
 Easier debugging: When an exception is raised, the Python interpreter prints a
traceback that shows the exact location where the exception occurred, making it
easier to debug your code.
Disadvantages of Exception Handling:
 Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to
catch and handle the exception.
 Increased code complexity: Exception handling can make your code more
complex, especially if you have to handle multiple types of exceptions or
implement complex error handling logic.
 Possible security risks: Improperly handled exceptions can potentially reveal
sensitive information or create security vulnerabilities in your code, so it's

Zenex Vision Degree College Phno:9515786774, 965250444. 32


III B.Sc SEMESTER V Application Development using Python

important to handle exceptions carefully and avoid exposing too much information
about your program.

Example(Exception)
n = 10
try:
res = n /
print("Can't be divided by zero!")
Output
Can’t be divided by zero!
Error(Example)
print("Hello world" # Missing closing parenthesis
n = 10
res = n / 0
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1
print("Hello world" # Missing closing parenthesis ^
SyntaxError: '(' was never closed

Key concepts of Python exceptions:


 Raising Exceptions:
When an error or an exceptional condition is encountered, an exception is "raised." This
stops the normal execution of the program at that point.
Example
def set(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print(f"Age set to {age}")

Zenex Vision Degree College Phno:9515786774, 965250444. 33


III B.Sc SEMESTER V Application Development using Python

try:
set(-5)
except ValueError as e:
print(e)
Output
Age cannot be negative.

 Exception Objects:
Exceptions are represented by Python objects, which are instances of classes derived
from BaseException.
 Handling Exceptions:
Exceptions can be caught and handled using try, except, else, and finally blocks.
 The try block contains the code that might raise an exception.
 The except block specifies the type of exception to catch and contains the code to
execute if that exception occurs within the try block. Multiple except blocks can be
used to handle different exception types.
 The else block (optional) executes if no exception is raised in the try block.
 The finally block (optional) always executes, regardless of whether an exception
occurred or was handled. It is commonly used for cleanup operations.

Example
try:
n=0
res = 100 / n

except ZeroDivisionError:
print("You can't divide by zero!")

except ValueError:
print("Enter a valid number!")

else:
print("Result is", res)

finally:
print("Execution complete.")

Zenex Vision Degree College Phno:9515786774, 965250444. 34


III B.Sc SEMESTER V Application Development using Python

Output
You can't divide by zero!
Execution complete.

Built-in Exceptions:
Python provides a rich hierarchy of built-in exception classes for common error
conditions, such as ValueError, TypeError, FileNotFoundError, ZeroDivisionError, and
many more.
Custom Exceptions:
Developers can define their own custom exception classes by inheriting from existing
exception classes (typically Exception) to represent specific error conditions in their
applications.
raise statement:
The raise keyword is used to explicitly raise an exception in your code, either a built-in
one or a custom one.

CONTEXT MANAGEMENT
Context management in Python refers to the ability to manage resources within a
controlled block of code, ensuring that resources are properly initialized and cleaned up,
even if exceptions occur. This is primarily achieved through context managers and
the with statement.
Key Concepts:
 Context Managers:
These are objects that define a runtime context for a block of code. They implement the
context manager protocol, which involves two special methods:
 __enter__(self): This method is called when entering the with statement block. It
typically sets up the resource (e.g., opens a file, acquires a lock) and can return a value
that is bound to the as variable in the with statement.
 __exit__(self, exc_type, exc_value, traceback): This method is called when exiting
the with statement block, regardless of whether the block completes normally or an
exception occurs. It's responsible for cleaning up the resource (e.g., closing a file,
releasing a lock). If it returns True, it suppresses any exception that occurred within
the with block.

with Statement:
This statement provides a concise and readable way to utilize context managers.

Zenex Vision Degree College Phno:9515786774, 965250444. 35


III B.Sc SEMESTER V Application Development using Python

Syntax :
with expression as variable:
# code block

The expression evaluates to a context manager object. The __enter__ method of this
object is called, and its return value (if any) is assigned to variable. After the code
block finishes, the __exit__ method is called to ensure proper cleanup.

BENEFITS
 Resource Management:
Ensures resources like files, network connections, or database connections are properly
opened and closed, preventing resource leaks.
 Exception Handling:
Guarantees cleanup even if errors or exceptions occur within the with block.
 Code Clarity and Readability:
The with statement provides a clear and concise way to manage resources, making code
easier to understand and maintain.

EXCEPTIONS AS STRINGS

If you need to store the exception message in a string variable or concatenate it with other
strings, you can explicitly convert the exception object to a string using str().

Example
try:
value = int("abc") # This will raise a ValueError
except ValueError as e:
error_message = str(e)
print(f"An error occurred: {error_message}")

Output: An error occurred: invalid literal for int() with base 10: 'abc'

ASSERTIONS

Assertions in Python are statements used to declare that a certain condition must be true
at a specific point in the program's execution. They serve as a debugging tool, helping
developers catch logical errors and incorrect assumptions during development.

Zenex Vision Degree College Phno:9515786774, 965250444. 36


III B.Sc SEMESTER V Application Development using Python

Syntax:
assert condition, message
 condition: This is a boolean expression that is evaluated.
 message : This is a string that will be displayed if the condition evaluates to False.

Behavior:
 If condition evaluates to True, the program continues executing normally.
 If condition evaluates to False, an AssertionError is raised, and the program halts. The
optional message will be included in the AssertionError traceback.
Purpose and Use Cases:
Debugging:
Assertions are primarily used to catch internal inconsistencies or bugs that indicate a
flaw in the program's logic.
 Internal Self-Checks:
They act as internal checks to ensure that the code behaves as expected at various
stages, such as validating function inputs or intermediate results.
 Unit Testing:
Assertions are fundamental in unit testing frameworks (like unittest or pytest) to verify
that functions or methods produce the correct output for given inputs.

STANDARD EXCEPTIONS

Python supports various built-in exceptions, the commonly used exceptions are
• NameError: It occurs when a name is not found.i.e attempt to access an undeclared
variable
Example:
a=5
c=a+b
print("Sum =",c)

Output:
Traceback (most recent call last):
File "expdemo.py", line 2, in
c=a+b
NameError: name 'b' is not defined

Zenex Vision Degree College Phno:9515786774, 965250444. 37


III B.Sc SEMESTER V Application Development using Python

• ZeroDivisionError: Occurs when a number is divided by zero.


Example:
a=5
b=0
print(a/b)

Output:
Traceback (most recent call last):
File "expdemo.py", line 3, in
print(a/b)
ZeroDivisionError: division by zero

• ValueError: Occurs when an inappropriate value assigned to variable.


Example:
a=int(input("Enter a number : "))
b=int(input("Enter a number : "))
print("Sum =",a+b)

Output:
Enter a number : 23
Enter a number : abc
Traceback (most recent call last):
File "expdemo.py", line 2, in
b=int(input("Enter a number : "))
ValueError: invalid literal for int() with base 10: 'abc'

• IndexError: Occurs when we request for an out-of-range index for sequence


Example:
ls=['c','java','python']
print("list item is :",ls[5])

Output:
Traceback (most recent call last):
File "expdemo.py", line 2, in
print("list item is :",ls[5])
IndexError: list index out of range.

Zenex Vision Degree College Phno:9515786774, 965250444. 38


III B.Sc SEMESTER V Application Development using Python

• KeyError: Occurs when we request for a non-existent dictionary key


Example:
dic={"name":"Madhu","location":"Hyd"}
print("The age is :",dic["age"])

Output:
Traceback (most recent call last):
File "expdemo.py", line 2, in
print("The age is :",dic["age"])
KeyError: 'age'

• IOError: Occurs when we request for a non-existent input/output file.


Example:
fn=open("exam.py")
print(fn)

Output:
Traceback (most recent call last):
File "expdemo.py", line 1, in
fn=open("exam.py")
FileNotFoundError: [IOError] No such file or directory: 'exam.py'

MODULES

A Python 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. It
also makes the code logically organized.

Create a Module
To create a module, write the desired code and save that in a file
with .py extension
Example:
def add(x, y):
return (x+y)
def subtract(x, y):

Zenex Vision Degree College Phno:9515786774, 965250444. 39


III B.Sc SEMESTER V Application Development using Python

return (x-y)

NAMESPACES

 A namespace is basically a system to make sure that all the names in a program
are unique and can be used without any conflict.

A namespace is a system to have a unique name for each and every object in
Python. An object might be a variable or a method. Python itself maintains a
namespace in the form of a Python dictionary.

Real-time example, the role of a namespace is like a surname. One might not find
a single “Kumar” in the class there might be multiple “Kumar” but when you
particularly ask for “N Kumar” or “S Kumar” (with a surname), there will be only
one (time being don’t think of both first name and surname are same for multiple
students).
Types of namespaces

 Local Namespace: This namespace includes local names inside a function. This
namespace is created when a function is called, and it only lasts until the function
returns.
 Global Namespace: This namespace includes names from various imported
modules that you are using in a project. It is created when the module is included
in the project, and it lasts until the script ends.
 Built-in Namespace: This namespace includes built-in functions and built-in
exception names. Like print (), input (), list () and etc.

Zenex Vision Degree College Phno:9515786774, 965250444. 40


III B.Sc SEMESTER V Application Development using Python

Example

print("Namespace Example")
#built-in namespace
a=10 #global namespace
def func1():
b=20 #local namespace
print(a+b)
func1()

Output

30

IMPORTING MODULES

We can import the functions, and classes defined in a module to another module using
the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.

Syntax
import module

Zenex Vision Degree College Phno:9515786774, 965250444. 41


III B.Sc SEMESTER V Application Development using Python

Example

import calc

print(calc.add(10, 2))

Output

12

IMPORTING MODULE ATTRIBUTES

In Python, importing a module allows access to its attributes, which can include
functions, classes, variables, and other objects defined within that module. There are
several ways to import and access module attributes:
1. Importing the entire module:
Syntax
import module_name
2.Accessing attributes using the dot notation: module_name.attribute_name.
Example:
Syntax
import math
print(math.pi)
print(math.sqrt(16))
3. Importing specific attributes from a module:
Syntax
from module_name import attribute1, attribute2
4. Importing all attributes from a module :
Syntax

Zenex Vision Degree College Phno:9515786774, 965250444. 42


III B.Sc SEMESTER V Application Development using Python

from module_name import *


4. Importing a module and renaming it:
Syntax
import module_name as alias_name

5. Importing specific attributes and renaming them:

Syntax

from module_name import attribute_name as alias_name

MODULE BUILT-IN FUNCTIONS

PACKAGES

Python packages are a way to organize and structure code by grouping related modules
into directories. A package is essentially a folder that contains an __init__.py file and
one or more Python files

Components

 Module: A single Python file containing reusable code (e.g., math.py).


 Package: A directory containing modules and a special __init__.py file.
 Sub-Packages: Packages nested within other packages for deeper organization.

Create and Access packages in python

1. Create a Directory: Make a directory for your package. This will serve as the root
folder.
2. Add Modules: Add Python files (modules) to the directory, each representing
specific functionality.
3. Include __init__.py: Add an __init__.py file (can be empty) to the directory to
mark it as a package.
4. Add Sub packages (Optional): Create subdirectories with their own __init__.py
files for sub packages.
5. Import Modules: Use dot notation to import, e.g., from mypackage.module1
import greet.

Example

Zenex Vision Degree College Phno:9515786774, 965250444. 43


III B.Sc SEMESTER V Application Development using Python

math_operations/__init__.py:

UNIT-III

REGULAR EXPRESSIONS

Regular expressions, often referred to as RegEx or regex, are a powerful tool in Python
for pattern matching and manipulating text. They are implemented through the built-
in re module.
KEY CONCEPTS:
 Patterns:
Regular expressions define a search pattern using a specialized syntax. This pattern
describes the characteristics of the text you want to find, such as specific character
sequences, character sets, repetitions, or positions within a string.
 re Module:
Python's re module provides functions to work with regular expressions. You import it
using import re.
 Raw Strings:
It is highly recommended to use raw strings (prefixed with r or R, e.g., r"my\s+pattern")
when defining regex patterns in Python. This prevents backslashes from being
interpreted as escape sequences by Python, ensuring they are passed directly to the
regex engine.

Common re Module Functions:

Zenex Vision Degree College Phno:9515786774, 965250444. 44


III B.Sc SEMESTER V Application Development using Python

 re.search(pattern, string): Searches for the first occurrence of pattern anywhere


within string. Returns a match object if found, None otherwise.
 re.match(pattern, string): Attempts to match pattern only at the beginning
of string. Returns a match object if found, None otherwise.
 re.findall(pattern, string): Returns a list of all non-overlapping matches
of pattern in string.
 re.sub(pattern, repl, string): Replaces all occurrences
of pattern in string with repl.
 re.split(pattern, string): Splits string by occurrences of pattern.

Example
import re

text = "The quick brown fox jumps over the lazy dog."

# Search for "fox"


match = re.search(r"fox", text)
if match:
print(f"Found: {match.group()}")

# Find all words starting with 'q'


words_q = re.findall(r"\bq\w+", text)
print(f"Words starting with 'q': {words_q}")

# Replace "lazy" with "energetic"


new_text = re.sub(r"lazy", "energetic", text)
print(f"Modified text: {new_text}")

SPECIAL SYMBOLS AND CHARACTERS

Python utilizes various special symbols and characters for different functionalities,
including operators, delimiters, escape sequences, and regular expression metacharacters.
1. Operators:
These symbols perform operations on values and variables. Examples include:
 Arithmetic: +, -, *, /, // (floor division), % (modulo), ** (exponentiation)
 Comparison: ==, !=, <, >, <=, >=
 Assignment: =, +=, -=, *= etc.

Zenex Vision Degree College Phno:9515786774, 965250444. 45


III B.Sc SEMESTER V Application Development using Python

 Logical: and, or, not (keywords, but perform logical operations)


 Bitwise: &, |, ^, ~, <<, >>

2. Delimiters:
These characters structure and separate elements within code. Examples include:
 Parentheses: (), used for function calls, grouping expressions, and defining tuples.
 Square Brackets: [], used for defining lists, accessing elements in sequences, and
slicing.
 Curly Braces: {}, used for defining dictionaries and sets.
 Comma: ,, used to separate items in lists, tuples, function arguments, etc.
Colon: :, used in if statements, for loops, function definitions, and dictionary key-
value pairs.
 Period: ., used for attribute access and floating-point numbers.

3. Escape Characters:
These are special sequences beginning with a backslash (`\`) used to represent characters
that are difficult or impossible to type directly. Common examples include:
 \n: Newline
 \t: Tab
 \r: Carriage return
 \\: Literal backslash
 \': Literal single quote
 \": Literal double quote

4. Regular Expression Metacharacters:


Used within the re module for pattern matching in strings. Examples include:
 .: Matches any character (except newline).
 ^: Matches the beginning of a string.
 $: Matches the end of a string.
 *: Matches zero or more occurrences of the preceding character/group.
 +: Matches one or more occurrences of the preceding character/group.
 ?: Matches zero or one occurrence of the preceding character/group.
 []: Defines a character set (e.g., [a-z] matches any lowercase letter).

Zenex Vision Degree College Phno:9515786774, 965250444. 46


III B.Sc SEMESTER V Application Development using Python

 |: Acts as an "OR" operator.


 (): Groups expressions.

RES AND PYTHON

In Python, "res" is commonly used as a variable name, typically short for "result," to
store the outcome of a computation or operation. It is not a reserved keyword or built-in
function, but rather a widely adopted naming convention for clarity and conciseness.

Example

def multiply_numbers(a, b):


res = a * b # 'res' stores the product of 'a' and 'b'
return res

final_result = multiply_numbers(5, 4)
print(final_result)

Output: 20

The term "res" can also refer to Regular Expressions (REs, regexes, or regex patterns),
which are a powerful tool for matching text patterns in Python. These are implemented
through the built-in re module.
The re module provides functions for various operations with regular expressions, such
as:
 re.search(): Scans through a string looking for the first location where the regular
expression produces a match.
 re.findall(): Returns all non-overlapping matches of the pattern in the string, as a list
of strings.
 re.sub(): Replaces occurrences of a pattern in a string with a replacement string.
 re.split(): Splits a string by the occurrences of a pattern.

MULTITHREADED PROGRAMMING

Multithreading in Python refers to the ability to execute multiple threads concurrently


within a single process. A thread is a lightweight unit of execution that shares the same
memory space as other threads within the same process. This allows for easier

Zenex Vision Degree College Phno:9515786774, 965250444. 47


III B.Sc SEMESTER V Application Development using Python

communication and data sharing between threads compared to separate processes, which
have their own isolated memory spaces.
Key aspects of multithreading
 Concurrency within a single process:
Multithreading enables a program to perform multiple tasks seemingly simultaneously
by rapidly switching between threads (context switching), even on a single-core CPU.
 Shared memory space:
Threads within the same process share resources like memory, global variables, and
open files, facilitating data exchange.
 Threading module:
Python's built-in threading module provides the tools to create, manage, and
synchronize threads.
 I/O-bound tasks:
Multithreading is particularly beneficial for I/O-bound operations (e.g., network
requests, file I/O, database queries) where the program spends a significant amount of
time waiting for external resources. During these waiting periods, other threads can
execute, improving overall responsiveness.
 Global Interpreter Lock (GIL):
Python's CPython implementation includes a Global Interpreter Lock (GIL), which
limits true parallel execution for CPU-bound tasks. The GIL ensures that only one
thread can execute Python bytecode at a time, even on multi-core processors. This
means multithreading may not provide significant performance gains for
computationally intensive tasks in CPython. For such tasks,
the multiprocessing module, which creates separate processes, is often more suitable.

THREADS AND PROCESSES

In Python, both threads and processes are mechanisms for achieving concurrency,
allowing multiple tasks to seemingly run at the same time. However, they differ
significantly in their implementation and suitability for various tasks.
PROCESSES:
 Independent Programs:
A process is an independent instance of a running program, with its own dedicated
memory space, resources, and execution environment.
 True Parallelism:

Zenex Vision Degree College Phno:9515786774, 965250444. 48


III B.Sc SEMESTER V Application Development using Python

Processes can achieve true parallelism on multi-core CPUs because each process runs
independently and is not subject to the Global Interpreter Lock (GIL).
 Higher Overhead:
Creating and managing processes involves more overhead (memory and time)
compared to threads due to their independent nature.
 Inter-Process Communication (IPC):
Communication between processes requires explicit mechanisms like pipes, queues, or
shared memory, as they do not share memory directly.
 Best for CPU-bound tasks:
Ideal for computationally intensive tasks that benefit from parallel execution on
multiple cpu cores, as they bypass the gil.

THREADS:
 Units within a Process:
Threads are lightweight units of execution within a single process, sharing the same
memory space and resources.
 Concurrency, not True Parallelism (due to GIL):
In CPython (the standard Python interpreter), a Global Interpreter Lock (GIL) ensures
that only one thread can execute Python bytecode at a time, even on multi-core
systems. This means threads achieve concurrency (tasks appear to run simultaneously
by switching quickly), but not true parallelism for CPU-bound operations.
 Lower Overhead:
Threads are "lighter" than processes, requiring less overhead for creation and context
switching.
 Shared Memory:
Threads within the same process can easily share data and communicate through shared
memory, but this requires careful synchronization (e.g., using locks) to prevent race
conditions.
 Best for I/O-bound tasks:
Suitable for tasks that involve waiting for external resources (like network requests or
file I/O), as the GIL is released during these waiting periods, allowing other threads to
run.

Zenex Vision Degree College Phno:9515786774, 965250444. 49


III B.Sc SEMESTER V Application Development using Python

GLOBAL INTERPRETER LOCK

A global interpreter lock (GIL) is a mechanism used in computer-


language interpreters to synchronize the execution of threads so that only one native
thread (per process) can execute basic operations (such as memory
allocation and reference counting) at a time.

As a general rule, an interpreter that uses GIL will see only one thread to execute at a
time, even if it runs on a multi-core processor, although some implementations provide
for CPU intensive code to release the GIL, allowing multiple threads to use multiple
cores. Some popular interpreters that have a GIL are CPython and Ruby MRI.

Advantages

 Increased speed of single-threaded


 Easy integration of C libraries that usually are not thread-safe,
 Ease of implementation

Example
from threading import Lock

INSTRUCTION_TABLE = { ... }
def execute(bytecode: list) -> None:
"""Execute bytecode."""
lock = Lock()
for (opcode, args) in bytecode:
lock.acquire()
INSTRUCTION_TABLE[opcode](args)
lock.release()

THREAD AND THREADING MODULE

In Python, "thread" refers to a lightweight unit of execution within a process, while


the threading module is the standard library module that provides a higher-level, object-
oriented API for working with threads.
THREAD MODULE
Threads are essentially independent sequences of instructions that run concurrently
within the same process.
 They share the same memory space, meaning they can access and modify the same
data structures and variables.
 Each thread has its own execution stack, but they share the process's heap memory.

Zenex Vision Degree College Phno:9515786774, 965250444. 50


III B.Sc SEMESTER V Application Development using Python

 Threads are particularly useful for tasks that involve waiting for external resources
(I/O-bound tasks), such as network requests, file operations, or database queries, as they
allow the program to perform other operations while waiting.

THREADING MODULE
The threading module offers a more robust and user-friendly way to manage threads
compared to the older, lower-level _thread module. Key features and components
include:
 Thread class:
This is the primary class for creating and managing individual threads. You can define a
custom class that inherits from threading.Thread and overrides its run() method, or you
can pass a target function to the Thread constructor.
 Synchronization primitives:
The module provides various tools to manage concurrent access to shared resources and
prevent race conditions, such as:
 Lock: A basic lock that ensures only one thread can acquire it at a time, protecting
critical sections of code.
 RLock (Reentrant Lock): Similar to Lock, but allows the same thread to acquire it
multiple times.
 Semaphore: A counter-based lock that limits the number of threads that can access
a resource concurrently.
 Event: A simple signaling mechanism where one thread can signal an event, and
other threads can wait for that event to be set.
 Condition: Allows threads to wait for specific conditions to be met before
proceeding.

Thread management functions:


The module also includes functions like active_count(), current_thread(),
and enumerate() to get information about active threads.

Example
import threading
import time
def worker_function(name, delay):
"""A function to be executed by a thread."""
print(f"Thread {name}: Starting...")
time.sleep(delay)

Zenex Vision Degree College Phno:9515786774, 965250444. 51


III B.Sc SEMESTER V Application Development using Python

print(f"Thread {name}: Finishing.")


# Create Thread objects
thread1 = threading.Thread(target=worker_function, args=("One", 2))
thread2 = threading.Thread(target=worker_function, args=("Two", 3))
# Start the threads
thread1.start()
thread2.start()
# Wait for threads to complete
thread1.join()
thread2.join()

print("All threads have completed.")


UNIT-IV

GUI PROGRAMMING INTRODUCTION

Python provides various options for developing graphical user interfaces (GUIs).
Some of them are

Tkinter- Tkinter is the python interface to the TK GUI toolkit shipped with python

wxPython- open source python interface for wxwidgets GUI toolkit

PyQt- Python interface for popular cross-platform Qt GUI library

PyGTK- PyGTK is a set of wrappers written in python and c for GTK + GUI library

PySimpleGUI- PySimpleGUI is an open source, cross- platformGUI library for python

Pygame-Python library used for developing video games

Jython- Jython is a python port of java,which gives python scripts seamless acess to the
java class libraries on local machine

TKINTER AND PYTHON PROGRAMMING

Tkinter is Python’s built-in library for creating graphical user interfaces (GUIs). It
acts as a lightweight wrapper around Tcl/Tk GUI toolkit, offering Python developers a
simple and intuitive way to build desktop applications. It supports layout management,
event handling and customization, making it ideal for rapid GUI development in
Python.

Features

Zenex Vision Degree College Phno:9515786774, 965250444. 52


III B.Sc SEMESTER V Application Development using Python

1. Provides a built-in and easy-to-use way to create GUI (Graphical User Interface)
applications in Python.
2. Offers various widgets like buttons, labels, text boxes and menus to build
interactive apps.
3. Eliminates the need for external GUI frameworks tkinter comes bundled with
Python.
4. Useful for building desktop applications like calculators, form apps and
dashboards.
5. Supports event-driven programming, making it suitable for responsive user
interfaces.

Create First Tkinter GUI Application

To create a Tkinter Python app, these steps to be followed

1. Import the tkinter module: Import the tkinter module, which is necessary for
creating the GUI components.
2. Create the main window (container): Initialize the main application window
using the Tk() class.
3. Set Window Properties: We can set properties like the title and size of the
window.
4. Add widgets to the main window: We can add any number of widgets like
buttons, labels, entry fields, etc., to the main window to design the interface.
5. Pack Widgets: Use geometry managers like pack(), grid() or place() to arrange the
widgets within the window.
6. Apply event triggers to the widgets: We can attach event triggers to the widgets
to define how they respond to user interactions.

There are two main methods used which user needs to remember while creating the
Python application with GUI. These methods are:

1. Tk()
To create a main window in Tkinter, we use the Tk() class.
Syntax:
root = tk.Tk(screenName=None, baseName=None, className='Tk', useTk=1)
Parameter:
 screenName: This parameter is used to specify the display name.
 baseName: This parameter can be used to set the base name of the application.
 className: We can change the name of the window by setting this parameter to
the desired name.
 useTk: This parameter indicates whether to use Tk or not.

Zenex Vision Degree College Phno:9515786774, 965250444. 53


III B.Sc SEMESTER V Application Development using Python

2. mainloop()
The mainloop() method is used to run application once it is ready. It is an infinite loop
that keeps application running, waits for events to occur (such as button clicks) and
processes these events as long as window is not closed.

Example:

This code initializes a basic GUI window using Tkinter. The tkinter.Tk() function
creates main application window, mainloop() method starts event loop, which keeps
the window running and responsive to user interactions.

import tkinter
m = tkinter.Tk()
'''
widgets are added here
'''
m.mainloop()
Output

WEB PROGRAMMING –INTRODUCTION

Web programming in Python involves using the Python programming language to


develop web applications and websites. While Python itself is not executed directly in
web browsers (JavaScript is used for client-side scripting), it is widely used for server-
side logic and backend development.
Key aspects of web programming in Python:

Zenex Vision Degree College Phno:9515786774, 965250444. 54


III B.Sc SEMESTER V Application Development using Python

 Frameworks:
Python boasts a rich ecosystem of web frameworks that streamline development.
 Django: A high-level, "batteries-included" framework known for its rapid
development capabilities and emphasis on convention over configuration. It provides
built-in features for user authentication, administration, forms, and more.
 Flask: A lightweight micro-framework offering more flexibility and control. It is
suitable for smaller projects or when a developer prefers to choose individual
components.
 Other frameworks: CherryPy, Pyramid, Web2py, and Bottle are also available,
each with its own strengths and use cases.
 Server-Side Development:

Python handles the server-side logic, including:


 Processing HTTP requests and generating responses.
 Interacting with databases for data storage and retrieval.
 Implementing business logic and application functionality.
 Rendering dynamic content to be sent to the client's browser.

Integration with Frontend Technologies:


While Python handles the backend, it integrates with standard frontend technologies
like HTML, CSS, and JavaScript, which are executed in the user's web browser to
create the user interface and interactive elements.

Advantages:
 Readability and Simplicity: Python's clear syntax makes it easy to learn and
write code, leading to faster development.
 Extensive Libraries: A vast collection of libraries and packages are available for
various tasks, from data analysis to machine learning, which can be integrated into web
applications.
 Scalability and Robustness: Frameworks like Django provide features for
building scalable and secure applications.
 Community Support: Python has a large and active community, offering
extensive documentation and support.

WEB SURFING WITH PYTHON

Zenex Vision Degree College Phno:9515786774, 965250444. 55


III B.Sc SEMESTER V Application Development using Python

Web surfing" with Python can refer to two main activities:


 Opening and controlling a web browser: This involves launching a web browser
and navigating to specified URLs using Python code. The webbrowser module, part of
Python's standard library, facilitates this.

Example

import webbrowser

# Open a URL in the default browser


webbrowser.open("https://www.google.com")

# Open a URL in a new browser tab


webbrowser.open_new_tab("https://www.python.org")

# Open a URL in a new browser window


webbrowser.open_new("https://docs.python.org/")

 Programmatically interacting with web content (Web Scraping): This involves


fetching web page content, parsing it, and extracting specific data. This is more akin to
automated browsing for data collection. Libraries like urllib (standard library)
and requests (third-party) are commonly used for fetching content,
while BeautifulSoup and lxml are popular for parsing HTML and XML.

Example

from urllib.request import urlopen

url = "http://olympus.realpython.org/profiles/aphrodite"
page = urlopen(url)
html_bytes = page.read()
html = html_bytes.decode("utf-8")
print(html)

CREATING SIMPLE WEB CLIENTS

Creating a simple web client in Python can be accomplished using the built-
in socket module for low-level network communication or the more user-
friendly requests library for handling HTTP requests.

Zenex Vision Degree College Phno:9515786774, 965250444. 56


III B.Sc SEMESTER V Application Development using Python

1. Using the socket module (for basic TCP communication):


This method allows direct interaction with the underlying network sockets.
import socket
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to a server (e.g., a simple echo server on localhost:8080)
server_address = ('localhost', 8080)
client_socket.connect(server_address)

# Send data
message = "Hello from the client!"
client_socket.sendall(message.encode())
# Receive data
data = client_socket.recv(1024)
print(f"Received from server: {data.decode()}")
# Close the connection
client_socket.close()

2.Using the requests library (for HTTP/HTTPS requests):


The requests library simplifies making HTTP requests, handling details like headers,
cookies, and redirects. It is the recommended approach for most web client applications.
First, install the library if you haven't already:
code
pip install requests
import requests
# Make a GET request
response = requests.get("https://www.example.com")
print(f"Status Code: {response.status_code}")
print(f"Content: {response.text[:200]}...") # Print first 200 characters

# Make a POST request with data


payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post("https://httpbin.org/post", data=payload)
print(f"POST Response: {response.json()}")
ADVANCED WEB CLIENTS

Zenex Vision Degree College Phno:9515786774, 965250444. 57


III B.Sc SEMESTER V Application Development using Python

Advanced web clients in Python extend beyond basic document downloading to perform
complex interactions with web resources. These clients are commonly used for tasks such
as:
 Web Scraping and Crawling:
Automatically extracting data from websites, indexing content for search engines, or
building local archives.
 Automated Testing and Browser Automation:
Simulating user interactions for testing web applications or automating repetitive tasks
within a browser environment.
 Building Custom Applications:
Creating specialized applications that communicate with web APIs, integrate with
online services, or provide offline browsing capabilities.
Several Python libraries facilitate the development of advanced web clients:
 Requests: A popular and user-friendly library for making HTTP requests. It
simplifies common tasks like handling sessions, cookies, and authentication.

Example

import requests

response = requests.get('https://example.com')
print(response.text)

 aiohttp: An asynchronous HTTP client/server framework built on asyncio. It is


suitable for high-performance applications requiring concurrent connections, such as
web scrapers or microservice architectures.

Example

import aiohttp
import asyncio

async def fetch_url(session, url):


async with session.get(url) as response:

Zenex Vision Degree College Phno:9515786774, 965250444. 58


III B.Sc SEMESTER V Application Development using Python

return await response.text()

async def main():


async with aiohttp.ClientSession() as session:
html = await fetch_url(session, 'https://example.com')
print(html)

if __name__ == '__main__':
asyncio.run(main())

 Scrapy:
A powerful and comprehensive framework specifically designed for web crawling and
data extraction. It provides a high-level structure for building scalable and efficient
crawlers.
 Selenium:
A library for browser automation, allowing you to control a web browser
programmatically. It is ideal for interacting with dynamic web pages, executing
JavaScript, and simulating user behavior.

Example

from selenium import webdriver

driver = webdriver.Chrome() # Or Firefox, Edge, etc.


driver.get("https://example.com")
# Perform interactions, e.g., driver.find_element_by_id("some_id").click()
driver.quit()

Beautiful Soup: A library for parsing HTML and XML documents, often used in
conjunction with HTTP clients like Requests to extract specific data from web pages

Example

from bs4 import BeautifulSoup


import requests

response = requests.get('https://example.com')
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string)

Zenex Vision Degree College Phno:9515786774, 965250444. 59


III B.Sc SEMESTER V Application Development using Python

CGI-HELPING SERVERS PROCESS CLIENT DATA

The Common Gateway Interface (CGI) is a standard method that enables web servers to
interact with external applications, allowing them to process client data and generate
dynamic content. Essentially, CGI acts as a bridge between the web server and these
applications, facilitating the exchange of information.
When a client submits data (e.g., through an HTML form), the web server receives this
request and, if configured for CGI, passes the relevant information to a designated CGI
program. This program, written in languages like Python, Perl, C, or Java, processes the
client's input, performs necessary actions (like querying a database or performing
calculations), and then generates dynamic content, typically in HTML format. The web
server then receives this generated content from the CGI program and sends it back to the
client's browser as a response.
In essence, CGI allows web servers to move beyond serving static files and provide
interactive experiences where client input can trigger server-side processing and result in
customized, dynamic web pages.

BUILDING CGI APPLICATION

Building a CGI (Common Gateway Interface) application in Python involves creating


Python scripts that a web server can execute to generate dynamic web content.
1. Web Server Setup:
 Ensure your web server (e.g., Apache, NGINX) is configured to support CGI
execution. This typically involves enabling the CGI module and defining
a ScriptAlias or ExecCGI directive for the directory where your CGI scripts will reside
(commonly cgi-bin).
2. Python CGI Script Creation:
 Shebang Line:
Begin your Python script with a shebang line indicating the path to your Python
interpreter (e.g., #!/usr/bin/env python or #!C:\Python39\python.exe for Windows).
 Import cgi and cgitb:
Import the cgi module for handling form data and the cgitb module for error reporting
(e.g., import cgi, cgitb).
 Enable Error Reporting (Optional but Recommended):

Zenex Vision Degree College Phno:9515786774, 965250444. 60


III B.Sc SEMESTER V Application Development using Python

Use cgitb.enable() to display detailed error messages in the browser during


development. You can also log errors to a file for debugging in production
(cgitb.enable(display=0, logdir="path")).
 Content-Type Header:
Print the HTTP Content-type header to specify the type of content being sent back to
the browser (e.g., print("Content-type: text/html\n\n")).
 Handle Form Data:
 Create an instance of cgi.FieldStorage() to parse and store data submitted via
HTML forms (e.g., form = cgi.FieldStorage()).
 Retrieve values from form fields using form.getvalue('field_name').
 Generate HTML Output:
Use print() statements to output the desired HTML content that will be rendered by the
browser.
3. Permissions and Placement:
 Place your Python CGI script in the designated CGI directory configured in your
web server.
 Ensure the script has executable permissions (e.g., chmod 755 your_script.py on
Unix-like systems).
 Verify that the web server user has appropriate read/write permissions for any files
your script needs to access

Example

import cgi, cgitb


cgitb.enable() # Enable error reporting

print("Content-type: text/html\n\n")
print("<html>")
print("<head>")
print("<title>My CGI Application</title>")
print("</head>")
print("<body>")

form = cgi.FieldStorage()
name = form.getvalue("name")

Zenex Vision Degree College Phno:9515786774, 965250444. 61


III B.Sc SEMESTER V Application Development using Python

if name:
print(f"<h1>Hello, {name}!</h1>")
else:
print("<h1>Please provide your name.</h1>")

print("</body>")
print("</html>")

ADVANCED CGI

While the cgi module in Python's standard library provided support for Common
Gateway Interface (CGI) scripting, it has been deprecated since Python 3.11 and removed
in Python 3.13. This means that using the cgi module for advanced CGI programming is
no longer recommended for modern Python development.
The removal of the cgi module reflects a shift in web development practices, moving
away from traditional CGI scripts towards more robust and feature-rich web
frameworks. These frameworks provide a more structured and efficient way to build web
applications, including handling requests, managing sessions, interacting with databases,
and generating dynamic content.
For advanced web development in Python, including tasks that might have previously
been handled by advanced CGI techniques (like handling complex forms, file uploads, or
managing cookies and sessions), modern web frameworks are the recommended
approach.
Examples of such frameworks include:
 Django:
A high-level web framework that encourages rapid development and clean, pragmatic
design. It includes a comprehensive ORM, an administrative interface, and a templating
system.
 Flask:
A microframework for Python that is lightweight and flexible, allowing developers to
choose their own tools and libraries.
 FastAPI:
A modern, fast (high-performance) web framework for building APIs with Python 3.7+
based on standard Python type hints.
These frameworks offer built-in functionalities and extensions that simplify the
development of complex web applications, providing a more secure, scalable, and
maintainable alternative to traditional CGI scripting. If a project requires using
the cgi module specifically, a fork of the module is available on PyPI under the

Zenex Vision Degree College Phno:9515786774, 965250444. 62


III B.Sc SEMESTER V Application Development using Python

name legacy-cgi. However, this is not supported by the core Python team and should be
used with caution, primarily for maintaining older codebases.

WEB(HTTP)SERVERS

Python provides several ways to create an HTTP web server, ranging from simple built-in
modules for serving static files to more robust frameworks for building dynamic web
applications.
1. Simple Static File Server (using http.server):
For serving static files from a directory, Python's built-in http.server module offers a
quick solution.
Code
python3 -m http.server 8000
This command starts an HTTP server on port 8000, serving the contents of the current
directory. You can then access the files by navigating to http://localhost:8000/ in your
web browser.
2. Custom HTTP Server (using http.server and socketserver):
For more control over request handling, you can create a custom server
using http.server.BaseHTTPRequestHandler and socketserver.TCPServer.
Code
import http.server
import socketserver
PORT = 8000
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(b"<h1>Hello from Python!</h1>")
with socketserver.TCPServer(("", PORT), MyHandler) as httpd:
print(f"Serving at port {PORT}")
httpd.serve_forever()

This example creates a server that responds to all GET requests with a simple "Hello
from Python!" message. You can customize the do_GET, do_POST, etc., methods to
handle different request types and serve dynamic content.

Zenex Vision Degree College Phno:9515786774, 965250444. 63


III B.Sc SEMESTER V Application Development using Python

3. Web Frameworks (e.g., Flask, Django):


For building more complex web applications with features like routing, templating, and
database integration, Python web frameworks like Flask or Django are
recommended. These frameworks provide a structured approach to web development and
handle many of the underlying HTTP server complexities.
Note: The built-in http.server module is suitable for testing and development but is not
recommended for production environments due to its limited features and performance
considerations. For production, consider using a WSGI server like Gunicorn or Waitress
in conjunction with a robust web framework.
UNIT-V

DATABASE PROGRAMMING

Database programming in Python involves using Python to interact with various types of
databases, including relational databases like MySQL, PostgreSQL, and SQLite, as well
as non-relational databases such as MongoDB and Redis.
Key aspects of database programming in Python:
 Database Drivers/Connectors:
Python requires specific libraries or drivers to connect to different database
systems. Examples include mysql-connector-python for MySQL, psycopg2 for
PostgreSQL, sqlite3 (built-in) for SQLite, and pymongo for MongoDB.
 Connecting to the Database:
The first step is to establish a connection to the database server. This typically involves
providing connection details like host, username, password, and the database name.

Code

import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

 Creating a Cursor Object: A cursor object is used to execute SQL queries or


database commands.

Zenex Vision Degree College Phno:9515786774, 965250444. 64


III B.Sc SEMESTER V Application Development using Python

Code

mycursor = mydb.cursor()

 Executing Queries: SQL statements (e.g., CREATE


TABLE, INSERT, SELECT, UPDATE, DELETE) are executed using the cursor
object's execute() method.

Code

mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address


VARCHAR(255))")

 Fetching Results: For SELECT queries, methods like fetchone(), fetchmany(),


or fetchall() are used to retrieve the results.

Code

mycursor.execute("SELECT * FROM customers")


myresult = mycursor.fetchall()
for x in myresult:
print(x)

 Committing Changes: For operations that modify the database


(e.g., INSERT, UPDATE, DELETE), the changes need to be committed to make them
permanent.

Code

mydb.commit()

 Closing the Connection: After completing database operations, the connection and
cursor objects should be closed to release resources.
Code
mycursor.close()
mydb.close()

PYTHON DATABASE APPLICATION PROGRAMMERS INTERFACE

Zenex Vision Degree College Phno:9515786774, 965250444. 65


III B.Sc SEMESTER V Application Development using Python

The Python Database Application Programming Interface (DB-API) is a standardized


specification for how Python modules should interact with database systems. It is
documented in Python Enhancement Proposal (PEP) 249.
The primary purpose of the DB-API is to provide a consistent and uniform interface for
database access across various database systems and their respective Python drivers. This
consistency allows developers to write database-agnostic code, meaning the same Python
application code can often be used with different underlying databases (e.g., MySQL,
PostgreSQL, SQLite, Oracle) with minimal modifications, typically only requiring a
change in the imported database module and connection parameters.
Key components and concepts within the Python DB-API include:
 Connection Objects:
These represent a connection to a specific database. They are responsible for managing
transactions (commit, rollback) and providing access to cursor objects.
 Cursor Objects:
These objects allow for the execution of SQL queries and the fetching of results. They
provide methods for executing statements, fetching single rows, multiple rows, or all
remaining rows.

 Standard Exceptions:
The DB-API defines a set of standard exceptions
(e.g., Error, Warning, InterfaceError, DatabaseError) that database drivers should raise
in response to specific database-related issues, ensuring consistent error handling.
 Module Contents:
The specification outlines required module-level attributes and functions that database
drivers must implement to conform to the DB-API standard.
By adhering to the DB-API, Python database modules (like sqlite3, psycopg2 for
PostgreSQL, mysql-connector-python for MySQL) offer a familiar and predictable way
to interact with databases, simplifying development and promoting code portability.

OBJECT RELATIONAL MANAGERS

Object-Relational Managers (ORMs) in Python are libraries or frameworks that provide a


layer of abstraction between a Python application and a relational database. They allow
developers to interact with the database using object-oriented programming concepts
(like classes and objects) instead of writing raw SQL queries.
How ORMs Work:

Zenex Vision Degree College Phno:9515786774, 965250444. 66


III B.Sc SEMESTER V Application Development using Python

 Mapping:
ORMs map Python classes to database tables and instances of those classes to rows
within those tables. Attributes of the Python objects correspond to columns in the
database.
 Abstraction:
They translate object-oriented operations (e.g., creating an object, modifying an object's
attribute, querying for objects) into the appropriate SQL statements, which are then
executed against the database.
 Simplification:
This abstraction simplifies database interactions, making it more intuitive for Python
developers to work with data, especially those less familiar with SQL.
Key Benefits of Using ORMs:
 Increased Productivity:
Developers can work with familiar Python objects and methods, reducing the need to
write and manage complex SQL queries.
 Reduced Boilerplate Code:
ORMs often handle common database tasks like connection management, data type
conversions, and relationship mapping, reducing the amount of manual code required.
 Database Agnosticism:
Many ORMs support multiple database systems (e.g., PostgreSQL, MySQL, SQLite),
allowing for easier switching between databases with minimal code changes.
 Improved Maintainability:
By abstracting database interactions, ORMs can make code more readable and easier to
maintain.
Popular Python ORMs:
 SQLAlchemy:
A powerful and flexible ORM that provides both a SQL Expression Language and an
ORM component. It is highly configurable and suitable for complex applications.
 Django ORM:
The built-in ORM for the Django web framework. It is tightly integrated with Django's
features and provides a convenient way to manage database interactions within Django
projects.
 Peewee:
A lightweight and expressive ORM designed for simplicity and ease of use, particularly
for smaller projects.

Zenex Vision Degree College Phno:9515786774, 965250444. 67


III B.Sc SEMESTER V Application Development using Python

 PonyORM:
An ORM that uses Python's generator expressions for defining queries, aiming for a
more Pythonic and intuitive query syntax.
 Tortoise ORM:
An asynchronous ORM designed for use with asyncio applications, commonly used in
conjunction with asynchronous web frameworks like FastAPI.

Zenex Vision Degree College Phno:9515786774, 965250444. 68

You might also like