0% found this document useful (0 votes)
264 views

Python Complete Material Notes by Ns

The document provides a syllabus for a Python programming course divided into 5 units. Unit 1 covers Python basics like objects, standard types, numbers, sequences, files, exceptions, and modules. Unit 2 discusses regular expressions, multithreaded programming, and GUI programming. Unit 3 covers web programming and database programming. The final units cover additional topics like GUI programming, web programming, and database programming.

Uploaded by

Manish Practice
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
264 views

Python Complete Material Notes by Ns

The document provides a syllabus for a Python programming course divided into 5 units. Unit 1 covers Python basics like objects, standard types, numbers, sequences, files, exceptions, and modules. Unit 2 discusses regular expressions, multithreaded programming, and GUI programming. Unit 3 covers web programming and database programming. The final units cover additional topics like GUI programming, web programming, and database programming.

Uploaded by

Manish Practice
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 348

PYTHON PROGRAMMING SYLLABUS

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, Related Modules
Sequences - Strings, Lists, and Tuples, Mapping and Set Types
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,
Persistent Storage Modules, Related Modules
Exceptions: Exceptions in Python, Detecting and Handling Exceptions, Context
Management, *Exceptions as Strings, Raising Exceptions, Assertions, Standard
Exceptions, *Creating Exceptions, Why Exceptions (Now)?, Why Exceptions at All?,
Exceptions and the sys Module, Related Modules
Modules: Modules and Files, Namespaces, Importing Modules, Importing Module
Attributes, Module Built-in Functions, Packages, Other Features of Modules
UNIT - III

Regular Expressions: Introduction, Special Symbols and Characters, Res and


Python Multithreaded
Programming: Introduction, Threads and Processes, Python, Threads, and the
Global Interpreter Lock, Thread Module, Threading Module, Related Modules
UNIT – IV
GUI Programming: Introduction, Tkinter and Python Programming, Brief Tour of
Other GUIs, Related Modules and Other GUIs
WEB Programming: Introduction, Wed 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 (DB-API), Object Relational Managers (ORMs), Related Modules
For complete python tutorials click here : ns lectures youtube channel

PYTHON PROGRAMMING SYLLABUS

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 Type

Numbers –

Introduction to Numbers
Integers
Floating Point Real Numbers
Complex Numbers
Operators
Built-in Functions
Related Modules

Sequences –

Strings
Lists
Tuples
Mapping
Set Types
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel

Variables
Variables are containers for storing data values

Python variable is also known as an identifier and used to hold value,


(identifier :- name given by user is know as identifier , either name
can be variable name or method name or function name) .

Python is dynamically typed language so there is no need of declaring


data type to a variable

Creating Variables

A variable is created the moment you first assign a value to it.

Example program:

x=5

y = "nagendra"

print(x)

print(y)

output:

Nagendra

Assigning a single value to multiple variables:


Also, Python allows assigning a single value to several variables
simultaneously with “=”
Program:
a = b = c = 10
print(a)
print(b)
print(c)

output:
10
10
For complete python tutorials click here : ns lectures youtube channel

10
Assigning different values to multiple variables:
Python allows adding different values in a single line with “,”operators.
Program:

a, b, c = 1, 20.2, "nagendra"

print(a)

print(b)

print(c)

Output:
1
20.2
Nagendra

Variables do not need to be declared with any particular type, and can
even change type after they have been set.

Example:

x=4 # x is of type int


x = "Nagendra" # x is now of type str
print(“output is :” , x)

output:

output is : Nagendra

Rules for creating variables(identifiers) in Python


• A variable name must start with a letter or the underscore character.
• A variable name cannot start with a number.
• A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ ).
• Variable names are case-sensitive (name, Name and NAME are
three different variables).
• The reserved words(keywords) cannot be used naming the variable.
For complete python tutorials click here : ns lectures youtube channel

Comments in python
Comments in Python are the lines in the code that are ignored by the
interpreter during the execution of the program. Comments enhance
the readability of the code and help the programmers to understand the
code very carefully. There are three types of comments in Python –
• Single line Comments
• Multiline Comments
•Docstring Comments Creating

a single line Comment:

Comments starts with a #, and Python will ignore them:

Example:

#This is a comment
print("Hello, World!")

Output: Hello, World!"

Comments can be placed at the end of a line, and Python will


ignore the rest of the line:

Example:

print("Hello, World!") #This is a comment

Output: Hello, World!"

Multi Line Comments:

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example:

#This is a comment
#written in
For complete python tutorials click here : ns lectures youtube channel

#more than just one line


print("Hello, World!")

Output: Hello, World!")

Creating comments using docstring:


Since Python will ignore string literals that are not assigned to a variable,

You can create comments by using three single quotes(‘ ‘ ‘) at starting


and ending of the comment

You can also use three double quotes( “ “ “)at starting and ending of the
comment

Example:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Output:

Hello, World!"

Here, you cannot use three single quotes(‘ ‘ ‘) at starting and three
double quotes at the ending(‘ ‘ ‘)

Data types (or) Variable type (or) standard


types (or) built in types in Python
Variables can hold values, and every value has a data-type. Python
is a dynamically typed language; hence we do not need to define
the data type of the variable while declaring it. The interpreter can
automatically understand datatype of given value.

A variable can hold different types of values. For example, a person's


name must be stored as a string whereas its id must be stored as an
integer.
For complete python tutorials click here : ns lectures youtube channel

You can get the data type of a variable with the type() function.

Python provides various standard data types That are given below.

Python numbers:

There are three numeric types in Python:

• int
• float
• complex

Int type:

Int, or integer, is a whole number, positive or negative, without decimals,


of unlimited length.

Program:

a=5
print(a)
print(type(a))

output:

5
<class-‘int’>
For complete python tutorials click here : ns lectures youtube channel

The variable a holds integer value 5 and we did not define its type.
Python interpreter will automatically identify variables a as an integer
type.so print function is used to generate output so you will get output 5.
You can get the data type of a variable with the type() function.

Float type:

Float, or "floating point number" is a number, positive or negative,


containing one or more decimals.

Program:

a = 1.5
print(a)
print(type(a))

output:

1.5
<class-‘float’>

Complex type:

Numbers which contains both real part and imaginary part is known as
complex number

Example : 2+3j

Where,

2 is real part

3j is imaginary part

Example program:

a=2+3j

print(a)

print(type(a))

output:
For complete python tutorials click here : ns lectures youtube channel

2+3j
<class-‘complex’>

Example program 2:

a=2+3j

print(a.real) # it will display real value

print(a.imag) # it will display imaginary value

output:
2
3j

Complex() function:
it is used to convert number or string to complex number

syntax: complex(real, imaginary)

program:

a=complex(1,2)
print(a)
print(“real part is :”, a.real)

output:

1+2j
Real part is :1

if you don’t assign value , then by default it will take value 0

example:
a=complex(2)# I did not given imaginary value so It takes default value 0
print(a)

output:

1+0j
For complete python tutorials click here : ns lectures youtube channel

Boolean type:
The Python Boolean type has only two possible values:

1. True
2. False

Example program:

A=True # here T is capital letter


print(a)
print(type(a))

output:
True
<class-‘bool’>

Python boolean type is one of the built-in data types provided by


Python, which represents one of the two values i.e. True or False.( here
for True or False you need to use capital T and capital F), Generally, it
is used to represent the truth values of the expressions. For example,
1==1 is True whereas 2<1 is False.

Example:
Print(3==9)

Output:
False
Strings type:

Strings in python are surrounded by either single quotation marks, or


double quotation marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Program:

a = “sai”
print(a)
print(type(a))
For complete python tutorials click here : ns lectures youtube channel

output:
sai
<class-‘str’>

Python sequences:

1. list
2. tuple

List :
Lists are just like the arrays, declared in other languages which is a
ordered collection of data. It is very flexible as the items in a list do not
need to be of the same type.
List is written with curly brackets ([ ])

Example:

a=[10,’nagendra’,10.5]
print(a)
print(type(a))

output:

[10,’nagendra’,10.5]
<class ‘list’>

Tuple:
Just like list, tuple is also an ordered collection of Python objects.
Tuple is written with brackets ()

Example:

a=(10,’nagendra’,10.5)
print(a)
print(type(a))

output:

(10,’nagendra’,10.5)
<class ‘tuple’>
For complete python tutorials click here : ns lectures youtube channel

Set:
In Python, Set is an unordered collection of data type.
Set is written with curly brackets ({})

Example:
a={10,’nagendra’,10.5}
print(a)
print(type(a))

output:

{10,’nagendra’,10.5}
<class ‘set’>

Dictionary:
Dictionaries are used to store data values in key:value pairs.
Dictionaries are written with curly brackets ({})
Example:

a={‘name’:’nagendra’,’height’:6}

here ,

name and height are keys

nagendra and 6 are values

program:
a={‘name’:’nagendra’,’height’:6}
print(a)
print(type(a))
print(a.get(‘name’)) #by giving key you can find value

output:

{‘name’:’nagendra’,’height’:6}

<class ‘dict’>

nagendra
For complete python tutorials click here : ns lectures youtube channel

Python input and output


For complete python tutorials click here : ns lectures youtube channel

1. The end parameter


The end parameter is used to append any string at the end of the output
of the print statement in python.

By default, the print method ends with a newline. This means there is no
need to explicitly specify the parameter end as '\n' Like C programming.

The below example demonstrates that passing '\n' in end parameter or


not passing '\n' in end parameter gives the same result.

Program:

print("Btech")

print("students")

output:

Btech
students

program:

print("Btech", end= "\n")

print("students")

output:

Btech

students
For complete python tutorials click here : ns lectures youtube channel

2. The sep parameter


Sometimes, we may wish to print multiple values in a Python program in
a readable manner. This is when the argument sep comes to play. The
arguments passed to the program can be separated by different values.
The default value for sep is whitespace.

The below example shows that passing sep parameter as whitespace or


not passing the sep at all doesn't make a difference. Execute every line
of code to see the result.

Program:
print("Btech", "students")
output:
Btech students
Program:
print("Btech", "students ", sep = ' ')
output:
For complete python tutorials click here : ns lectures youtube channel
Btech students

here, sep parameter will separate values with given symbol [ here, in
above example I separated values with ‘-‘ symbol]

Python keywords
For complete python tutorials click here : ns lectures youtube channel

Keyword Description

and A logical operator

as To create an alias
For complete python tutorials click here : ns lectures youtube channel

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement


For complete python tutorials click here : ns lectures youtube channel

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling


For complete python tutorials click here : ns lectures youtube channel

yield To end a function, returns a generator

Unsupported types in python

Following are some of the types that are not supported by python

1. Charcter type (char):

In python there is no character data type, in python character is a string


of length one, it is represented by class str.

2. Pointers:

No, we don't have any kind of Pointer in Python language. In C and C++,
a pointer is a variable that holds a memory address, but we don't have
any kind of Pointer in Python , if you want to find address of any object
then you need to use id() function.

Program:

a=10

print(id(a)) #id() function is used to find address

output:

9789280

3. long int and short int:

In c programming for long size integer values and short size integer
values we use long int data type and short int data type but python do
not support long int and short int , in python for both long and short size
integers we use type int.
4. double data type:

We use double data type for long size float values ,but python do not
support double type. In python even for long size float values you can
use float data type.python float is actually C’s double data type
For complete python tutorials click here : ns lectures youtube channel
Standard type built in function

There are some built in functions in python that can be applied to all
basic object types they are

1. cmp():
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel

Python Operators
Operators are used to perform operations on variables and values.
• OPERATORS: Are the special symbols. Eg- + , * , /, etc.
• OPERANDS: It is the value on which the operator is applied.
In the example below, we use the + operator to add together two values:

Example
print(10 + 5)
output:
15
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
• Identity operators
• Membership operators

1. Arithmetic Operators:
Arithmetic operators are used to performing mathematical operations like addition, subtraction,
multiplication, and division.

Operator Description Syntax


+ Addition: adds two operands x+ y
– Subtraction: subtracts two operands x– y
* Multiplication: multiplies two operands x* y
Division (float): divides the first operand by the second and gives result as
/ x/ y
float value
Division (floor): divides the first operand by the second nd gives result as
// x // y
integer value
% Modulus: returns the remainder when the first operand is divided by the second x% y
** Power: Returns first raised to power second x ** y

Program:
For complete python tutorials click here : ns lectures youtube channel

In above example for a/b result is 0.5 because it will represent data as float value
and for a//b result is 05 because it will represent data as integer value, so it
ignores .5 and print only 0

2. Comparison Operators or Relational operator


Comparison or Relational operators compares the values. It either returns True or False according
to the condition.

Operator Description Syntax


> Greater than: True if the left operand is greater than the right x> y
< Less than: True if the left operand is less than the right x< y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
Greater than or equal to True if the left operand is greater than or equal to the
>= x >= y
right
<= Less than or equal to True if the left operand is less than or equal to the right x <= y

= is an assignment operator and == comparison operator.

Program:
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel

3. Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to
combine conditional statements.

Operator Description Syntax


and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
Logical NOT: True if the operand is False and
not False if operand is True not x

program:

Output:
False
True
True
For complete python tutorials click here : ns lectures youtube channel

4. Assignment Operators
Assignment operators are used to assign values to the variables.

Operator Description Syntax


= Assign value of right side of expression to left side operand x= y+z
Add AND: Add right-side operand with left side operand and then assign
+= a+=b a=a+b
to left operand
Subtract AND: Subtract right operand from left operand and then assign
-= a-=b a=a-b
to left operand
Multiply AND: Multiply right operand with left operand and then assign
*= a*=b a=a*b
to left operand
Divide AND: Divide left operand with right operand and then assign toleft
/= a/=b a=a/b
operand
Modulus AND: Takes modulus using left and right operands and assignthe
%= a%=b a=a%b
result to left operand
Divide(floor) AND: Divide left operand with right operand and thenassign
//= a//=b a=a//b
the value(floor) to left operand
Exponent AND: Calculate exponent(raise power) value using operands
**= a**=b a=a**b
and assign value to left operand
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left operand a>>=b a=a>>b
<<= Performs Bitwise left shift on operands and assign value to left operand a <<= b a= a << b

program:

a =3
b =5
a += b # a = a + b
print(a)

Output:
8

5. Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on
binary numbers.
For complete python tutorials click here : ns lectures youtube channel
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x| y
~ Bitwise NOT ~x
^ Bitwise XOR x^ y
>> Bitwise right shift x>>
<< Bitwise left shift x<<

Note:
For bitwise AND if both values are 1 then result is 1
For bitwise OR if both values are 0 then result is 0

For bitwise XOR if both values are Same then result is 0


For bitwise COMPLEMENT for 1 result is 0 and for 0 result is 1

example and program to perform bitwise AND, bitwise OR, bitwise XOR
operations on number 5 and 6
at first you need to convert number 5 into binary i.e., 101
after you need to convert number 6 into binary i.e., 110
For bitwise AND if both values are 1 then result is 1
For bitwise OR if both values are 0 then result is 0
For bitwise XOR if both values are Same then result is 0
For complete python tutorials click here : ns lectures youtube channel

program:

bitwise complement will increment value +1 and adds negative sign to it

program for bitwise complement :

print(~5)
print(~10)
print(~100)
output:
-6
-11
-101
For complete python tutorials click here : ns lectures youtube channel

bitwise right shift operator will shift bits to right so last bit gets removed
and left shift operator will shift bits to left so it add one bit(i.e., 0) at last
example :

1. Identity Operators
is and is not are the identity operators both are used to check if two values are located
on the same part of the memory. Two variables that are equal do not imply that they
are identical.
is True if the operands are identical
is not True if the operands are not identical

program:

a = 10
b = 20
print(a is not b)
print(a is b)

output:
For complete python tutorials click here : ns lectures youtube channel
True
False

2. Membership Operators:
in and not in are the membership operators; used to test whether a value or variable
is in a sequence.
in True if value is found in the sequence
not in True if value is not found in the sequence

program:

a= “ my name is nagendra “

print(“my” in a)

print(“btech” in a)

print(“btech “ not in a)

output:

True

False

True
For complete python tutorials click here : ns lectures youtube channel

Control Flow Statements


The flow control statements are divided into three categories

1. Conditional statements
2. Iterative statements.
3. Transfer statements

Conditional statements
In Python, condition statements act depending on whether a given
condition is true or false. Condition statements always evaluate either True
or False.If the condition is True, then the True block of code will be
executed, and if the condition is False, then the block of code is skipped,
and The controller moves to the next line

We can call this conditional statements as decision making statements


because they are used to make decision based on given condition

There are three types of conditional statements.

1. if statement
2. if-else
3. if-elif-else
4. nested if-else

1. If statement :

In control statements, The if statement is the simplest form. It takes a


condition and evaluates to either True or False.

If the condition is True, then the True block of code will be executed, and if
the condition is False, then the block of code is skipped, and The controller
moves to the next line
For complete python tutorials click here : ns lectures youtube channel

Syntax of the if statement


if condition:
statement 1
statement 2
:
:
statement n

Example-1
a=6
b = 10
if a < b:
print(“a is lessthan b”)

output:
a is lessthan b

Example-2
a = int(input(“enter no:”))
For complete python tutorials click here : ns lectures youtube channel

if a < 10:
print(“a value is less than 10 ”)

output:

enter no:6

a value is less than 10


2. If – else statement:

The if-else statement checks the condition and executes the if block of
code when the condition is True, and if the condition is False, it will execute
the else block of code.

Syntax of the if-else statement


if condition:
statement 1
else:
statement 2

If the condition is True, then statement 1 will be executed If the condition is


False, statement 2 will be executed. See the following flowchart for more
detail.
For complete python tutorials click here : ns lectures youtube channel

Example-1
a = int(input(“enter a value :”))
b = int(input(“enter b value :”))
if a < b:
print(“a is smaller no ”)
else:
print(“b is smaller no ”)

output 1:
enter a value :2
enter b value :30
a is smaller no

output 2:
enter a value :30
enter b value :7
b is smaller no

Example2:
password = input('Enter password ')

if password == "nagendra123":
print("Correct password")
else:
print("Incorrect Password")

Output 1:
Enter password nagendra123
Correct password

Output 2:
Enter password nagendra1111Incorrect Password
For complete python tutorials click here : ns lectures youtube channel

Note :For input() function default data type is string. In above example for
input() function I did not given any data type so it will take default data type
as string

example-3:

python program to check whether a person is eligible to vote or not

In the given Python program, we asked the user to enter the age of the
person by using the input() function. We use the int() function to convert
the user's entered age value to the integer.

# Python program to check vote eligibility

age = int(input("Enter age of a user: "))

if age >= 18:


print("eligible for voting ")
else:
print("not eligible for voting")

Output1:
Enter age of a user: 25
eligible for voting
Output2:
Enter age of a user: 13
not eligible for voting
Output3:
Enter age of a user: 18
eligible for voting
For complete python tutorials click here : ns lectures youtube channel

example-4
Python Program to Check if a Number is Odd or Even

Odd and Even numbers:

If you divide a number by 2 and it gives a remainder of 0 then it is known as


even number, otherwise an odd number.

Even number examples: 2, 4, 6, 8, 10, etc.

Odd number examples:1, 3, 5, 7, 9 etc.

num = int(input("Enter a number: "))


if (num % 2) == 0:
print(“Even number”)
else:
print("Odd number")

output:
Output 1

Enter a number: 43
Odd number

Output 2

Enter a number: 18
Even number

1. Chain multiple if statement in Python (elif statement):

The elif statement checks multiple conditions one by one and if the
condition fulfills, then executes that code.. In this variant of ‘if statement’,
there are many else if conditions declared. If the first condition does not
satisfy then the next condition is executed. But if this condition also does not
For complete python tutorials click here : ns lectures youtube channel

satisfy then the next condition is executed. statement. Syntax of the if-elif-
else statement:

if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement

Note – elif is short for else if. If the condition for if is FALSE then the elif
condition is checked and executed if found TRUE or, the statements after elif
are executed.
Flowchart –
For complete python tutorials click here : ns lectures youtube channel

Example

a = int(input('Enter number : '))

if (a<20):
print(“a value is lessthan 20 “)
elif (a==30):
print(“a value is equal to 30”)
elif (a==40):
print(“a value is equal to 40”)
else:
print(“number not found”)

output:
Enter number : 9
a value is lessthan 20

Enter number : 30
a value is equal to 30

Enter number : 100


Number not found

2. Nested if-else statement

In Python, the nested if-else statement is an if statement inside another if-


else statement. It is allowed in Python to put any number of if statements in
another if statement.

Indentation is the only way to differentiate the level of nesting. The nested
if-else is useful when we want to make a series of decisions.
For complete python tutorials click here : ns lectures youtube channel

Syntax of the nested-if-else:


if conditon_outer:
if condition_inner:
statement of inner if
else:
statement of inner else:
statement of outer if
else:
Outer else
statement outside if block

Example: Find a greater number between two numbers

num1 = int(input('Enter first number '))

num2 = int(input('Enter second number '))

if num1 >= num2:


if num1 == num2:
print(num1, 'and', num2, 'are equal')
else:
print(num1, 'is greater than', num2)
else:
print(num1, 'is smaller than', num2)

Output 1:
Enter first number 56
Enter second number 15
56 is greater than 15

Output 2:
Enter first number 29
Enter second number 78
29 is smaller than 78
For complete python tutorials click here : ns lectures youtube channel

Python Iterative Statements


Iteration statements or loop statements allow us to execute a block of
statements as long as the condition is true.

Loops statements are used when we need to run same code again and
again, each time with a different value.

Type of Iteration Statements In Python 3


In Python Iteration (Loops) statements are of three types :-

1. While Loop

2. For Loop

3. Nested For Loops

1. While Loop In Python

While Loop In Python is used to execute a block of statement as long as a


given condition is true. And when the condition is false, the control will
come out of the loop.

The condition is checked every time at the beginning of the loop.

While Loop Syntax


while (condition):

statements

Flowchart of While Loop


For complete python tutorials click here : ns lectures youtube channel

Example Of While Loop


x=0
while (x < 5):
print(x)
x= x+1

Output :-
0
1
2
3
4

Example of Infinite While Loop


For complete python tutorials click here : ns lectures youtube channel

x=1
while (x == 1):
print(‘hello’)

Output :-
hello
hello
hello
—–
—–

Using else statement with while loops


As discussed above, while loop executes the block until a condition is
satisfied. When the condition becomes false, the statement immediately
after the loop is executed.
The else clause is only executed when your while condition becomes
false. If you break out of the loop, or if an exception is raised, it won’t be
executed.
If else like this:
if condition:
# execute these statements
else:
# execute these statements
and while loop like this are similar
while condition:
# execute these statements
else:
# execute these statements
Python program Using else statement with while loop :
Password =” 123456”
For complete python tutorials click here : ns lectures youtube channel

Input_password=input(“enter password:”)
while password != input_password:
Input_password=input(“enter password:”)
else:
print(“unlocked!!!!!!!!!”)

output:
enter password:11111
enter password:135656
enter password:123456
unlocked!!!!!!!!!

2. For Loop In Python


For loop in Python is used to iterate over items of any sequence, such as a
list or a string.

For Loop Syntax


For val_name in range(start,stop):

statements

Flowchart of For Loop


For complete python tutorials click here : ns lectures youtube channel

Example of For Loop


for i in range(1,5):
print(i)

Output :-
1
2
3
4

The range() Function In Python


The range() function is a built-in that is used to iterate over a sequence of
numbers.

Syntax Of range() Function


range(start, stop)

The range() Function Parameters


start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.

Example2:

for i in range(10):

print(i)

output:
0
1
2
3
4
5
6
7
8
9
For complete python tutorials click here : ns lectures youtube channel

Note: In above example I did not given starting range, so by default it will
take value 0 ,

Example3:

n=4
for i in range(0, n):
print(i)

output:

Example4:

for loop to display the multiplication table of 5.

Program:

num = 5

for i in range(1, 11):

print(num, 'x', i, '=', num*i)

output:

5x1=5
5 x 2 = 10

5 x 3 = 15

5 x 4 = 20
For complete python tutorials click here : ns lectures youtube channel

5 x 5 = 25

5 x 6 = 30

5 x 7 = 35

5 x 8 = 40

5 x 9 = 45

5 x 10 = 50

3. Nested Loops In Python:


In Python programming language there are two types of loops which
are for loop and while loop. Using these loops we can create nested loops
in Python. Nested loops mean loops inside a loop. For example, while
loop inside the for loop, for loop inside the for loop, etc.

Python Nested Loops Syntax:


Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop

Program:

Printing multiplication table using Python nested for loops

for a in range(1, 6):

for b in range(1, 11):

print(a, "x", b, "=", a*b)


For complete python tutorials click here : ns lectures youtube channel

output:
1X1=1
1X2=2
1X3=3
1X4=4
1X5=5
1X6=6
1X7=7
1X8=8
1X9=9
1 X 10 = 10
2X1=2
2X2=4
2X3=6
2X4=8
2 X 5 = 10
2 X 6 = 12
2 X 7 = 14
2 X 8 = 16
2 X 9 = 18
2 X 10 = 20
3X1=3
3X2=6
3X3=9
3 X 4 = 12
3 X 5 = 15
3 X 6 = 18
3 X 7 = 21
3 X 8 = 24
3 X 9 = 27
3 X 10 = 30
4X1=4
4X2=8
4 X 3 = 12
4 X 4 = 16
4 X 5 = 20
4 X 6 = 24
4 X 7 = 28
4 X 8 = 32
For complete python tutorials click here : ns lectures youtube channel

4 X 9 = 36
4 X 10 = 40
5X1=5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
5 X 6 = 30
5 X 7 = 35
5 X 8 = 40
5 X 9 = 45
5 X 10 = 50

Loop control statements or transfer statements


Using loops in Python automates and repeats the tasks in an efficient
manner. But sometimes, there may arise a condition where you want to
exit the loop completely, skip an iteration or ignore that condition. These
can be done by loop control statements. Loop control statements
change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are
destroyed. Python supports the following control statements.

• Break statement
• Continue statement
• Pass statement

1. Break statement:
The break statement is used to terminate the loop or statement in which it
is present. After that, the control will pass to the statements that are
present after the break statement, if available. If the break statement is
present in the nested loop, then it terminates only those loops which
contains break statement.
Syntax:
break
For complete python tutorials click here : ns lectures youtube channel

Program:

for a in range(1,11):
print(a)
if a==5:
break

output:
1
2
3
4
For complete python tutorials click here : ns lectures youtube channel

2. Continue statement:
Continue is also a loop control statement just like the break
statement. continue statement is opposite to that of break statement,
instead of terminating the loop, it forces to execute the next iteration of the
loop.
As the name suggests the continue statement forces the loop to continue
or execute the next iteration. When the continue statement is executed in
the loop, the code inside the loop following the continue statement will be
skipped and the next iteration of the loop will begin.

Syntax:
Continue
For complete python tutorials click here : ns lectures youtube channel

program:

program to print odd numbers by using continue

for a in range(1,11):
if a%2==0:
continue
else:
print(a)

output:
1
3
5
7
9

3. Pass statement:
As the name suggests pass statement simply does nothing. The pass
statement in Python is used when a statement is required syntactically but
you do not want any command or code to execute. It is like null operation,
as nothing will happen if it is executed. Pass statement can be used for
writing empty loops, control statement, function and classes.
Syntax:
pass

Program:

if “a” in “india”:

pass

output:
For complete python tutorials click here : ns lectures youtube channel

in above example I don’t want to write any statements inside if condition,


but having an empty if condition will generate error, so I written pass, pass
statement simply does nothing.

Python Functions
The idea is to put some repeatedly done tasks together and make a
function so that instead of writing the same code again and again for
different inputs, we can do the function calls to reuse code contained in
it over and over again.

A function is a block of code which only runs when it is called.

You can pass values to a function known as parameters.A function can


return data as a result.

Syntax:

Types of function
There are two types of function in Python programming:
• Standard library functions - These are built-in functions in Python that
are available to use.
Example:type(), print(), len(), str()

• User-defined functions - We can create our own functions based on


our requirements.
Example:fun(), sum(), sai(), raju()
For complete python tutorials click here : ns lectures youtube channel

Creating a Python Function


We can create a Python function using the def keyword.

Program:
def fun():
print("my name is nagendra")

note:
when I run above program I will not get any output because I declared
function but I did not call function. If you want to print data inside
function then you need to call function by giving function name

Calling a Python Function


After creating a function we can call it by using the name of the function
followed by parenthesis

Example program:
#declaring a function

def fun():
print("my name is nagendra")

# call a function

fun()

output: my name is nagendra

In the below example I defined Python function once and I called


many times

Example program:
#declaring a function

def fun():
print("my name is nagendra")

# call a function 3 times


For complete python tutorials click here : ns lectures youtube channel

fun()
fun()
fun()

output:
my name is nagendra
my name is nagendra
my name is nagendra

function with parameters


data can be passed into functions as an arguments.

Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma.

program1:

#Defining a function
def function(a,b):
print (" two inputs are" ,a,b)
print("addition is:",a+b)
print("subtraction is:",a-b)

#Calling function and passing arguments


function(50,30)
function( 10, 20)
function( 60, 20)

output:
For complete python tutorials click here : ns lectures youtube channel

Program2:

# Defining a function

def fun (name):

print(" my name is " ,name)

# Calling function and passing arguments

fun ( "nagendra")

fun ( "sudeer")

fun ( "ganesh")

output:

Python return statement

A return statement is used to end the execution of the function call


and “returns” the result . The statements after the return statements
are not executed. If the return statement is without any expression,
then the special value None is returned . A return statement is overall
used to invoke a function so that the passed statements can be
executed.
Note: Return statement can not be used outside the function.

Program:

def name():

print("my name is nagendra") # here I am using print function

print(name())

output:
For complete python tutorials click here : ns lectures youtube channel

my name is nagendra

None

Program2

def name():

return "my name is nagendra" # here I am using return keyword

print(name())

output:

my name is nagendra

Program3

def name():

return "my name is nagendra" # here I am using return keyword

print(“hello”)

print(name())

output:

my name is nagendra

Note: in above program it will not print “hello” because the statements after
the return statements are not executed.

Types of function arguments


There are various ways to use arguments in a function. In Python, we have
thefollowing 4 types of function arguments.
1. Positional arguments
2. Keyword arguments (named arguments)
3. Default argument
4. Arbitrary arguments (variable-length arguments *args and
**kwargs)
For complete python tutorials click here : ns lectures youtube channel

1. Positional Arguments:

Positional arguments are those arguments where values get


assigned to the arguments by their position when the function is
called. For example, the 1st positional argument must be 1st when
the function is called. The 2nd positional argument needs to be 2nd
when the function is called, etc.

By default, Python functions are called using the positional


arguments.
Example: Program to subtract 2 numbers using
positional arguments. def data(name, rollno):

print(“my name is:”,name,”my roll no is :”, rollno)

data(“bhavani”, 10)

data(10, “bhavani)
For complete python tutorials click here : ns lectures youtube channel

output:

my name is : bhavani my roll no is :10

my name is : 10 my roll no is : bhavani

Note: If you try to pass more arguments, you will get an error.

Program:

def data(name, rollno):

print(“my name is:”,name,”my roll no is :”, rollno)

data(“bhavani”, 10,”hyderabad”)

output:

error

2. Keyword arguments (named arguments)

Usually, at the time of the function call, values get assignedto the
arguments according to their position. So we must pass values in the same
sequence defined in a function definition

For example, when we call student('Anurag', 692, 'B',), the value


“Anurag” gets assigned to the argument name, and similarly, 692 to
rollno and so on as per the sequence.
We can alter this behavior using a keyword argument.
Keyword arguments are those arguments where values get assigned to the
arguments by their keyword (name) when the function is called. It is assigned
by the variable name and an (=) assignment operator. The Keyword Argument is
also called a named argument
.
For complete python tutorials click here : ns lectures youtube channel

Program1:

def student(name, rollno , section):

print('Student Details:', name, rollno, section)

# 3 positional arguments

student(rollno=92,section=”B”,name='anurag')

output:

Student Details: anurag 92 B

3. Default argument:

In a function, arguments can have default values. We assign default


values to the argument using the ‘=’ (assignment) operator at the time of
function definition. You can define a function with any number of default
arguments.

The default value of an argument will be used inside a function if we do


not pass a value to that argument at the time of the function call. Due to
this, the default arguments become optional during the function call.
It overrides the default value if we provide a value to the default
arguments during function calls.
For complete python tutorials click here : ns lectures youtube channel

Program:

# function with keyword arguments i.e., section

def student(name, rollno , section="A")


print('Student Details:', name, rollno, section)

# without passing section Passing only the mandatoryarguments

student('anurag', 92 )

output:

Student Details: anurag 92 A

Program2:

# function with keyword arguments section

def student(name, rollno , section="A"):

print('Student Details:', name, rollno, section)

# here i am passing section as B so it will replace Awith B

student('anurag', 92, “B”)

output:

Student Details: anurag 92 B

Note:

It overrides the default value if we provide a value to the default


arguments during function calls.In above example i given default
argument as section="A" but i want to change it to section B , so i given
argument as B, now it will replace section=”A” with B.
For complete python tutorials click here : ns lectures youtube channel

4. Variable-length arguments

In Python, sometimes, there is a situation where we need to pass


multiple arguments to the function. Such types of arguments are
called arbitrary arguments or variable-length arguments.
We use variable-length arguments if we don’t know the number of
arguments needed for the function in advance.
Types of Arbitrary Arguments:
• arbitrary positional arguments (*args)
• arbitrary keyword arguments (**kwargs)

Arbitrary positional arguments (*args)

We can declare a variable-length argument with the * (asterisk) symbol.


Place an asterisk (*) before a parameter in the function definition to
define anarbitrary positional argument.
we can pass multiple arguments to the function. Internally all these
values are represented in the form of a tuple. Let’s understand the use of
variable-length arguments with an example.
Program:

def

students(*names):

print(names)

print(len(names))

print(type(names))

students("vinny","shruthi","rishitha","rahul")

Output:

('vinny', 'shruthi', 'rishitha', 'rahul')


For complete python tutorials click here : ns lectures youtube channel

4
<class 'tuple'>

Arbitrary keyword arguments (**kwargs)

We saw how to use *args. Now let’s see how to use the **kwargs
argument. The **kwargs allow you to pass multiple keyword arguments
to a function. Use the **kwargs if you want to handle named arguments in a
function.

Use the unpacking operator(**) to define variable-length keyword


arguments. Keyword arguments passed to a kwargs are accessed
using key- value pair (same as accessing a dictionary in Python).

Program:

def students(**names):

print(names)

print(len(names))

print(type(names))

students(name="shruthi",rollno=24)

output:

{'name': 'shruthi', 'rollno': 24}

2
<class 'dict'>
For complete python tutorials click here : ns lectures youtube channel

Scope of variable in python


Global variables are those which are not defined inside any function and have
a global scope whereas local variables are those which are defined inside a
function and its scope is limited to that function only.

Local variable Example:

def fun():

a = "hello" # a is local variable because we defined ‘a’ inside function


print(a)

fun()

output:

hello

Global Variables

These are those which are defined outside any function and which are
accessible throughout the program, i.e., inside and outside of every
function. Let’s see how to create a global variable.

Local variable Example:

def fun():
print(a)

a = "hello" # a is global variable because we defined ‘a’ outside function


fun()

output:
For complete python tutorials click here : ns lectures youtube channel

hello

lambda function

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have
one expression.

Syntax
lambda arguments : expression

The expression is executed and the result is returned:

Example

Add 10 to argument a, and return the result:

x = lambda a: a + 10

print(x(5))

output:

15
For complete python tutorials click here : ns lectures youtube channel

Python Function Recursion


Python also accepts function recursion, which means a defined function can call
itself.

Function which calls itself is know as recursion. This has the benefit of meaning that
you can loop through data to reach a result.

Example:

def name():

print(“my name is nagendra”)

name()

name()

output:

my name is nagendra

my name is nagendra

my name is nagendra

my name is nagendra

in above example I written name() function inside name() function, which means
function name() calls itself , so it keep on repeating same code again and again, so
we can loop statements by using recursion

Following is an example of a recursive function to find the factorial of an


integer.
For complete python tutorials click here : ns lectures youtube channel
Factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6
= 720 .

Example of a recursive function


def factorial(n):

if n == 1:

return 1

else:

return n * factorial(n-1)

n=5

print("The factorial of", n, "is", factorial(n))

output:

The factorial of 5 is 120

Built-In Functions
Python has a set of built-in functions.
1. input()
Input() Python built-in functions, reads an input.
Example:
a=int(input(“enter no:”))
print(a)
output:
enter no: 10
10
2. eval()
Eval( ) function will accept any data type values that you enter.
Example:
a=eval(input(“enter no:”))
print(a)
output:
enter no: 10
For complete python tutorials click here : ns lectures youtube channel
10
3. exec()
exec() runs Python code dynamically.
>>> exec('a=2;b=3;print(a+b)')
Output
5
4. hex()
Hex() Python built-in functions, converts an integer to hexadecimal.
>>> hex(16)
Output
‘0x10’
5. id()
id() returns an object’s identity(address).
>>> id(orange)
Output
100218832
6. len()
We’ve seen len() so many times by now. It returns the length of an object.
Example:
a=(1,2,3,4,5,6,7)
print(len(a))
output:
7
7. max()
max() returns the item, in a sequence, with the highest value of all.

Example:
a=(1,2,3,4,5,6,7)
print(max(a))
output:
7
8. min()
For complete python tutorials click here : ns lectures youtube channel
min() returns the item, in a sequence, with the smallest value of all.

Example:
a=(1,2,3,4,5,6,7)
print(min(a))
output:
1
9. pow()

pow() takes two arguments- say, x and y. It then returns the value of x to the power of y.
>>> pow(3,4)
Output
81

10. print()
We don’t think we need to explain this anymore. We’ve been seeing this function since the
beginning.
>>> print("hi”)
output:
hi

11. repr()
repr() returns a representable string of an object.
>>> repr("Hello")
Output
“‘Hello'”

12. range()
we use range ( ) function in order to print values in sequence
example:
>>> for i in range(1,6):
print(i)
Output
1
2
3
4
5
For complete python tutorials click here : ns lectures youtube channel

13. sorted()
Like we’ve seen before, sorted() prints out a sorted version of an iterable. It does not, however, alter
the iterable.
>>> sorted('Python')
Output
[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]

14. sum()
The function sum() takes an iterable as an argument, and returns the sum of all values.

>>> sum([3,4,5],3)
Output
15

15. type()
We have been seeing the type() function to check the type of object we’re dealing with.

>>> type(10)
Output
<class ‘int’>

other built in functions :


int(), float(), str(), complex( ), list ( ) , tuple ( ) , set ( ) .
Example:
print(int(10.5)) #converting float value to int
print(int("10")) #converting string to int
print(float(10)) #converting int to float
print(float("10.5")) #converting string to float
print(str(10)) #converting int to str
print(str(10.5)) #converting float to str
print(complex(1,2.3)) #converting int and float numbers to complex
print(list((1,2.4,"btech"))) #converting tuple to list
print(tuple([1,2.4,"btech"])) #converting list to tuple
For complete python tutorials click here : ns lectures youtube channel
print(set([1,2.4,"btech"])) #converting list to set
output:
10
10
10.0
10.5
10
10.5
(1+2.3j)
[1, 2.4, 'btech']
(1, 2.4, 'btech')
{'btech', 1, 2.4}
For complete python tutorials click here : ns lectures youtube channel

PYTHON SEQUENCES
A sequence is a group of items with a deterministic ordering. The order
in which we put them in is the order in which we get an item out from
them.
Operations on Python Sequences:
Various operations we can perform on the sequences they are
1. Concatenation:
The operator (+) is used to concatenate the second element to
the first.
For example – [1,3,4] + [1,1,1] will evaluate to [1,3,4,1,1,1].
We can concate all other sequences like this.

2. Repeat:
The operator (*) is used to repeat a sequence n number of times.
For example – (1,2,3) * 3 will evaluate to (1,2,3,1,2,3,1,2,3).
This also works on sequences other than tuples.

3. Membership testing:
Membership operators (in) and (not in) are used to check whether an
item is present in the sequence or not. They return True or False.
For example – ‘india’ in “I love india” evaluates to True and
‘india’ not in “I love india” evaluates to False.

4. Slicing
All the sequences in Python can be sliced. The slicing operator
can take out a part of a sequence from the sequence.

5. indexing:
you can access python objects by giving index numbers. Index number
starts from 0.
For complete python tutorials click here : ns lectures youtube channel

Python Sequence Functions:

Python sequences are classified in three types they are:

1. string
2. list
3.tuple
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel

String Comparison in Python:

The simplest way to check if two strings are equal in Python is to use the == operator.And if
you are looking for the opposite, then != is what you need. That's it!

== and != are boolean operators, meaning they return True or False. Forexample, ==
returns True if the two strings match, and False otherwise

Whereas is operator checks whether both the operands refer to the same object or
not. The same is the case for != and is not.

Program:
a="hyderabad"
b="india"
print( a is b)
print( a is not b)
print(a==b)
print(a!=b)
output:
False
True
False
True

The relational operators compare the Unicode values of the characters of the
strings from the zeroth index till the end of the string. It then returns a boolean
value according to the operator used.
Program:
a="hyderabad"
b="india"
print( a < b)
print( a > b)

output:
True
False

Python String Methods

Python has a set of built-in methods

Strings are not mutable in Python. Strings are a immutable data


For complete python tutorials click here : ns lectures youtube channel

types which means that its value cannot be updated.


Note: All string methods returns new values. They do not change the original string.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value

expandtabs() Sets the tab size of the string

find() Searches the string for a specified value and returns the position of where it was
fou

format() Formats specified values in a string

format_map() Formats specified values in a string

index() Searches the string for a specified value and returns the position of where it was
fo

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters
For complete python tutorials click here : ns lectures youtube channel

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits

isidentifier() Returns True if the string is an identifier

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable() Returns True if all characters in the string are printable

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Converts the elements of an iterable into a string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string

maketrans() Returns a translation table to be used in translations

partition() Returns a tuple where the string is parted into three parts
For complete python tutorials click here : ns lectures youtube channel

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the

lastposition of where it was found

rindex() Searches the string for a specified value and returns the

lastposition of where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value

strip() Returns a trimmed version of the string

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case


For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel

Python Sets
Sets are used to store multiple items in a single variable. Sets can also
be used to perform mathematical set operations like union, intersection,
symmetric difference, etc.

Set are represented by { } .

Program:

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


print(a)

print(type(a))

print(len(a))

output:

{‘apple’, ‘banana’, ‘cherry’}

<class ‘set’>

From above example, to determine how many items a set has, use
the len() function.
type() is used to identify data type, so it will display data type as “set”

A set is an unordered collection of items.

• The elements in the set cannot be duplicates.


• The elements in the set are immutable(cannot be modified) but the
set as a whole is mutable.
• There is no index attached to any element in a python set. So they
do not support any indexing or slicing operation.

Duplicates Not Allowed

Sets cannot have two items with the same value.


For complete python tutorials click here : ns lectures youtube channel

Program:

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

print(a)

output:

{ ‘banana’, ‘cherry’, ‘apple’}

In above example “apple” is repeated twice but it will not allow


duplicates, so it will display “apple” only once.

Unordered

Unordered means that the items in a set do not have a defined


order.

Program:

a = {1,2,3,4}

print(a)

output:

{ 3,2,1,4}

From above example, you will not get output in order.

Unchangeable

Set items are unchangeable, meaning that we cannot change the items
after the set has been created.

Once a set is created, you cannot change its items, but you can remove
items and add new items.

Set items can be of any data type:


For complete python tutorials click here : ns lectures youtube channel

Program:

a = {"abc", 34, True, 40, "male"}

print(a)

output:

{True, 34, 40, 'male', 'abc'}

The set() Constructor

It is also possible to use the set() constructor to make a set.

Program:

a = set(("apple", "banana", "cherry"))

print(a)

output:

{'cherry', 'banana', 'apple'}

Access Items

You cannot access items in a set using a for loop.

Program:

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

for x in a:

print(x)

output:

apple
cherry
banana

To check member or not

Check if "banana" is present in the set:


For complete python tutorials click here : ns lectures youtube channel

Program:

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

print("banana" in a)

output:

True

Set Methods

Python has a set of built-in methods that you can use on sets.

Method Description

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() Returns a set containing the difference between

two or more sets

difference_update() Removes the items in this set that are also included

in another, specified set

discard() Remove the specified item

intersection() Returns a set, that is the intersection of two other sets


For complete python tutorials click here : ns lectures youtube channel

intersection_update() Removes the items in this set that are not present

in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or not

issubset() Returns whether another set contains this set or not

issuperset() Returns whether this set contains another set or not

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() Returns a set with the symmetric differences of two sets

symmetric_difference_update() inserts the symmetric differences from this set and

another

union() Return a set containing the union of sets

update() Update the set with the union of this set and others

Set operations

Add Items:

Once a set is created, you cannot change its items, but you can
add new items.

To add one item to a set use the add() method.


For complete python tutorials click here : ns lectures youtube channel

add() method:

Program:
a = {"apple", "banana", "cherry"}
a.add("orange")
print(a)
output:
{'cherry', 'banana', 'apple', 'orange'}

Combine two Sets:

To add items from another set into the current set, use
the update() method.

update() method:

Program:

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

b = {"pineapple", "mango", "papaya"}

a.update(b)

print(a)

output:

{'banana', 'cherry', 'mango', 'pineapple', 'papaya', 'apple'}

The object in the update() method does not have to be a set, it


can be any iterable object (tuples, lists, dictionaries etc.).

Program:

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


For complete python tutorials click here : ns lectures youtube channel

b = ["pineapple", "mango", "papaya"]

a.update(b)

print(a)

output:

{'banana', 'cherry', 'mango', 'pineapple', 'papaya', 'apple'}

Remove Item:

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

remove() method:

Program

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

a.remove("banana")

print(a)

output:

{'apple', 'cherry'}

Note: If the item to remove does not exist, remove() will raise an error.

discard() method:

Program:

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

a.discard("banana")

print(a)

output:

{'apple', 'cherry'}

Note: If the item to remove does not exist, discard()will NOT raise an
error.
For complete python tutorials click here : ns lectures youtube channel

del keyword

The del keyword will delete the set completely:

Program:

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

del a

print(a)

output:

this will raise an error because the set no longer exists

You can also use the pop() method. Sets are unordered, so
when using the pop() method, you do not know which item
that gets removed.so don’t use pop() method in sets.

Join Two Sets:

There are several ways to join two or more sets in Python.

You can use the union() method that returns a new set containing all
items from both sets, or the update() method that inserts all the items
from one set into another:

union() method:

program

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

b = {1, 2, 3}

c = a.union(b)

print(c)

output:

{1, 2, 3, 'c', 'a', 'b'}


For complete python tutorials click here : ns lectures youtube channel

update()method:

The update() method inserts the items in b into a:

program:
a = {"a", "b" , "c"}
b = {1, 2, 3}
a.update(b)
print(a)

output:

{'a', 'c', 1, 2, 3, 'b'}

Note: Both union() and update() will not include any duplicate items

intersection() method:

The intersection() method will return a new set, that only contains the
items that are present in both sets.
Program:

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

b = {"google", "microsoft", "apple"}

c = a.intersection(b)

print(c)

output:

{'apple'}

intersection_update() method:

The intersection_update() method will keep only the same items that are
present in both sets.
For complete python tutorials click here : ns lectures youtube channel

Program:

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

b = {"google", "microsoft", "apple"}

a.intersection_update(b)

print(a)

output:

{'apple'}

symmetric_difference() method:

The symmetric_difference() method will return a new set, that contains


only the elements that are NOT present in both sets.

Program:

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

b = {"google", "microsoft", "apple"}

c = a.symmetric_difference(b)

print(c)

output:

{'google', 'banana', 'microsoft', 'cherry'}

symmetric_difference_update() method:

The symmetric_difference_update() method will keep only the elements


that are NOT present in both sets.

Program:

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

b = {"google", "microsoft", "apple"}


For complete python tutorials click here : ns lectures youtube channel

a.symmetric_difference_update(b)

print(a)

output:

{'microsoft', 'banana', 'cherry', 'google'}

Python Dictionary
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow
duplicates.
Dictionaries are written with curly brackets, and have keys and values.
To determine how many items a dictionary has, use the len() function.
The values in dictionary items can be of any data type.

From Python's perspective, dictionaries are defined as objects with the data
type 'dict'.

program:
a={"Name": "Amrit", "rollno": "21VE1A6698", "age": 18}
print(a)
print(len(a))
print(type(a))
output:
{'Name': 'Amrit', 'rollno': '21VE1A6698', 'age': 18}
3
<class 'dict'>
Dictionary items are ordered:
When we say that dictionaries are ordered, it means that the items have a
defined order, and that order will not change.In which order you given input in
same order you receive output. Unordered means that the items does not
have a defined order.

Changeable
Dictionaries are changeable, meaning that we can change, add or remove
items after the dictionary has been created
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
For complete python tutorials click here : ns lectures youtube channel
program:
a={"Name": "Amrit", "Name": "Amrit","rollno": "21-V98","age": 18,"age": 21}
print(a)
output:
{'Name': 'Amrit', 'rollno': '21-V98', 'age': 21}

In above example i written “Name”:”Amrit” twice, but Dictionaries cannot have


duplicate values so it will print “Name”:”Amrit” only once and similarly
I written "age": 18 and "age": 21 here, key “age” repeated twice but it will print
only one key with is given at last so you will get output “key”:21

The dict() Constructor


It is also possible to use the dict() constructor to make a dictionary.
Program:
a = dict(name = "ramya", age = 18, country = "INDIA")
print(a)
output:
{'name': 'ramya', 'age': 18, 'country': 'INDIA'}

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description
clear() Removes all the elements from the dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
Returns the value of the specified key. If the key does not exist:
setdefault()
insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs
values() Returns a list of all the values in the dictionary
For complete python tutorials click here : ns lectures youtube channel
dictionary operations
Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:
program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}


print(a[‘name’])
output:
ramya
There is also a method called get() that will give you the same result:
get( ) method:
program:
a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}
print(a.get(‘name’))
output:
ramya

Get Keys, Get Values, Get items :

The keys() method will return a list of all the keys in the dictionary.

The values() method will return a list of all the values in the dictionary.

The items() method will return each item in a dictionary, as tuples in a list.

keys( ) method, values() method, items() method :


Program:
a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}
print(a.keys())
print(a.values())
print(a.items())
For complete python tutorials click here : ns lectures youtube channel
output:
dict_keys(['name', 'age', 'country'])
dict_values(['ramya', 18, 'INDIA'])
dict_items([('name', 'ramya'), ('age', 18), ('country', 'INDIA')])
changing values :

program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

a["name"]="rajesh"

print(a)

output:

{'name': 'rajesh', 'age': 18, 'country': 'INDIA'}

Adding new key and value:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

a["name2"]="rajesh"

print(a)

output:

{'name': 'ramya', 'age': 18, 'country': 'INDIA', 'name2': 'rajesh'}

You can change the value of a specific item by referring to its key name:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}


a["name"]="rajesh"
print(a)

output:

{'name': 'rajesh', 'age': 18, 'country': 'INDIA'}


For complete python tutorials click here : ns lectures youtube channel
Check if Key Exists

To determine if a specified key is present in a dictionary use the in keyword:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

if "name" in a:

print("Yes, 'name' is one of the keys in the dictionary")

output:

Yes, 'name' is one of the keys in the dictionary

Update Dictionary

The update() method will update the dictionary with the items from the given
argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

update() method:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

a.update({"city": "hyderabad"})

print(a)

output:

{'name': 'ramya', 'age': 18, 'country': 'INDIA', 'city': 'hyderabad'}

Removing Items

There are several methods to remove items from a dictionary:

pop() method:

The pop() method removes the item with the specified key name:
For complete python tutorials click here : ns lectures youtube channel

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

a.pop("name")

print(a)

output:

{'age': 18, 'country': 'INDIA'}

popitem() method:

The popitem() method removes the last inserted item

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

a.popitem()

print(a)

output:

{'name': 'ramya', 'age': 18}

del keyword:

The del keyword removes the item with the specified key name:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

del a["name"]

print(a)

output:

{'age': 18, 'country': 'INDIA'}


For complete python tutorials click here : ns lectures youtube channel

The del keyword can also delete the dictionary completely:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

del a

print(a)

output:

error

output is error because we deleted dictionary completely

clear() method:

The clear() method empties the dictionary:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

a.clear()

print(a)

output:

{ }

Loop Through a Dictionary:


You can loop through a dictionary by using a for loop.

When looping through a dictionary, the return value are the keys of the dic-
tionary, but there are methods to return the values as well.

Print all key names in the dictionary, one by one:

Program:
For complete python tutorials click here : ns lectures youtube channel
a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

for x in a:

print(x)

output:
name
age
country

Print all values in the dictionary, one by one:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

for x in a:

print(a[x])

output:

ramya
18
INDIA

Copy a Dictionary

You cannot copy a dictionary simply by typing dict2 = dict1,

because: dict2 will only be a reference to dict1, and changes made


in dict1 will automatically also be made in dict2.

There are ways to make a copy, one way is to use the built-in Dictionary
method copy().

Copy( ) method:

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

b = a.copy()

print(b)
For complete python tutorials click here : ns lectures youtube channel
output:

{'name': 'ramya', 'age': 18, 'country': 'INDIA'}

dict( ) method:

Another way to make a copy is to use the built-in function dict()

Program:

a={'name': 'ramya', 'age': 18, 'country': 'INDIA'}

b = dict(a)

print(b)

output:

{'name': 'ramya', 'age': 18, 'country': 'INDIA'}

Nested Dictionaries

A dictionary can contain dictionaries, this is called nested dictionaries.

Program:
a = { "sectionA":{ "name" : "ramesh", "rollno":21},"sectionB":{ "name" : "ra-
hul", "rollno":25}}
print(a)

output:
{'sectionA': {'name': 'ramesh', 'rollno': 21}, 'sectionB':
{'name': 'rahul', 'rollno': 25}}

Or, if you want to add three dictionaries into a new dictionary:

Create two dictionaries, then create one dictionary that will contain the other
two dictionaries:

PROGRAM:

sectionA={ "name" : "ramesh", "rollno":21}


For complete python tutorials click here : ns lectures youtube channel
sectionB={ "name" : "rahul", "rollno":25}

a = {"sectionA":sectionA,"sectionB":sectionB}

print(a)

OUTPUT:

{'sectionA': {'name': 'ramesh', 'rollno': 21}, 'sectionB': {'name': 'rahul', 'rollno': 25}}

Python object
Python is an object-oriented programming language. Everything is in Python treated as an
object, including variable, function, list, tuple, dictionary, set, etc. Every object belongs to
its class. For example - An integer variable belongs to integer class. An object is a real-life
entity. An object is the collection of various data and functions that operate on those data.
An object contains the following properties.

Value:
data item that is represented by an object
Example:
a=10 #here 10 is value
print(a)
output:

10

Type:
an object’s type indicates what kind of values an object can hold. what operations can be applied to
such objects. type ( ) function is used to find type of object
Example:
a=10
print(type(a))
output:
<class ‘int’>

Identity :
Each object contains unique identity that differentiates from all other objects. And you can check id
of an object by using id ( ) function.
Example:
For complete python tutorials click here : ns lectures youtube channel
a=10
print(id(a))
output:
9789280

literals and types of literal constants


literal is a raw data given to variable or constant
in python there are various types of literals they are

1. numberic literals :
3 types – integer, float, complex
Example:
a=10
b=10.5
c=1+2j
print(a)
print(b)
print(c)
output:
10
10.5
1+2j
2. string literals :
Example:
a=”hello”
print(a)
output:

hello
3. special literals :
None
For complete python tutorials click here : ns lectures youtube channel
if you dont want to give any value to the variable then you can use None
Example:
a=None
print(a)
output:

here you will not get any output because None means nothing

python - Type conversion


type conversion is the process of converting data of one type to another. For example:
converting integer data to string.
There are two types of type conversion in Python.
• Implicit Conversion - automatic type conversion
• Explicit Conversion - manual type conversion

1. Implicit Type Conversion:


In certain situations, Python automatically converts one data type to another. This is
known as implicit type conversion.
Python always converts smaller data types to larger data types to avoid the loss of
data.
Integer is smaller than float and float is smaller than string
Example:
a=10
b=10.5
c=a+b
print(c)
output:
20.5
For complete python tutorials click here : ns lectures youtube channel
In the above example, I took a value as 10 which is integer and b value as 10.5 which
is float .though i given one value as integer and other value as float , i got output as
float value because Python always converts smaller data types to larger data types to
avoid the loss of data. In this example integer value is smaller than float value, so
integer value 10 is automatically converted into float value,so i got output 20.5 which
is float value.
2. Explicit Type Conversion:
In Explicit Type Conversion, Python cannot automatically converts one data type to
another so, users converts one data type to another manually .
We use the built-in functions like int(), float(), str(), complex( ), list ( ) , tuple ( ) ,
set( ) to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the
data type of the objects.
Example:
print(int(10.5)) #converting float value to int
print(int("10")) #converting string to int
print(float(10)) #converting int to float
print(float("10.5")) #converting string to float
print(str(10)) #converting int to str
print(str(10.5)) #converting float to str
print(complex(1,2.3)) #converting int and float numbers to complex
print(list((1,2.4,"btech"))) #converting tuple to list
print(tuple([1,2.4,"btech"])) #converting list to tuple
print(set([1,2.4,"btech"])) #converting list to set
output:
10
10
10.0
10.5
10
10.5
For complete python tutorials click here : ns lectures youtube channel
(1+2.3j)
[1, 2.4, 'btech']
(1, 2.4, 'btech')
{'btech', 1, 2.4}

explicit type conversion program 2:

Example:
a=10
b=”10” #when you take 10 in double quotes then it is string
c=a+b
print(c)
output:
error
In above example it will display error because we cannot add integer value and string
value
So you need to convert string “10” to integer value by using int( ) function.
Example:
a=10
b="10” #when you take 10 in double quotes then it is string
c=a+int(b) # now i converted string 10 to integer value by using int( )
print(c)
output:
20
For complete python tutorials click here : ns lectures youtube channel

Python - Internal types

1) Traceback:
when you get an error it is recommended that you should trace it
backward(traceback). Whenever the code gets an exception(error), the
traceback will give the information about what went wrong in the
code.The Python traceback contains great information that can help
you find what is going wrong in the code.

Example:

a = [1, 2, 3]
print(a[10])

output:.
Traceback (most recent call last):
File "", line 2,
inprint(a[10])
IndexError: list index out of range

In above example, we are trying to access the 10th element of the list.
With only 3 elements present in the list it will give Runtime error. When
this program is executed you will get the above traceback.

2) Slice:
A slice object is used to specify how to slice a sequence. You can
specify where to start the slicing, and where to end. You can also
specifythe step
The slice() function returns a slice object.

Syntax
slice(start, end, step)

Example:

a = ("a", "b", "c", "d", "e", "f", "g", "h")

x = slice(3, 5)
For complete python tutorials click here : ns lectures youtube channel
print(a[

x])

output:
('d', 'e')

3) Xrange():

Xrange objects are created by xrange( ) function. In python3 there is


noxrange ( ) function so, range ( ) function behaves like xrange( )
function.

xrange() – This function returns the generator object that can be used
todisplay numbers only by looping.

To loop through a set of code a specified number of times, we can use


the range() function,

The range() function returns a sequence of numbers, starting from 0


bydefault, and increments by 1 (by default), and ends at a specified
number.

Example:
for x in range(1,6):
print(x)

output:
1
2
3
4
5

4) code:
Code objects are executable pieces of python source that are byte
compiled, usually as return values form calling the compile ( ) . such
objects are appropriate for execution by either exec( ) or by the eval(
).

Code objects themselves do not contain any information regarding


theirexecution environment, but they are at the heart of every user-
defined function, all of which do contain some execution context.
For complete python tutorials click here : ns lectures youtube channel
5) frame:

These are objects representing execution stack frames in python


Frame objects contain all the information the python interpreter needs
toknow during a runtime execution environment. Each function call
resultsin a new frame object , and for each frame object, a C stack
frame is created.
6) ellipsis:

you can use the ellipsis to indicate that you’re leaving something out.
Essentially, you use three dots (...) .it is same like pass statement.

Program:
def fun():
...
fun()

When you run above program There’s no error when you execute a
function in Python that contains only( ...) in the function body. That means
you can use an ellipsis as a placeholder similar to the pass keyword.

Other built in types

Type
Null object ( None )
File
Set
Function /
MethodModule
Class
Differences Between C and Python
Comparison
C Python
Parameter
The Python programming
The C programming language was
Developed / language was first worked upon by
developed by Dennis M. Ritchie in
Founded by Guido van Rossum and was
1972.
released in the year 1991.
For complete python tutorials click here : ns lectures youtube channel
Programming C is a procedural programming Python is an object oriented
model language programming language.
Python is a high-level language as
C is a middle level language as it
Type of the translation of Python code
binds the bridges between machine
language takes place into machine
level and high level languages.
language, using an interpreter.
C is a compiled programming Python is an interpreted
language. Special programs known programming language. Special
Compilation
as compilers check the C code line programs known as interpreters
and
by line and if any error is found on check the entire Python code and
Interpretation
any line, the program compilation all the errors in the entire Python
stops then and there. code is reported at once.
Python programs are usually
C is a faster language compared to
Speed slower than C programs as they
Python as it is compiled.
are interpreted.
In Python, variables are untyped,
In C, the type of the various that is, there is no need to define
variables must be declared when the data type of a variable while
Variable
they are created, and only values of declaring it. A given variable in
Declaration
those particular types must be Python can store values of
assigned to them. different data types in different
parts of the Python code.
Memory management is
Memory Memory management needs to be automatically handled in Python by
Management done manually in C. the Garbage Collector provided by
it.
Pointers C has support for pointers. Python has no support pointers.
In C, mostly the functional units are In Python, mostly the functional
Functional
functions as it is a procedural units are objects as it is an object
Units
programming language. oriented programming language.
Python is a more robust
C is a less robust programming programming language compared
Robustness
language compared to Python. to C as it has strong memory
management schemes.

The C programming language is


Python is a general purpose
Applications mostly used for the development of
programming language
hardware applications.
Built-in The number of built-in functions in C There are a lot of built-in functions
functions are very limited. in Python.
To use various data structures like It is easier to use Data Structures
Usage of Data
stacks, queues, etc. in C, we need in Python as it provides built in
Structures
to implement them on our own. libraries for the same.
For complete python tutorials click here : ns lectures youtube channel
Python does not allow inline
In line C allows inline assignment. For
assignment. For instance, a = 5;
assignment. instance: int a = 5; runs well in C.
throws an error in python.
C codes are stored with .c Python codes are stored with .py
Type of file
extension. extension.

C++ Vs Java Vs Python


The following table summarizes the significant differences between C++ vs. Java
vs Python.
TOPIC C++ Java Python
Compiled Interpreted
Compiled vs. Java is both Compiled
Programming Programming
Interpreted and Interpreted.
Language Language

Platform C++ is platform Java is platform- Python is platform-


Dependence dependent independent independent

C++ supports Python supports


Operator Java does not support
operator operator
Overloading operator overloading
overloading overloading

In Java, single
inheritance is possible Python provides
C++ provides both
while multiple both single and
Inheritance single and multiple
inheritances can be multiple
inheritances
achieved using inheritances
Interfaces

C++ does not have


built-in support for
Java has built-in Python supports
Thread Support threads; It
thread support multithreading
depends on
Libraries
For complete python tutorials click here : ns lectures youtube channel
C++ is very fast.
It’s, in fact, the first Java is much faster Due to the
Execution Time than Python in terms interpreter, Python
choice of
of speed of execution is slow in terms of
competitive
but slower than C++. execution
programmers

Every bit of Functions and


Functions and
Program code(variables and variables can be
variables are used
Handling functions) has to be declared and used
outside the class
inside the class itself. outside the class

Java provides library Python has a huge


C++ has limited
Library Support support for many set of libraries and
library support
concepts like UI modules.

Code length is
Java code length is
lesser than Java, Python has a small
Code Length bigger than Python
around 1.5 times code length
and C++.
less.
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python tutorials click here : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel

UNIT – 2
FILES:
File Objects
File built in functions( open( ) ) and built in methods

File Builtin Attributes


Standard Files
Command Line Arguments
FileSystem
File Execution
Persistent storage modules And Related modules

EXCEPTIONS:
Exceptions in python
Detecting and Handling Exceptions
Context management
*Exceptions as strings
Raising Exceptions
Assertions
Standard Exceptions
*Creating Exceptions
Why Exceptions (now)? , Why Exceptions at All?
Exceptions and sys module and related modules
MODULES:

Modules and Files


Namespaces
For complete python subject tutorials visit : ns lectures youtube channel

Importing Module Attributes


Module built in functions
Packages
Other features of modules
For complete python subject tutorials visit : ns lectures youtube channel

File Handling
File handling is an important part of any web application.

Python provides inbuilt functions for creating, writing, and reading files.
There are two types of files that can be handled in python,normal text
files and binary files (written in binary language,0s,and1s).

Python File Modes


There are four different methods (modes) for opening a file:

"r" - Read - Default value. Opens a file for reading, error if the file does
not exist

"a" - Append - Opens a file for appending, creates the file if it does not
exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

In addition you can specify if the file should be handled as binary or text
mode

"t" - Text - Default value. Text mode


"b" - Binary - Binary mode (e.g. images)
Read and Write (‘r+’): Open the file for reading and writing. The
handle is positioned at the beginning of the file. Raises I/O error if the
file does not exist.
Write and Read (‘w+’) : Open the file for reading and writing. For an
existing file, data is truncated and over-written. The handle is
positioned at the beginning of the file.
Append and Read (‘a+’) : Open the file for reading and writing. The file
is created if it does not exist. The handle is positioned at the end of the
file. The data being written will be inserted at the end, after the existing
data.
For complete python subject tutorials visit : ns lectures youtube channel

Python File Methods


Python has a set of methods available for the file object.

Method Description

close() Closes the file

read() Returns the file content

readline() Returns one line from the file

readlines() Returns a list of lines from the file

seek() Change the file position

tell() Returns the current file position

writable() Returns whether the file can be written to or not

write() Writes the specified string to the file

writelines() Writes a list of strings to the file

tru ncate() : Resizes the file to a specified size


flush() : Flushes the internal buffer

The key function for working with files in Python is the open() function.

The open() function takes two parameters; filename, and mode.


For complete python subject tutorials visit : ns lectures youtube channel

create a File
"x" mode is used Create the specified file, returns an error if the file
exists

Example:
f = open("C:/Desktop/file.txt", "x")

f.close()

when ever you run above code in python it will create file in desktop with
name file.txt .“x” mode is used to create file and I want to create file in
my desktop so you need to given location "C:/Desktop/file.txt" for
example if you want to create file in location: local disk D then just
give location “D: /file.txt".

if file.txt is already present then it will display error

whenever you open a file, at last you need to close file by using close()
function

Open a File

Syntax

To open a file for reading it is enough to specify the name of the file:

"r" - Read - Default value. Opens a file for reading, error if the file does
not exist

f = open("file.txt")

The code above is the same as:

f = open("file.txt", "r")

To print text present in my file on output :


Assume we have the following file, located in the Desktop, let file name
is file.txt , let file contains text given below:

file.txt
For complete python subject tutorials visit : ns lectures youtube channel

Hello! Welcome to hyderabad


This is nagendra sai.
Good Luck!

To open the file, use the built-in open() function.

read() method for reading the content of the file:

Example
f = open("C:/Desktop/file.txt", "r")

print(f.read())

f.close()
output:

Hello! Welcome to hyderabad


This is nagendra sai.
Good Luck!

In the above example,I want to open file which is present in my desktop


so you need to specify path like “C:/Desktop/file.txt”. If the file is located
in a different location, you will have to specify the file path.

I want to read text present in file.txt . so , I am using “r” mode to read


text present in file named file.txt , by using read mode you can only read
a file .
read( ) function is used to read text present in my file and print( )
function is used to print text on my output screen so I written
print(f.read()).

whenever you open a file, at last you need to close file by using close()
function
Note: Make sure the file exists, or else you will get an error

Read Only Parts of the File:

By default the read() method returns the whole text, but you can also
specify how many characters you want to return:
For complete python subject tutorials visit : ns lectures youtube channel

Assume we have the following file, located in the Desktop, let file name
is file.txt , let file contains text given below:

file.txt
Hello! Welcome to hyderabad
This is nagendra sai.
Good Luck!
Example
f = open("C:/Desktop/file.txt", "r")

print(f.read(5))

f.close()
output:

Hello
In above example I written print(f.read(5)) so it will print only first 5
characters. So , I will get output hello

whenever you open a file, at last you need to close file by using close()
function

readline() method

You can return one line by using the readline() method:

Assume we have the following file, located in the Desktop, let file name
is file.txt , let file contains text given below:

file.txt
Hello! Welcome to hyderabad
This is nagendra sai.
Good Luck!
Example
f = open("C:/Desktop/file.txt", "r")

print(f.readline())

f.close()
For complete python subject tutorials visit : ns lectures youtube channel

output:

Hello! Welcome to Hyderabad

By calling readline() two times, you can read first two lines:

Program to print characters for a file using readline() method

Example
f = open("C:/Desktop/file.txt", "r")

print(f.readline(3)) #it will print first 3 characters in my file

f.close()
output:

Hel

By looping through the lines of the file, you can read the whole file, line
by line:

Example

Loop through the file line by line:


f = open("C:/Desktop/file.txt", "r")

for x in f:

print (x)

f.close()

output:

Hello! Welcome to hyderabad


This is nagendra sai.
Good Luck!

It is a good practice to always close the file when you are done with it.

readlines() method:

Returns a list of lines from the file


For complete python subject tutorials visit : ns lectures youtube channel

Assume we have the following file, located in the local disk E, let file
name is sai.txt , let file contains text given below:

file.txt

hello ramesh
i am nagendra

i am from hyderabad
program:

a=open("E:/sai.txt","r")

print(a.readlines())

a.close()

output:

['hello ramesh\n', 'i am nagendra \n', 'i am from hyderabad \n']

Python File Write


Write to an Existing File

To write to an existing file, you must add a parameter to


the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Assume we have the following file, located in the Desktop, let file name
is file.txt , let file contains text given below:

file.txt

Hello! Welcome to hyderabad


This is nagendra sai.
Good Luck!
For complete python subject tutorials visit : ns lectures youtube channel

Program: to add text “ how are you ? “ at last in my file


named file.txt
f = open("C:/Desktop/file.txt ", "a") #use “a” mode to add text
f.write("how are you ? “)

f.close()

open and read the file after the appending:


f = open("file.txt", "r") # use “r” mode to print data as output

print(f.read()) #print( ) function to print output

f.close()

output:

Hello! Welcome to hyderabad


This is nagendra sai.
Good Luck!
how are you?

For above example, use “a” mode to add text in my file named file.txt.

Program: to replace my file text with “ how are you?” using


“w” mode

"w" - Write - will overwrite any existing content

My file contains text:

Hello! Welcome to hyderabad


This is nagendra sai.
Good Luck!

Now it will replace ths text with “how are you?”

Program:

f = open("file.txt", "w") #use “w” mode to add text to my file

f.write("how are you ? “)


For complete python subject tutorials visit : ns lectures youtube channel

f.close()

#open and read the file after the appending:


f = open("file.txt", "r") # use “r” mode to print data as output

print(f.read()) #print( ) function to print output

f.close()

output:

how are you?


From above example, “w” mode will replace text with ” how are you?”
Create a New File

To create a new file in Python, use the open() method, with one of the
following parameters:

"x" - Create - will create a file, returns an error if the file exist

"a" - Append - will create a file if the specified file does not exist

"w" - Write - will create a file if the specified file does not exist

Delete a File

To delete a file, you must import the OS module, and run


its os.remove() function:

Program:

import os
os.remove("file.txt")

adding multiple line text in my file named file.txt:

program:

a=open("E:/sai.txt","w")

a.write("hello ramesh \n i am nagendra \n i am from hyderabad ")


For complete python subject tutorials visit : ns lectures youtube channel

a.close()

output:

hello ramesh

i am nagendra

i am from Hyderabad

Note

Form all the above examples for each and every method you need to
include f.close(), f.read(), f.write(), f.readline()….so on. Because my file
is present in variable f. So you need to include variable_name before
any method

file object attributes


Once a file is opened and you have one file object, you can get various
information related to that file.
Here is a list of all attributes related to file object −

SR.NO. ATTRIBUTE & DESCRIPTION

file.closed
1 Returns true if file is closed, false otherwise.

file.mode
2 Returns access mode with which file was opened.

file.name
3 Returns name of the file.

Example:

# Open a file
a = open("name.txt", "r")
print ("Name of the file: ", a.name)
print ("Closed or not : ", a.closed)
print ("Opening mode : ", a.mode)
a.close()
For complete python subject tutorials visit : ns lectures youtube channel

output:
Name of the file: name.txt
Closed or not : False
Opening mode : r

python truncate() Method, flush() Method, fileno() Method

truncate() Resizes the file to a specified size

flush() Flushes the internal buffer

Python File truncate() Method :


For example, my file name is file.txt and my file contains data i.e., hello india
The truncate() method resizes the file to the given number of bytes.If the size is
not specified, the current position will be used.
Syntax
file.truncate(size)
Example
Open the file with "a" for appending, then truncate the file to 5 bytes:
a= open("file.txt", "a")
a.truncate(5)
a.close()
#open and read the file after the truncate:
a= open("file..txt", "r")
print(a.read())
output:
hello

Python File flush() Method:


The flush() method cleans out the internal buffer.
Syntax
file.flush()
example:
a= open("myfile.txt", "a")
a.write("how are you")
a.flush()
a.write("hello")

Python File fileno() Method:


The fileno() method returns the file descriptor of the stream, as a number.
An error will occur if the operator system does not use a file descriptor.
For complete python subject tutorials visit : ns lectures youtube channel

program:
a= open("file.txt", "r")
print(a.fileno())
output:
3
split() method
split each word in single quotes and it is represented in list

Assume we have the following file, located in the local disk E, let file
name is sai.txt , let file contains text given below:

file.txt
hello ramesh
i am nagendra

i am from hyderabad

program:

a=open("E:/sai.txt","r")

b=a.read()

print(b.split())

a.close()

output:

['hello’, ‘ramesh’, 'I’, ‘am’, ‘nagendra’, ‘I’, ‘am’, ‘from’, ‘hyderabad’]

Python Program to Copy Content of One File to


Another File
Program:

a=open(“file1.txt”, “r”)
For complete python subject tutorials visit : ns lectures youtube channel

b=open(“file2.txt”, “w”)

for i in a:

b.write(i)

a.close()

b.close()

output:

When you run above code it will copy content from file1.txt to file2.txt

Above program explanation:

in the above example I want to copy text from file1.txt to file2.txt. At first I
need to read text present in my file. so, I opened file1.txt in “r” mode i.e..,
read mode and after reading text present in file1.txt now I need to write
text from file1.txt to file2.txt so I opened file2.txt in “w” mode i.e.., write
mode. file1.txt is stored in variable “a” and file2.txt is stored in variable
“b”.

At first for loop will store all the content present in variable “a” to variable
“i” and then we can copy data present in variable “i” to variable “b” by
using write() mode. At last close both files by using close() method.

Python File seek() and tell() Method


tell() method:
The tell() method returns the current file position in a file stream.
Syntax
file.tell()

for example file.txt is my file , contains data i.e., hello ramesh


program:
a=open("sai.txt","r+")
print(a.tell())
For complete python subject tutorials visit : ns lectures youtube channel

print(a.readline(3))
print(a.tell())
output:
0
hel
3
From above example, The tell() method returns the current file position
So when I write print(a.tell()) it will print current position of cursor i.e, 0
After printing first 3 characters by using print(a.readline(3)) , now my
cursor is at position 3, So again when I write print(a.tell()) it will print
current position of cursor i.e, 3

seek() method
In Python, seek() function is used to change the position of the File
Handle to a given specific position. File handle is like a cursor, which
defines from where the data has to be read or written in the file.

Syntax: file.seek( )

for example file.txt is my file , contains data i.e., hello ramesh

program:
a=open("sai.txt","r+")
a.seek(6)
print(a.readline())

output:
ramesh

from the above example , a.seek(6) will move cursor to position 6.


So when you print file data by using print(a.readline()), it will print only
“ramesh” and it will skip “hello “ because we moved cursor to position 6
by using seek().
For complete python subject tutorials visit : ns lectures youtube
channel
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel
sys module
The sys module in Python provides valuable information about the Python
interpreter. You can also use it to obtain details about the constants, functions
and methods of the Python interpreter.

The sys module comes packaged with Python, which means you do not need
to download and install it separately using the PIP package manager.
In order to start using the sys module and its various functions, you need to
import it. You can do that using the below line of code,

import sys

File system : Python OS Module

In a computer, a file system is the way in which files are named and where
they are placed logically for storage and retrieval.

Python OS module provides the facility to establish the interaction between


the user and the operating system. It offers many useful OS functions that
are used to perform OS-based tasks and get related information about
operating system.

Python’s OS module comes packaged within python when installed. This


means you do not need to separately install it In order to access its various
methods/functions, you just need to import the module.

import os

Now that you’ve imported the module, you can start using its various
functions.

Getting current working directory

Note − Directory is nothing but folder.


The currently working directory is the folder in which the python script is
saved and being run from.
Program:
import os
os.getcwd()

output:
D:\ Python\

Note − Directory is nothing but folder.

Creating a directory:

import os
os.mkdir("D:\nagendra")
This will create a folder nagendra in the D drive.
Note − If no location is specified, it will just create a “new folder” in the
current working directory.

Deleting a directory

In order to delete a directory, we will be using the rmdir() function, it stands


for remove directory.
import os
os.rmdir("D:\nagendra")

Renaming a directory

In order to rename a folder, we use the rename function present in the os


module.

import os
os.mkdir("D:\ nagendra")
os.rename("D:\nagendra","D:\nagendra2")
The above line of code renames nagendra to nagendra2.
change the current working directory:

The os module provides the chdir() function to change the current working
directory.

import os
os.chdir("d:\\")
To get the list of all files and directories in the specified
directory
os.listdir() method in python is used to get the list of all files and
directories in the specified directory.
program:

import os
os.listdir("D:/nagendra")

output:
[ 'file.txt, 'image.jpeg’, 'New folder']

above code will display files/ folder present in nagendra directory which is
located in local disk D
In nagendra directory which is located in local disk D contains 3 files
file.txt, image.jpeg and New folder. It will display output in to form of list

Program To get the list of all files and directories in the specified
directory Line by line

program:
import os
a=os.listdir("D:/nagendra")
for i in a:
print(i)
output:

file.txt

image.jpeg

New folder

os.system() method:
used to open files present in system like notepad, chrome etc….

os.system("notepad")

output:
0

0 means success so, when you run above code it will automatically opens
notepad if output is 0

It returns 1 if it fails to open particular file.


For complete python subject tutorials visit : ns lectures youtube channel

File Execution : Execution Environment


How to Run Python Code Interactively ( interactive mode ):

A widely used way to run Python code is through an interactive session. To


start a Python interactive session, just open a command-line or terminal
and then type in python, or python3 depending on your Python installation,
and then hit Enter.

Here’s an example of how to do this on Linux:

$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
For complete python subject tutorials visit : ns lectures youtube channel

> >>
The standard prompt for the interactive mode is >>>, so as soon as you
see these characters, you’ll know you are in.

Now, you can write and run Python code as you wish, with the only
drawback being that when you close the session, your code will be gone.

When you work interactively, every expression and statement you type in is
evaluated and executed immediately:

>>>
>>> print('Hello World!')
Hello World!

An interactive session will allow you to test every piece of code you write,
which makes it an awesome development tool and an excellent place to
experiment with the language and test Python code on the fly.

To exit interactive mode, you can use one of the following options:

• quit() or exit(), which are built-in functions

How to Run Python Scripts Using the Command-Line (script mode) or


(normal mode)

A Python interactive session will allow you to write a lot of lines of code, but
once you close the session, you lose everything you’ve written. That’s why
the usual way of writing Python programs is by using plain text files. By
convention, those files will use the .py extension. (On Windows systems
the extension can also be .pyw.)

Python code files can be created with any plain text editor. If you are new
to Python programming, you can try Sublime Text, which is a powerful and
easy-to-use editor, but you can use any editor you like.

To keep moving forward in this tutorial, you’ll need to create a test script.
Open your favorite text editor and write the following code:

hello.py
For complete python subject tutorials visit : ns lectures youtube channel

print('Hello World!')

Save the file in your working directory with the name hello.py. With the test
script ready, you can continue reading.

Using the python Command


To run Python scripts with the python command, you need to open a
command-line and type in the word python, or python3 if you have both
versions, followed by the path to your script, just like this:

$ python3 hello.py
Hello World!
If everything works okay, after you press Enter , you’ll see the phrase Hello
World! on your screen. That’s it! You’ve just run your first Python script!

Running Modules With the -m Option


Python offers a series of command-line options that you can use according
to your needs. For example, if you want to run a Python module, you can
use the command python -m <module-name>.

The -m option searches sys.path for the module name and runs its content
as main :

$ python3 -m hello
Hello World!
Note: module-name needs to be the name of a module object, not a string.
Using the Script Filename
On recent versions of Windows, it is possible to run Python scripts by
simply entering the name of the file containing the code at the command
prompt:

C:\Desktop> hello.py
Hello World!
Using importlib and imp
In the Python Standard Library, you can find importlib, which is a module
that provides import_module().
For complete python subject tutorials visit : ns lectures youtube channel

With import_module(), you can emulate an import operation and, therefore,


execute any module or script. Take a look at this example:

>>>

>>> import importlib


>>> importlib.import_module('hello')
Output:
Hello World

Run Python Scripts From an IDE or a Text Editor:

When developing larger and more complex applications, it is recommended


that you use an integrated development environment (IDE) or an advanced
text editor.

Advanced text editors like Sublime Text and Visual Studio Code also allow
you to run your scripts.

IDEs such as Eclipse-PyDev, PyCharm, Eric, and NetBeans also allow you
to run Python scripts from inside the environment.
How to Run Python Scripts From a File Manager

Running a script by double-clicking on its icon in a file manager is another


possible way to run your Python scripts. This option may not be widely
used in the development stage, but it may be used when you release your
code for production.

You are now able to run Python scripts from:

• The operating system command-line or terminal


• The Python interactive mode
• The IDE or text editor you like best
• The file manager of your system, by double-clicking on the icon of
your script
For complete python subject tutorials visit : ns lectures youtube channel

Persistent storage modules


Pickle Module
The process to converts any kind of python objects (list, dict, tuple etc.)
into byte streams (0s and 1s) is called pickling or serialization or
flattening or marshalling. We can converts the byte stream (generated
through pickling) back into python objects by a process called as
unpickling or de-serializing.

In real world sceanario, the use pickling and unpickling are widespread
as they allow us to easily transfer data from one server/system to
another and then store it in a file or database.
Python pickle module is used for serializing and de-serializing python
object
pickle.dump ( ) method is used to pickle objects

pickle.load ( ) method is used to un-pickle objects

Only after importing pickle module we can do pickling and unpickling.


Importing pickle can be done using the following command –

import pickle

Example:
Import pickle

a=[“nagendra”,10,”btech”]

b=open(“D:/newfile.txt” , ”wb”)

pickle.dump(a,b)

f= open(“D:/newfile.txt” , ”rb”)

print(pickle.load(f))
For complete python subject tutorials visit : ns lectures youtube channel

From the above example I want to store list object to file named
newfile.txt so I took list in variable “a” and newfile.txt in “b” and we
need to use “wb” mode i.e., write binary because I want to copy list
object to my file named newfile.txt and when you write pickle.dump(a,b)
this pickle.dump() method will copy list object present in variable “a”
to “b” i.e, newfile.txt

If you want to print data which is present in newfile.txt you need to use
pickle.load( ) method. Here you need to use “rb” mode i.e., read
mode because I want to read data which is present in newfile.txt. so I will
get output [‘nagendra’,10,’btech’] which is present in newfile.txt.

Marshal Module
Even though marshal module in Python’s standard library provides
object serialization features (similar to pickle module), it is not really
useful for general purpose data persistence or transmission of Python
objects through sockets etc.

Difference between marshal and pickle is that marshal can handle only
simple python objects (numbers,sequences,mapping) while pickle can
handle all types of objects including classes.
Just as pickle module, marshal module also defined load() and dump()
functions for reading and writing marshaled objects from / to file.

marshal.dump ( ) method is used to pickle objects

marshal.load ( ) method is used to un-pickle objects

dumps() − method is used to pickle objects. Only objects of standard


data types are supported for pickling. Unsupported types raise
ValueError exception.
loads() − method is used to un-pickle objects. If the conversion doesn’t
result in valid Python object, ValueError or TypeError may be raised.

Example:
For complete python subject tutorials visit : ns lectures youtube channel

Import marshal

a=[“nagendra”,10,”btech”]

b=marshal.dumps(a) #marshal.dumps() will copy list ‘a’ to ‘b’

marshal.loads(b) #marshal.loads() will print output present in ‘b’

output:
[‘nagendra’,10,’btech’]

Shelve Module
The Shelve Module of Python is a very popular module of Python which
works like an effective tool for persistent data storage inside files using a
Python program. As the name of this module suggests, i.e., Shelve, we
can easily interpret that it will work as a shelf object to keep all our data
inside a file and save all the necessary information.

Shelve Module is not only helpful in storing information inside a file, but it
is also very effective in modifying the already present information and
adding some new information in the same file. We can perform all these
operations (creating, reading, writing, and deleting from a file) from the
Shelve Module by using this module and its functions inside a Python
program.

Following code creates a database and stores dictionary entries in it.


import shelve
a=shelve.open("D:/test")
a['name']="Ajay"
a['age']=23
a['marks']=75
a.close()

This will create test.dir file in local lisk D and store key-value data in
hashed form. The Shelf object has following methods available −To
access value of a particular key in shelf −
a=shelve.open('test')
print (a['age']) #this will print 23
For complete python subject tutorials visit : ns lectures youtube channel

a['age']=25 # I changed age 23 to 25


print (a.get('age')) #this will print 25
a.pop('marks') #this will remove corresponding k-v pair
As in a built-in dictionary object, the items(), keys() and values() methods
return view objects.
print (list(a.items()))

output: [('name', 'Ajay'), ('age', 25), ('marks', 75)]

print (list(a.keys()))
output: ['name', 'age', 'marks']

print (list(a.values()))
output: ['Ajay', 25, 75]

Database Manager (dbm) package


dbm package in python provides a simple dictionary like interface of the
form DBM (DataBase Manager) generally used in Unix operating
system. dbm stores data in simple key – value pair form like a
dictionary which makes it easier to insert, edit and retrieve data from
database. It stores data by the use of a single primary key (“key”) in
fixed size blocks.
There are three types of sub modules in dbm package :
1. dbm.gnu: GNU’s reinterpretation of dbm
2. dbm.ndbm: Interface based on ndbm
3. dbm.dumb: Portable DBM implementation

import dbm
>>> a=dbm.open('D:/mydata.db','n')
>>> a['name']=’nagendrasai’
>>> a['address']=’hyderabad’
>>> a['PIN']='500027'
>>> a.close()
The open() function allows mode these flags –

'n' :- Always create a new, empty database, open for reading andwriting
'r' :- Open existing database for reading only (default)
'w' :- Open existing database for reading and writing
'c' :- Open database for reading and writing, creating it . if it doesn’t exist
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel

Python Exception Handling


Error in Python can be of two types i.e. Syntax errors and Exceptions.Errors are the
problems in a program due to which the program will stop the execution.Exceptions
are raised when the program is syntactically correct, but the code resulted in an error.
This error does not stop the execution of the program, however, it changes the normal
flow of the program.

Example of error:

a=10
prnt(a)

output:
NameError: name ‘prnt’ is not defined

In the above example instead of writing ‘print’ i written ‘prnt’ which is known error.

Example of Exception:

a=10
b=0
c=a/b
print(c)

output:
ZerodivisionError : Division by zero

We encountered an exception error after executing above code. Because we cannot


divide any number by zero. This error does not stop the execution of the program,
however, it changes the normal flow of the program.

Python Exception Handling (try..except..finally)

We know that exceptions abnormally terminate the execution of a program.


This is why it is important to handle exceptions. In Python, we use the
try...except block.

Python try...except Block


The try...except block is used to handle exceptions in Python. Here's the syntax
of try...except block:
For complete python subject tutorials visit : ns lectures youtube channel

syntax:

try:
# code that may cause exception
except:
# code to run when exception occurs

Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block
cannot be used without the try block.
Example: Exception Handling Using try...except
a=10
b=0
try:
c=a/b
print(c)
except:

print(“error , b value cant be 0 “)

OUTPUT:
error , b value cant be 0

In the example, we are trying to divide a number by 0.


Here, this code generates an exception.
To handle the exception, we have put the code, c=a/b inside the try block. Now
when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except blockare
executed.

If none of the statements in the try block generates an exception, the except block
is skipped.

Example2:
For complete python subject tutorials visit : ns lectures youtube channel

a=20
b=10
try:
c=a/b
print(c)
except:

print(“error , b value cant be 0 “)

output:
2

from the above example ,i will get output 2 , because If none of the statements in the
try block generates an exception, it will print code inside try block .so it will write
value of c i.e., 2 and except block is skipped.

For each try block, there can also be multiple except blocks.

Python try with else


In some situations, we might want to run a certain block of code if the code block
inside try runs without any errors.
For these cases, you can use the optional else keyword with the try statement.

Example: Exception Handling Using try...except and else block.


a=10
b=0
try:
c=a/b
print(c)
except:

print(“error , b value cant be 0 “)


else:
For complete python subject tutorials visit : ns lectures youtube channel

print(“ try block is working”)

OUTPUT:
error , b value cant be 0

In the above example,if no exception occurs then it willprint both try and
else block. If exception occurs then it will skip try and else block and it print
only exceptblock

Example2 : Exception Handling Using try...except and else block.


a=20
b=10
try:
c=a/b
print(c)
except:

print(“error , b value cant be 0 “)


else:
print(“ try block is working”)

OUTPUT:
2
try block is working

In the above example,no exception occurs so it will printboth try and else
block.
Python try...finally
In Python, the finally block is always executed no matterwhether there is an
exception or not.
The finally block is optional. And, for each try block,there can be only one
finally block.
For complete python subject tutorials visit : ns lectures youtube channel

Example:
a=10
b=0
try:
c=a/b
print(c)
except:

print(“error , b value cant be 0 “)


finally:

print(“this finally block “)

Output:

error , b value cant be 0

this finally block

Context Management in Python


In any programming language, the usage of resources like file operations or
database connections is very common. But these resources are limited in
supply. Therefore, the main problem lies in making sure to release these
resources after usage. If they are not released then it will lead to resource
leakage and may cause the system to either slow down or crash. It would be
very helpful if users have a mechanism for the automatic setup and
For complete python subject tutorials visit : ns lectures youtube channel

Tear down of resources. In Python, it can be achieved by the usage of context


managers which facilitate the proper handling of resources.

Program:

a = open("hello.txt", "w")
a.write("Hello, World!")
a.close()

in the above example , if exception occurs while writing text “ hello world”
then it will stop execution and it will not close file. so, This implementation
doesn’t guarantee the file will be closed if an exception occurs

In Python, you can use two general approaches to deal with resource
management. You can wrap your code in:

1. A try … finally construct


2. A with construct

The try … finally Approach


Working with files is probably the most common example of resource management in
programming. In Python, you can use a try … finally statement to handle
opening and closing files properly:
example:
a = open("hello.txt", "w")

try:
a.write("Hello, World!")

finally:
a.close()
For complete python subject tutorials visit : ns lectures youtube channel

from the above example try … finally Approach will safely opens file and
automatically closes a file. Even if exception occurs while writing “hello,
world!” it will automatically close my file.
The with Statement Approach

The Python with statement creates a runtime context that allows you to run a
group of statements under the control of a context manager.

Compared to traditional try … finally constructs, the with statement can make
your code clearer, safer, and reusable. Many classes in the standard library support
the with statement. A classic example of this is open(), which allows you to work
with file objects using with.

The context manager object results from evaluating the expression after with. In
other words, expression must return an object that implements the context
management protocol. This protocol consists of two special methods:

1. . enter () is called by the with statement to enter the runtime context.


2. . exit () is called when the execution leaves the with code block.

Example:
a= open("hello.txt", "w")
with a:
a.write("Hello, World!")

from the above example with statement approach will safely opens file and
automatically closes a file. Even if exception occurs while writing “hello,
world!” it will automatically close my file. there is no need of writing a.close()
because it will automatically close my file.

Raising Exceptions
If a condition does not meet our criteria but is correct according to the Python
interpreter, we can intentionally raise an exception using the raise keyword. We can
use a customized exception in conjunction with the statement.
If we wish to use raise to generate an exception when a given condition happens, we
may do so as follows:
example:
a=[1,2,3,4,5,6]
For complete python subject tutorials visit : ns lectures youtube channel

if len(a)>4:
raise Exception(“error!!!!! length of list must be lessthan 3”)
Output:
Exception:error!!!! length of list must be lessthan 3

Assertions
Assertions in any programming language are the debugging tools that help in the
smooth flow of code.
assert in Python
In simpler terms, we can say that assertion is the boolean expression that checks
if the statement is True or False. If the statement is true then it does nothing and
continues the execution, but if the statement is False then it stops the execution of
the program and throws an error.
Flowchart of Python Assert Statement

assert Keyword in Python


In python, assert keyword helps in achieving this task. This statement takes as
input a boolean condition, which when returns true doesn’t do anything and
continues the normal flow of execution, but if it is computed to be false, then it
raises an AssertionError along with the optional message provided.
Syntax : assert condition, error_message(optional)

Parameters :
condition : The boolean condition returning true or false.
error_message : The optional argument to be printed in console in case of
AssertionError
Returns :
Returns AssertionError, in case the condition evaluates to false along with the
error message which when provided.

Example 1: Python assert keyword without error message


a =4
For complete python subject tutorials visit : ns lectures youtube channel

b =0
print("The value of a / b is : ")
assertb !=0
print(a /b)

Output :
The value of a / b is :

AssertionError Traceback (most


recent call last)
Input In [19], in <cell line: 10>()
8 # using assert to check for 0
9 print("The value of a / b is : ")
---> 10 assert b != 0
11 print(a / b)

AssertionError:

Example 2: Python assert keyword with error message

a =4

b =0

print("The value of a / b is : ")

assertb !=0, "Zero Division Error"

print(a /b)

Output:

AssertionError: Zero Division Error

Standard Exceptions List


Here is the complete list of Python in-built exceptions.
Sr.No. Name of the Exception Description of the Exception
1 Exception All exceptions of Python have a base class.
If the next() method returns null for an iterator, this
2 StopIteration
exception is raised.
3 SystemExit The sys.exit() procedure raises this value.
Excluding the StopIteration and SystemExit, this is
4 StandardError the base class for all Python built-in exceptions.
For complete python subject tutorials visit : ns lectures youtube channel

All mathematical computation errors belong to this


5 ArithmeticError
base class.
This exception is raised when a computation
6 OverflowError
surpasses the numeric data type's maximum limit.
If a floating-point operation fails, this exception is
7 FloatingPointError
raised.
For all numeric data types, its value is raised
8 ZeroDivisionError whenever a number is attempted to be divided by
zero.
9 AssertionError If the Assert statement fails, this exception is raised.
This exception is raised if a variable reference or
10 AttributeError
assigning a value fails.

11 EOFError When the endpoint of the file is approached, and the


interpreter didn't get any input value by raw_input()
or input() functions, this exception is raised.
12 ImportError
This exception is raised if using the import keyword
to import a module fails.
13 KeyboardInterrupt
If the user interrupts the execution of a program,
generally by hitting Ctrl+C, this exception is raised.
14 LookupError
LookupErrorBase is the base class for all search
errors.
15 IndexError This exception is raised when the index attempted to
be accessed is not found.
16 KeyError When the given key is not found in the dictionary to
be found in, this exception is raised.
17 NameError This exception is raised when a variable isn't located
in either local or global namespace.

18 UnboundLocalError This exception is raised when we try to access a local


variable inside a function, and the variable has not
been assigned any value.
For complete python subject tutorials visit : ns lectures youtube channel

All exceptions that arise beyond the Python


19 EnvironmentError
environment have this base class.
If an input or output action fails, like when using the
20 IOError print command or the open() function to access a file
that does not exist, this exception is raised.
This exception is raised whenever a syntax error
22 SyntaxError
occurs in our program.
This exception was raised when we made an
23 IndentationError
improper indentation.
This exception is raised when the sys.exit() method is
24 SystemExit used to terminate the Python interpreter. The parser
exits if the situation is not addressed within the code.
This exception is raised whenever a data type-
25 TypeError incompatible action or function is tried to be
executed.
This exception is raised if the parameters for a built-
26 ValueError in method for a particular data type are of the correct
type but have been given the wrong values.
This exception is raised when an error that occurred
27 RuntimeError
during the program's execution cannot be classified.
If an abstract function that the user must define in an
28 NotImplementedError inherited class is not defined, this exception is raised.

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 anundeclared variable
Example:
a=5
c=a+b
print("Sum =",c)

Output:
Traceback (most recent call last):
For complete python subject tutorials visit : ns lectures youtube channel

File "expdemo.py", line 2, inc=a+b


NameError: name 'b' is not defined

• 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, inprint(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:
a=['c','java','python']
print("list item is :",a[5])

Output:
Traceback (most recent call last):
File "expdemo.py", line 2, in print("list item is :",a [5])
IndexError: list index out of range.
• KeyError: Occurs when we request for a non-existent dictionary key
Example:
a={"name":"Madhu","location":"Hyd"}
print("The age is :",a["age"])

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

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


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

Output:
Traceback (most recent call last):
File "expdemo.py", line 1, in
a=open("exam.py")
FileNotFoundError: [IOError] No such file or directory:'exam.py'
exc_info( ) function
The exec_info() function is used for obtaining information about an exception.For
using this function you need to import sys module at the beginning of the python
program.
This function returns a tuple of three valuesthat gives information about exception
that currently being handled.
The values returned from this functions are ( type, value, trackback ).
where,
type gets the exception being handled ( it is class object ).
values gets the exception parameters .
traceback gets a traceback object.
Program:

import sys
a=10
b=0
try:
print(a/b)
except:
print(sys.exc_info())

output:

(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback


object at 0x7f85ea12be80>)

Creating exceptions
Defining Custom Exceptions:
In Python, we can define custom exceptions by creating a new class that is
derived from the built-in Exception class.
Here's the syntax to define custom exceptions,

class CustomError(Exception):
...
pass

try:
...

except CustomError:
...

Here, CustomError is a user-defined error which inherits from the Exception class.
Note:

• When we are developing a large Python program, it is a good practice to place all
the user-defined exceptions that our program raises in a separate file.
• Many standard modules define their exceptions separately
as exceptions.py or errors.py (generally but not always).

Example: Python User-Defined Exception


# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass
a = int(input("Enter a number: "))
try:

if a > 18:
print("Eligible to Vote")

else:

raise InvalidAgeException

except InvalidAgeException:
print("Exception occurred: Invalid Age")
Output
If the user input input_num is greater than 18,

Enter a number: 45
Eligible to Vote
If the user input input_num is smaller than 18,
Enter a number: 14
Exception occurred: Invalid Age

In the above example, we have defined the custom


exception InvalidAgeException by creating a new class that is derived from the
built-in Exception class.
Here, when a is smaller than 18, this code generates an exception.
When an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the user-defined InvalidAgeException exception and
statements inside the except block are executed.
For complete python subject tutorials visit : ns lectures youtube channel

Python Modules
As our program grows bigger, it may contain many lines of code. Instead
of putting everything in a single file, we can use modules to separate
codes in separate files as per their functionality. This makes our code
organized and easier to maintain.
Module is a file that contains code to perform a specific task. A module
may contain variables, functions, classes etc.
Create a simple Python module
Let’s create a simple file1.py in which we define two functions,
one add and another subtract.

Program in File1.py

def add(x, y):


print(x+y)

def subtract(x, y):


print(x-y)

Import Module in Python


Import in python is similar to #include header_file in C/C++. Python
modules can get access to code from another module by importing the
file/function using import. The import statement is the most common
way of invoking the import machinery, but it is not the only way.
We can import the functions, and classes defined in a module to
another module using the import keyword 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.

We use the import keyword to do this. To import our previously defined


module example, we type the following in the Python prompt.

Syntax of Python Import

import module_name
For complete python subject tutorials visit : ns lectures youtube channel

Note: This does not import the functions or classes directly instead
imports the module only. To access the functions inside the module the
dot(.) operator is used.

import file1

file1.add(10, 2)

output:

12

The from-import Statement in Python


Python’s from statement lets you import specific attributes from a
module without importing the module as a whole.
Importing specific attributes from the module

Here, we are importing specific sqrt and factorial attributes from the
math module.(math module is built-in module that you can use for
mathematical tasks.)
Program:
from math import sqrt, factorial, log, pow, sin, cos
sqrt(16)
factorial(6)
log(10)
pow(2,3)
sin(1)
cos(1)

Output:
4.0
720
2.30
8
0.84
0.54
For complete python subject tutorials visit : ns lectures youtube channel

From import * Statement


The use of * has its advantages and disadvantages. If you know exactly
what you will be needing from the module, it is not recommended to
use *, else do so.
Program:
from math import *
sqrt(16)
factorial(6)

Output:
4.0
720
Module for displaying Fibonacci series
fibseries.py
def fib(n):
a=0
b=1
sum=0
for i in range(0,n):
print(sum, end=” ”)
a=b
b=sum
sum=a+b

open python shell and import above module and access the function

import fibseries
fibseries.fib(10)
output:

0 1 1 2 3 5 8 13 21 34
For complete python subject tutorials visit : ns lectures youtube channel

Namespace in Python

A namespace is a way of providing the different name for each object in


Python. Everything in Python is an object, i.e., a variable or a method. In
other words, it is a collection of the defined symbolic names along with
the information about the object that each name references. A
namespace can be understood as a dictionary where a name represents
a key and objects are values. Let's understand it with a real-life example
- A namespace is like a surname. A "Karthikeya" name might be difficult
to find in the class if there are multiple "karthikeya," but when we
particularly ask for "govinda karthikeya" or "surla venkata karthikeya,". It
might be rare to find the same name and surname in a class for multiple
students.

The namespace helps the Python interpreter to understand what exact


method or variable is trying to point out in the code. So its name gives
more information - Name (which means name, a unique identifier)
+ Space (related to scope).Python doesn’t have same name of objects
within single scope.
For complete python subject tutorials visit : ns lectures youtube channel

In Python, there are four types of namespaces which are given below.

o Built-in
o Global
o Enclosing
o Local
For complete python subject tutorials visit : ns lectures youtube channel

As these namespace various have lifetimes, Python interpreter creates


namespaces as necessary and deletes them when they are no longer
needed.

Let's understand the various types of namespace in Python.

1. The Built-in Namespace

As its name suggests, it contains pre-defined names of all of Python's


built-in objects already available in Python. Let's list these names with
the following command.

Open the Python terminal and type the following command.

Command -

dir( builtins )

Output:

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',


'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
'ConnectionRefusedError', 'ConnectionResetError',
'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
'Exception', 'False', 'FileExistsError', 'FileNotFoundError',
'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError',
'ImportError', 'ImportWarning', 'IndentationError', 'IndexError',
'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt',
'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError',
'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError',
'OSError', 'OverflowError', 'PendingDeprecationWarning',
'PermissionError', 'ProcessLookupError', 'RecursionError',
'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning',
'SystemError', 'SystemExit', 'TabError',
'TimeoutError', 'True', 'TypeError', 'UnboundLocalError',
'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError',
'Warning', 'WindowsError', 'ZeroDivisionError', ' build_class ',
' debug ', ' doc ', ' import ', ' loader ', ' name ',
' package ', ' spec ', 'abs', 'all', 'any', 'ascii', 'bin', 'bool',
'breakpoint', 'bytearray', 'bytes', 'callable',
For complete python subject tutorials visit : ns lectures youtube channel

'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr',


'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int',
'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max',
'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print',
'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

The built-in namespace creates by the Python interpreter when its starts
up. These are terminated when Python interpreter terminates.

2. The Global Namespace

The global namespace consists of any names in Python at any level of


the main program. It is created when the main body executes and
remains in existence until the interpreter terminates.

3. The Local Namespaces

The function uses the local namespaces; the Python interpreter creates
a new namespace when the function is executed. The local namespaces
remain in existence until the function terminates. The function can also
consist of another function. We can define one function inside another
as below.

Program for global and localnamepaces:

def evenodd(num): #global namespace

n=num #local namespace

if n%2==0:

return "even no"

else:

return "odd no "

num=int(input("enter no:"))

print(evenodd(num))
For complete python subject tutorials visit : ns lectures youtube channel

Python Module Attributes: name, doc, file, dict


Python module has its attributes that describes it. Attributes perform
some tasks or contain some information about the module. Some of
the important attributes are explained below:

name Attribute

The name attribute returns the name of the module. By default,


the name of the file (excluding the extension .py) is the value of
name attribute.

Example:

>>> import math


>>> math. name

Output:
'math'

The value of the name attribute is main on the Python


interactive shell.

Example:

>>> name

Output:
' main '

When we run any Python script (i.e. a module), its name attribute
is also set to main

doc Attribute

The doc attribute denotes the documentation string (docstring)line


written in a module code.

Example:

>>> import math


>>> math. doc
For complete python subject tutorials visit : ns lectures youtube channel

Output:
'This module is always available. It provides access to the mathematical
functions defined
file Attribute

file is an optional attribute which holds the name and path of the
module file from which it is loaded.

Example:

>>> import io
>>> io. file

Output

'C:\\python37\\lib\\io.py'
dict Attribute

The dict attribute will return a dictionary object of module


attributes, functions and other definitions and their respective values.

Example:
>>> import math
>>> math. dict

Output:
{' name ': 'math', ' doc ': 'This module is always
available. It provides a
ccess to the\nmathematical functions defined by the C
standard.', ' package ':
'', ' loader__': <class
'_frozen_importlib.BuiltinImporter'>, ' spec ': Modu
leSpec(name='math', loader=<class
'_frozen_importlib.BuiltinImporter'>, origin='
built-in'), 'acos': <built-in function acos>, 'acosh':
<built-in function acosh>
, 'asin': <built-in function asin>, 'asinh': <built-in
function asinh>, 'atan':
For complete python subject tutorials visit : ns lectures youtube channel

<built-in function atan>, 'atan2': <built-in function


atan2>, 'atanh': <built-in
function atanh>, 'ceil': <built-in function ceil>,
'copysign': <built-in functi
on copysign>, 'cos': <built-in function cos>, 'cosh':
<built-in function cosh>,
'degrees': <built-in function degrees>, 'erf': <built-in
function erf>, 'erfc':
<built-in function erfc>, 'exp': <built-in function exp>,
'expm1': <built-in fun
ction expm1>, 'fabs': <built-in function fabs>,
'factorial': <built-in function
factorial>, 'floor': <built-in function floor>, 'fmod':
<built-in function fmod>
, 'frexp': <built-in function frexp>, 'fsum': <built-in
function fsum>, 'gamma':
<built-in function gamma>, 'gcd': <built-in function
gcd>, 'hypot': <built-in f
unction hypot>, 'isclose': <built-in function isclose>,
'isfinite': <built-in fu
nction isfinite>, 'isinf': <built-in function isinf>,
'isnan': <built-in functio
n isnan>, 'ldexp': <built-in function ldexp>, 'lgamma':
<built-in function lgamm
a>, 'log': <built-in function log>, 'log1p': <built-in
function log1p>, 'log10':
<built-in function log10>, 'log2': <built-in function
log2>, 'modf': <built-in
function modf>, 'pow': <built-in function pow>, 'radians':
<built-in function ra
dians>, 'remainder': <built-in function remainder>, 'sin':
<built-in function si
n>, 'sinh': <built-in function sinh>, 'sqrt': <built-in
function sqrt>, 'tan': <
built-in function tan>, 'tanh': <built-in function tanh>,
'trunc': <built-in fun
ction trunc>, 'pi': 3.141592653589793, 'e':
2.718281828459045, 'tau': 6.28318530
7179586, 'inf': inf, 'nan': nan}
For complete python subject tutorials visit : ns lectures youtube channel

dir() function in Python


dir() is a powerful inbuilt function in Python3, which returns list of the
attributes and methods of any object (say functions , modules, strings,
lists, dictionaries etc.)

Syntax :

dir({object})
Returns :
dir() tries to return a valid list of attributes of the object it is called upon.
Also, dir() function behaves rather differently with different type of
objects, as it aims to produce the most relevant one, rather than the
complete information.

• For Class Objects, it returns a list of names of all the valid attributes
and base attributes as well.

• For Modules/Library objects, it tries to return a list of names of all the


attributes, contained in that module.

• If no parameters are passed it returns a list of names in the current


local scope.

Example : Without importing external libraries.

print(dir())

output:

[' builtins__', ' cached__', ' doc__', ' file ', ' loader '
' name ','__package ', ' spec ']

Example2 : With importing external libraries

Import math
Import random
print(dir())

output:
For complete python subject tutorials visit : ns lectures youtube channel

[' builtins__', ' cached__', ' doc__', '__file__', ' loader ',
' name ', '__package ', ' spec ', 'math', 'random']

Functions in Python Math Module


The math module is a standard module in Python and is always
available. To use mathematical functions under this module, you have to
import the module using import math.
It gives access to the underlying C library functions. For example,
# Square root calculation

import math
math.sqrt(4)

output:
2
Functions in Python Math Module
Here is the list of all the functions and attributes defined in math module
with a brief explanation of what they do.
List of Functions in Python Math Module

Function Description

ceil(x) Returns the smallest integer greater than or equal to x.

copysign(x, y) Returns x with the sign of y

fabs(x) Returns the absolute value of x

factorial(x) Returns the factorial of x

floor(x) Returns the largest integer less than or equal to x

fmod(x, y) Returns the remainder when x is divided by y


For complete python subject tutorials visit : ns lectures youtube channel

frexp(x) Returns the mantissa and exponent of x as the pair (m, e)

Returns an accurate floating point sum of values in the


fsum(iterable)
iterable

Returns True if x is neither an infinity nor a NaN (Not a


isfinite(x)
Number)

isinf(x) Returns True if x is a positive or negative infinity

isnan(x) Returns True if x is a NaN

ldexp(x, i) Returns x * (2**i)

modf(x) Returns the fractional and integer parts of x

trunc(x) Returns the truncated integer value of x

exp(x) Returns e**x

expm1(x) Returns e**x - 1

log(x[, b]) Returns the logarithm of x to the base b (defaults to e)

log1p(x) Returns the natural logarithm of 1+x

log2(x) Returns the base-2 logarithm of x

log10(x) Returns the base-10 logarithm of x

pow(x, y) Returns x raised to the power y

sqrt(x) Returns the square root of x


For complete python subject tutorials visit : ns lectures youtube channel

acos(x) Returns the arc cosine of x

asin(x) Returns the arc sine of x

atan(x) Returns the arc tangent of x

atan2(y, x) Returns atan(y / x)

cos(x) Returns the cosine of x

hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)

sin(x) Returns the sine of x

tan(x) Returns the tangent of x

degrees(x) Converts angle x from radians to degrees

radians(x) Converts angle x from degrees to radians

acosh(x) Returns the inverse hyperbolic cosine of x

asinh(x) Returns the inverse hyperbolic sine of x

atanh(x) Returns the inverse hyperbolic tangent of x

cosh(x) Returns the hyperbolic cosine of x

sinh(x) Returns the hyperbolic cosine of x

tanh(x) Returns the hyperbolic tangent of x

erf(x) Returns the error function at x


For complete python subject tutorials visit : ns lectures youtube channel

erfc(x) Returns the complementary error function at x

gamma(x) Returns the Gamma function at x

Returns the natural logarithm of the absolute value of the


lgamma(x)
Gamma function at x

Mathematical constant, the ratio of circumference of a


pi
circle to it's diameter (3.14159...)

e mathematical constant e (2.71828...)

Python Packages
We usually organize our files in different folders and subfolders based
on some criteria, so that they can be managed easily and efficiently.
For example, we keep all our games in a Games folder and we can
even subcategorize according to the genre of the game or something
like this. The same analogy is followed by the Python package.
A Python module may contain several classes, functions, variables, etc.
whereas a Python package can contains several module. In simpler
terms a package is folder that contains various modules as files.

Creating Package
Let’s create a package named “world” that will contain two modules
“india.py” and “america.py”. To create this module follow the below
steps –
• Create a folder named “world”.
• Inside this folder create an empty Python file i.e. init .py
• Then create two modules “india.py” and “america.py” in this folder.

India.py
def telangana():
print(“I am from telangana”)
def andhrapradesh():
print(“I am from andhrapradesh”)
For complete python subject tutorials visit : ns lectures youtube channel

america.py
def alabama():
print(“I am from alabama”)
def washington():
print(“I am from washington”)

Understanding init .py


init .py helps the Python interpreter to recognise the folder as
package. It also specifies the resources to be imported from the
modules. If the init .py is empty this means that all the functions of
the modules will be imported

import Modules from a Package


We can import these modules using the from…import statement and
the dot(.) operator.

Syntax:
import package_name.module_name

Example: Import Module from package

We will import the modules “india.py” and “america.py” from the above
created package i.e., “world” and will use the functions inside those
modules.

Import world.india

Import world.america

world.america.alabama() #output: I am from alabama

world.india.telangana() #output: I am from telangana


For complete python subject tutorials visit : ns lectures youtube channel

UNIT-3
Regular Expressions:

special symbols and characters and functions.

Multithreaded programming:

Threads and processes


Global interpreter lock
Thread module
Threading module
Related modules
For complete python subject tutorials visit : ns lectures youtube channel

Regular Expressions
A Regular Expressions (RegEx) is a special sequence of characters that
uses a search pattern to find a string or set of strings. It can detect the
presence or absence of a text by matching it with a particular pattern, and
also can split a pattern into one or more sub-patterns. Python provides a re
module that supports the use of regex in Python. Its primary function is to
offer a search, where it takes a regular expression and a string. Here, it
either returns the first match or else none.

RegEx Module

Python has a built-in package called re, which can be used to work with
Regular Expressions.

Import the re module:

import re
RegEx in Python

When you have imported the re module, you can start using regular
expressions:

Example-1:

Search the string to see if it starts with "My"and ends with "nagendra":
import re

a = "My name is nagendra"

x = re.search("^My.*nagendra$",a)

if x:

print("YES! We have a match!")

else:

print("No match")
For complete python subject tutorials visit : ns lectures youtube channel

output:

YES! We have a match!

Example-2:
import re
s = 'my name is nagendra'
print(re.search('nagendra', s))

output:

<re.Match object; span=(11, 19), match='nagendra'>


RegEx Functions
The re module offers a set of functions that allows us to search a string for
a match:

Function Description

findall Returns a list containing all matches

search Returns a Match object, if there is a match anywhere


in the string

split Returns a list where the string has been split at each
match

sub Replaces one or many matches with a string


For complete python subject tutorials visit : ns lectures youtube channel

match Returns a Match object if there is a match starting in


the string

The match() Function


The match() function searches the string for a match, and returns a Match
object if there is a match at the starting of my string.

Example-1:
import re

a = "my name is nagendra, my age is 24"

x = re.match("my", a)

print(x)

Output:

<re.Match object; span=(0, 2), match='My'>

Example-2:
import re

a = "my name is nagendra, my age is 24"

x = re.match("The", a)

print(x)
Output:

None

The search() Function


For complete python subject tutorials visit : ns lectures youtube channel

The search() function searches the string for a match, and returns a Match
object if there is a match.

If there is more than one match, only the first occurrence of the match will
be returned:

Match Object

A Match Object is an object containing information about the


search and the result.

Note: If there is no match, the value None will be returned,


instead of the Match Object.

Example-1:
import re

a = "my name is nagendra, my age is 24"

x = re.search("my", a) #here, my is match object

print(x)

Output:

<re.Match object; span=(0, 2), match='My'>

Example-2:
import re

a = "my name is nagendra, my age is 24"


x = re.search("24", a)

print(x)

Output:

<re.Match object; span=(31, 33), match='24'>


For complete python subject tutorials visit : ns lectures youtube channel

The findall() Function


The findall() function returns a list containing all matches.

Example-1:
import re

a = "my name is nagendra, my age is 24"

x = re.findall("My", a)

print(x)

Output:

['my', 'my']

The split() Function


The split() function returns a list where the string has been split at each
match:

Example-1:

import re

a = "my name is nagendra, my age is 24"

x = re.split("nagendra", a)

print(x)

Output:

['my name is ', ', my age is 24']


For complete python subject tutorials visit : ns lectures youtube channel

The sub() Function


The sub() function replaces the matches with the text of your choice:

Example-1:
import re

a = "my name is nagendra, my age is 24"

x = re.sub("nagendra","rahul", a)

print(x)

Output:

my name is rahul, my age is 24

Meta Characters
To understand the RE analogy, Meta Characters are useful, important, and will be
used in functions of module re. Below is the list of meta characters.

Meta Characters Description

Used to drop the special meaning of character


\
following it

[] Represent a character class

^ Matches the beginning

$ Matches the end

. Matches any character except newline


For complete python subject tutorials visit : ns lectures youtube channel

Meta Characters Description

Means OR (Matches with any of the characters


|
separated by it.

? Matches zero or one occurrence

Any number of occurrences (including 0


*
occurrences)

+ One or more occurrences

Indicate the number of occurrences of a preceding


{}
regex to match.

() Enclose a group of Regex

[ ] (Square Brackets)
Square Brackets ([]) represent a character class consisting of a set of
characters that we wish to match. For example, the character class [abc]
will match any single a, b, or c.
We can also specify a range of characters using – inside the square
brackets. For example,
• [0-3] is sample as [0123]
• [a-c] is same as [abc]
We can also invert the character class using the caret(^) symbol. For
example,
• [^0-3] means any number except 0, 1, 2, or 3
• [^a-c] means any character except a, b, or c
example-1:
import re
For complete python subject tutorials visit : ns lectures youtube channel

a= "my name is nagendra"


print(re.findall("[a-m]”, a))
output:
['m', 'a', 'm', 'e', 'i', 'a', 'g', 'e', 'd', 'a']

example-2:
import re
a= "my name is nagendra, my age is 25"
print(re.findall("[0-9]”, a))

output:
['2', '5']

^ (Caret)
Caret (^) symbol matches the beginning of the string i.e. checks whether
the string starts with the given character(s) or not. For example –
• ^B will check if the string starts with g such as Btech, Ball, BOX etc.
• ^BTECH will check if the string starts with BTECH such as BTECH
HYDERABAD, BTECH AIML, BTECH CSE etc.
example-1:
import re
a = 'Btech'
result = re.match(‘^B’, a)

if result:
print("Search successful.")
else:
print("Search unsuccessful.")
For complete python subject tutorials visit : ns lectures youtube channel

output:

Search successful.

example-2:

import re

a = 'Btech hyderabad'

result = re.match(‘^Btech’, a)

if result:

print("Search successful.")

else:

print("Search unsuccessful.")

output:

Search successful.

$ (Dollar)
Dollar($) symbol matches the end of the string i.e checks whether the string
ends with the given character(s) or not. For example –
• s$ will check for the string that ends with a such as geeks, ends, s,
etc.
• ks$ will check for the string that ends with ks such as geeks,
geeksforgeeks, ks, etc.
example-1:
import re
a = 'Btech'
result = re.search(‘h$’, a)
For complete python subject tutorials visit : ns lectures youtube channel

if result:
print("Search successful.")
else:
print("Search unsuccessful.")

output:

Search successful.

example-2:

import re

a = 'Btech hyderabad'

result = re.search(‘hyderabad$’, a)

if result:

print("Search successful.")

else:

print("Search unsuccessful.")

output:

Search successful.

. (Dot)
Dot(.) symbol matches only a single character except for the newline
character (\n). For example –
• a.b will check for the string that contains any character at the place of
the dot such as acb, adb, arb, a1b, etc...
For complete python subject tutorials visit : ns lectures youtube channel

• .. will check if the string contains at least 2 characters.for example


a..b will check for the string that contains any two character at the
place of the dot such as acrb, adhb, arfb, a12b, etc…
example-1:
import re
a= "hello hyderabad"
x = re.findall("he..o", a)
print(x)
output:
['hello']

example-2:
import re
a= "hello hyderabad"
x = re.findall("hyd .... d", a)
print(x)
output:
['hyderabad']

| (Or)
Or symbol works as the or operator meaning it checks whether the pattern
before or after the or symbol is present in the string or not. For example –
• btech|mtech will match any string that contains btech or mtech.

Example-1:
import re
a= "i am from btech and i am from mtech "
For complete python subject tutorials visit : ns lectures youtube channel

x = re.findall("btech|mtech", a)
print(x)
output:
['btech', 'mtech']

Example-2:
import re
a= "i am nagendra and i am from BTECH"
x = re.findall(" BTECH | MTECH ", a)
print(x)
output:
['btech']

? (Question Mark)
The question mark symbol ? matches zero or one occurrence of the
pattern left to it.
Expression String Matched?

mn 1 match

man 1 match

No match (more than one a


ma?n maaan
character)

main No match (a is not followed by n)

woman 1 match

example-1:
For complete python subject tutorials visit : ns lectures youtube channel

import re
a= "i am a man"
x = re.findall("ma?n", a)
print(x)
output:
['man']

example-2:
import re
a= "i am a mn"
x = re.findall("ma?n", a)
print(x)
output:
['mn']

example-3:
import re
a= "i am a maaaan"
x = re.findall("ma?n", a)
print(x)
output:
[ ] ( output is empty because a repeated more than once. The question
mark symbol ? matches zero or one occurrence of the pattern left to it.)

* (Star)
The star symbol * matches zero or more occurrences of the pattern left to
it.
For complete python subject tutorials visit : ns lectures youtube channel

Expression String Matched?

mn 1 match

man 1 match

ma*n maaan 1 match

main No match (a is not followed by n)

woman 1 match

example-1:
import re
a= "i am a maaan"
x = re.findall("ma*n", a)
print(x)
output:
['maaan']
example-2:
import re
a= "i am a mn"
x = re.findall("ma*n", a)
print(x)
output:
['mn']

+ (Plus)
The plus symbol + matches one or more occurrences of the pattern left to it.
For complete python subject tutorials visit : ns lectures youtube channel

Expression String Matched?

mn No match (no a character)

man 1 match

maaan 1 match

ma+n No match (a is not followed


main
by n)

woman 1 match

example-1:
import re
a= "i am a maaan"
x = re.findall("ma+n", a)
print(x)
output:
['maaan']

example-2:
import re
a= "i am a mn"
x = re.findall("ma+n", a)
print(x)

output:
For complete python subject tutorials visit : ns lectures youtube channel

[ ] ( output is empty because a is not present .The plus symbol + matches


one or more occurrences of the pattern left to it)

{ } (Braces)
Consider this code: {n,m}. This means at least n, and at most m repetitions
of the pattern left to it.
Example-1:
import re
a= "my name is nagendra, my age is 25"
x = re.findall("my{1,3}", a)
print(x)

output:
['my', 'my']

from above pattern my{1,3} mean --if “my” is present at least once and
maximum three time then it will print “my”
from above example “my” is present twice, so it will print my twice

( ) -Group
Group symbol is used to group sub-patterns.

List of special sequences


Special sequences do not match for the actual character in the string
instead it tells the specific location in the search string where the match
must occur. It makes it easier to write commonly used patterns.
For complete python subject tutorials visit : ns lectures youtube channel

Special
Description
Sequence

\A Matches if the string begins with the given character

Matches if the word begins or ends with the given character.


\b \b(string) will check for the beginning of the word and (string)\b
will check for the ending of the word.

It is the opposite of the \b i.e. the string should not start or end
\B
with the given regex.

Matches any decimal digit, this is equivalent to the set class [0-
\d
9]

Matches any non-digit character, this is equivalent to the set


\D
class [^0-9]

\s Matches any whitespace character.

\S Matches any non-whitespace character

Matches any alphanumeric character, this is equivalent to the


\w
class [a-zA-Z0-9_].

\W Matches any non-alphanumeric character.

\Z Matches if the string ends with the given regex


For complete python subject tutorials visit : ns lectures youtube channel

Program:
import re
a="my name is nagendra, my age is 25"
b=re.findall("\Amy",a)
c=re.findall("\w",a)
d=re.findall("\W",a)
e=re.findall("\d",a)
f=re.findall("\D",a)
g=re.findall("\s",a)
h=re.findall("\S",a)
i=re.findall(r"\bmy", a)
i=re.findall(r"\bna", a)
j=re.findall(r"ra\b",a)
print("output of \A is ",b)
print("output of \w is ",c)
print("output of \W is ",d)
print("output of \d is ",e)
print("output of \D is ",f)
print("output of \s is ",g)
print("output of \S is ",h)
print("output of \b is ",i)
print("output of \b is ",j)
For complete python subject tutorials visit : ns lectures youtube channel

output:
output of \A is ['my']

output of \w is ['m', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'n', 'a', 'g', 'e', 'n', 'd', 'r', 'a',
'm', 'y', 'a', 'g', 'e', 'i', 's', '2', '5']

output of \W is ['', '', '', ',', '', '', '', '']

output of \d is ['2', '5']

output of \D is ['m', 'y', '', 'n', 'a', 'm', 'e', '', 'i', 's', '', 'n', 'a', 'g', 'e', 'n', 'd',
'r', 'a', ',', '', 'm', 'y', '', 'a', 'g', 'e', '', 'i', 's', '']

output of \s is ['', '', '', '', '', '', '']

output of \S is ['m', 'y', 'n', 'a', 'm', 'e', 'i', 's', 'n', 'a', 'g', 'e', 'n', 'd', 'r', 'a',
',', 'm', 'y', 'a', 'g', 'e', 'i', 's', '2', '5']

output of \b is ['na’]

output of \b is ['ra’]
For complete python subject tutorials visit : ns lectures youtube channel

Multithreading
Python Multithreading:
Multithreading is a threading technique in Python programming to run
multiplethreads concurrently by rapidly switching between threads with
a CPU help (called context switching). Besides, it allows sharing of its
data space with the main threads inside a process that share
information and communication with other threads easier than
individual processes. Multithreading aims to perform multiple tasks
simultaneously, which increases performance, speed and improves the
rendering of the application.
Benefits of Multithreading in Python
A thread is the smallest unit of a program or process executed independently
or scheduled by the Operating System. In the computer system, an Operating
System achieves multitasking by dividing the process into threads. A thread is
a lightweight process that ensures the execution of the process separately on
the system. In Python 3, when multiple processors are running on a program,
each processor runs simultaneously to execute its tasks separately.

Following are the benefits to create a multithreaded application in Python, as


follows:
1. It ensures effective utilization of computer system resources.
2. Multithreaded applications are more responsive.
3. It shares resources and its state with sub-threads (child) which makes it
more economical.
4. It makes the multiprocessor architecture more effective due to similarity.
5. It saves time by executing multiple threads at the same time.
6. The system does not require too much memory to store multiple threads.

When to use Multithreading in Python?


It is a very useful technique for time-saving and improving the performance of
an application. Multithreading allows the programmer to divide application
tasks into sub-tasks and simultaneously run them in a program. It allows
threads to communicate and share resources such as files, data, and
memory to the same processor. Furthermore, it increases the user's
responsiveness to continue running a program even if a part of the application
is the length or blocked.
How to achieve multithreading in Python?
There are two main modules of multithreading used to handle threads in
Python.
For complete python subject tutorials visit : ns lectures youtube channel

1. The thread module


2. The threading module

Thread modules
A thread is an entity within a process that can be scheduled for execution.
Also, it is the smallest unit of processing that can be performed in an OS
(Operating System). In simple words, a thread is a sequence of such
instructions within a program that can be executed independently of other
codes.
It is started with Python 3, designated as obsolete, and can only be
accessed with _thread thatsupports backward compatibility.
Syntax:
thread.start_new_thread ( function_name, args[, kwargs] )
example:
import _thread
import time
def name(n):
time.sleep(0.5)
print("my name is:",n)
def country(m):
time.sleep(0.5)
print("my country is :",m)
r=time.time()
_thread.start_new_thread(name,("nagendrasai",))
_thread.start_new_thread(country,("india",))
print("time taken to execute two functions:",time.time()-r)

output:
my name is nagendrasai
my country is india
time taken to execute two functions:00:0045555
For complete python subject tutorials visit : ns lectures youtube channel

Types of Threads
There are two types of threads, which are:
1. User Level Thread

As the name suggests, the user-level threads are only managed by users,
and the kernel does nothave its information.
These are faster, easy to create and manage.
The kernel takes all these threads as a single process and handles them
as one process only. The user-level threads are implemented by user-
level libraries, not by the system calls.
2. Kernel-Level Thread

The kernel-level threads are handled by the Operating system and managed
by its kernel. These threads are slower than user-level threads because
context information is managed by the kernel. To create and implement a
kernel-level thread, we need to make a system call.
Features of Thread
• Threads share data, memory, resources, files, etc., with their peer threads
within a process.
• One system call is capable of creating more than one thread.
• Each thread has its own stack and register.
• Threads can directly communicate with each other as they share the same
address space.
• Threads need to be synchronized in order to avoid unexpected scenarios.

Threading Modules
The threading module included with Python 2.4 provides much more
powerful, high-level support for threads than the thread module .To use
multithreading, we need to import the threading module in Python Program.
The threading module exposes all the methods of the thread module and
provides some additional methods −
• threading.activeCount() − Returns the number of thread objects that are
active.
• threading.currentThread() − Returns the number of thread objects
in the caller's threadcontrol.
• threading.enumerate() − Returns a list of all thread objects that are
currently active.
In addition to the methods, the threading module has the Thread class that
For complete python subject tutorials visit : ns lectures youtube channel

implements threading. The methods provided by the Thread class are as follows

• run() − The run() method is the entry point for a thread.
• start() − The start() method starts a thread by calling the run method.
• join() − The join() waits for threads to terminate.
• isAlive() − The isAlive() method checks whether a thread is still executing.
• getName() − The getName() method returns the name of a thread.
• setName() − The setName() method sets the name of a thread.

threading Module Objects:

Apart from the functions specified above, the threading module also provides
many classes whose objects are very useful in creating and managing threads.

Following are some of the Object types:

Object Description

Thread Object that represents a single thread of execution.

Lock Primitive lock object.

RLock or Re-entrant lock object provides ability for a


RLock single thread to (re)acquire an already-held lock
(recursive locking).

Condition variable object causes one thread to wait until


Condition certain "condition" has been satisfied by another thread
(such as change in state or some data value)

Its a more general version of condition variables, whereby


a number of threads can be made to wait for some event
Event
to occur and all the threads waiting will only awaken
when the event happens.

Provides a "counter" of finite resources shared between


Semaphore
threads block when none are available.

BoundedSemaphore Similar to a Semaphore but ensures that it never exceeds


For complete python subject tutorials visit : ns lectures youtube channel

its initial value.

Similar to Thread, except that it waits for a specified


Timer
period of time before running.

Creates a "barrier" at which a specified number of


Barrier threads must all arrive before they're all allowed to
continue.

The above table gives a brief introduction of various object types in python
threading module. We will discuss about all these objects in details in the next few
tutorials.

Follow the given below steps to implement the threading module in Python
Multithreading:
1. Import the threading module:

Create a new thread by importing the threading module, as shown.


Syntax:
import threading
A threading module is made up of a Thread class, which is instantiated to
create a Python thread.
2. Declaration of the thread parameters:

It contains the target function, argument, and kwargs as the parameter in the
Thread() class.
• Target: It defines the fun4. Join method:ction name that is executed by
the thread.
• Args: It defines the arguments that are passed to the target function
name.
3. Start a new thread:

To start a thread in Python multithreading, call the thread class's object. The
start() method can becalled once for each thread object; otherwise, it throws an
exception error.

4. Join method:
It is a join() method used in the thread class to halt the main thread's
execution and waits till the complete execution of the thread object. When the
thread object is completed, it starts the execution of the main thread in
Python.
For complete python subject tutorials visit : ns lectures youtube channel

Multi threading programs:

1. python programming for multi threading in which one thread executes and
prints the square of numbers and other thread executes and prints the cube of
numbers from 1 to 5
(OR)
PYTHON PROGRAM TO ACHIEVE PARALLELISM BY THREADING
MODULE
(OR)
PROGRAM FOR INTER PROCESS COMMUNICATION
(OR)
PYTHON PROGRAM FOR MULTI-THREADING

PROGRAM:

import threading
import time
def square(n):
print("square of a number:")
for i in n:
time.sleep(0.2)
print("square is :",i*i)
def cube(n):
print("cube of a number:")
for i in n:
time.sleep(0.2)
print("cube is :",i*i*i)

r=time.time()
l=[1,2,3,4,5]
t1=threading.Thread(target=square,args=(l,))
t2=threading.Thread(target=cube,args=(l,))
t1.start()
t2.start()
t1.join()
t2.join()
print("time taken to execute two functions:",time.time()-r)output:

square of a number:
cube of a number:
square is : 1
cube is : 1
cube is : 8
square is : 4
cube is : 27
square is : 9
For complete python subject tutorials visit : ns lectures youtube channel

cube is : 64
square is : 16
cube is : 125
square is : 25
time taken to execute two
functions: 1.0623559951782227

2. python program to create two threads. one thread will display the numbers
from 1 to 10 in normal order and other thread will display the numbers in
reverse order

import threading
import time
def normalorder(n):
print("normal order:")
for i in range(1,n+1):
time.sleep(0.2)
print(i)
def reverseorder(n):
print("reverse order:")
for i in range(n,0,-1):
time.sleep(0.2)
print(i)

r=time.time()
t1=threading.Thread(target=normalorder,args=(10,))
t2=threading.Thread(target=reverseorder,args=(10,))
t1.start()
t1.join()
t2.start()
t2.join()
print("time taken to execute two functions:",time.time()-r)

output:

normal order:
1
2
3
4
5
6
7
8
9
For complete python subject tutorials visit : ns lectures youtube channel

10

reverse order:
10
9
8
7
6
5
4
3
2
1
time taken to execute two functions: 4.010312557220459

Difference between Process and Thread


Both process and thread are related to each other and quite similar as these are the
independent sequence of execution. The basic difference between a process and a
thread is that a process takes place in different memory spaces, whereas a thread
executes in the same memory space.

A process is an instance of a program that is being executed. When we run a


program, it does not execute directly. It takes some time to follow all the steps
required to execute the program, and following these execution steps is known as a
process.

A thread is the subset of a process and is also known as the lightweight


process. A process can have more than one thread, and these threads are
managed independently by the scheduler. All the threads within one process
are interrelated to each other.

S.NO Proces Thread


s
Process means any program
1. Thread means a segment of a process.
is inexecution.
The process takes more
2. The thread takes less time to terminate.
time toterminate.
3. It takes more time for creation. It takes less time for creation.
It also takes more time for
4. It takes less time for context switching.
contextswitching.
The process is less
5. Thread is more efficient in terms of communication.
efficient interms of
communication.
We don’t need multi programs in action for
Multiprogramming holds
6. multiple threads because a single process
theconcepts of multi-
consists of multiplethreads.
process.
For complete python subject tutorials visit : ns lectures youtube channel

7. The process is isolated. Threads share memory.


The process is called A Thread is lightweight as each thread in a
8.
theheavyweight processshares code, data, and resources.
process.
Process switching uses an Thread switching does not require calling an
9.
interface in an operating operatingsystem and causes an interrupt to the
system. kernel.
If one process is blocked
If a user-level thread is blocked, then all other user-
10. then itwill not affect the
levelthreads are blocked.
execution of other
processes
The process has its own
Thread has Parents’ PCB, its own Thread Control
11. Process Control Block, Stack,
Block,and Stack and common Address space.
and AddressSpace.
Since all threads of the same process share
Changes to the parent address spaceand other resources so any changes
12.
process donot affect child to the main thread may affect the behavior of the
processes. other threads of the process.
13. A system call is involved in it. No system call is involved, it is created using APIs.
The process does not share
14. datawith each other. Threads share data with each other.

Note: In some cases where the thread is processing a bigger workload


compared toa process’s workload then the thread may take more time
to terminate. But this is an extremely rare situation and has fewer
chances to occur.

Inter process Communication (IPC)


IPC is a mechanism which allows the exchange of data between processes. It
enables resource and data sharing between the processes without interference.
Processes that execute concurrently in the operating system may be either
independent processes or cooperating processes.
A process is independent and it may or may not be affected by other processes
executing in the system. Any process that does not share data with any other
process is independent.
Suppose if a process is cooperating then, it can be affected by other processes
that are executing in the system. Any process that shares the data with another
process is called a cooperative process.
Given below is the diagram of inter process communication −
For complete python subject tutorials visit : ns lectures youtube channel

Reasons for Process Cooperation


There are several reasons which allow process cooperation, which is as follows −
• Information sharing − Several users are interested in the same piece of
information. We must provide an environment to allow concurrent access to
such information.
• Computation speeds up − If we want a particular task to run faster, we must
break it into subtasks, then each will be executed in parallel with the other.
The speedup can be achieved only if the computer has multiple processing
elements.
• Modularity − A system can be constructed in a modular fashion dividing the
system functions into separate processes or threads.
• Convenience − An individual user may work on many tasks at the same time.
For example, a user may be editing, compiling, and printing in parallel.
The cooperative process requires an IPC mechanism that will allow them to
exchange data and information.
IPC Models
There are two fundamental models of IPC which are as follows −
Shared memory
A region of memory that is shared by cooperating processes is established.
Processes can then exchange information by reading and writing data to the
shared region.
Message passing
Communication takes place by means of messages exchanged between the
cooperating processes. Message passing is useful for exchanging small amounts
of data because no conflicts need be avoided.
It is easier to implement when compared to shared memory by using system calls
and therefore, it requires more time-consuming tasks of the kernel.
For complete python subject tutorials visit : ns lectures youtube channel

Python Global Interpreter Lock (GIL)


A global interpreter lock (GIL) is a mechanism to apply a global lock on an
interpreter. It is used in computer-language interpreters to synchronize and
manage the execution of threads so that only one native thread (scheduled by the
operating system) can execute at a time.

In a scenario where you have multiple threads, what can happen is that both the
thread might try to acquire the memory at the same time, and as a result of which
they would overwrite the data in the memory. Hence, arises a need to have a
mechanism that could help prevent this phenomenon.

Some popular interpreters that have GIL are CPython and Ruby MRI. As most of
you would know that Python is an interpreted language, it has various
distributions like CPython, Jython, IronPython. Out of these, GIL is supported only
in CPython, and it is also the most widely used implementation of Python.
CPython has been developed in both C and Python language primarily to support
and work with applications that have a lot of C language underneath the hood.

Hence, GIL (Source: Understanding the Python GIL):

• Limits the threading operation.


• Parallel execution is restricted.
• The GIL ensures that only one thread runs in the interpreter at once.
• It helps in simplifying various low-level details like memory management.

The impact of the GIL isn’t visible to developers who execute single-threaded
programs.Since the GIL allows only one thread to execute at a time even in a multi-
threaded architecture with more than one CPU core, the GIL has gained a reputation
as an “infamous” feature of Python.

Python Global Interpreter Lock (GIL) is a type of process lock which is used
by python whenever it deals with processes. Generally, Python only uses
only one thread to execute the set of written statements. This means that in
python only one thread will be executed at a time. The performance of the
single-threaded process and the multi-threaded process will be the same in
python and this is because of GIL in python. We can not achieve
multithreading in python because we have global interpreter lock which
restricts the threads and works as a single thread.
For complete python subject tutorials visit : ns lectures youtube channel

Difference Between Lock and RLock


A thread is an entity within a process that can be scheduled for execution.
Also, it is the smallest unit of processing that can be performed in an OS
(Operating System). In simple words, a thread is a sequence of such
instructions within a program that can be executed independently of other
codes.

There are two states of a lock i.e locked and unlocked. A lock is a class in
the threading module whose object generated in the unlocked state and has
two primary methods i.e acquire() and release(). When the acquire() method is
called, it locks the execution of the Lock and blocks it’s execution until the
release() method is called in some other thread which sets it to unlock state.
Locks help us in efficiently accessing a shared resource in a program in order
to prevent corruption of data, it follows mutual exclusion as only one thread
can access a particular resource at a time.
For complete python subject tutorials visit : ns lectures youtube channel

A threading.Lock can only be acquired once, and once acquired it cannot be


acquired again by the same thread or any other thread until it has been released.

A threading.RLock can be acquired more than once by the same thread,


although once acquired by a thread it cannot be acquired by a different thread
until it is been released.

A threading.RLock can be acquired more than once by the same thread,


although once acquired by a thread it cannot be acquired by a different thread
until it is been released.

Importantly, each time the threading.RLock is acquired by the same thread it


must be released the same number of times until it is available to be acquired
again by a different thread. This means that the number of calls to acquire() must
have the same number of calls to release() for the RLock to return to the
unlocked state.

How to Use the Reentrant Lock


Python provides a reentrant lock via the threading.RLock class.

An instance of the RLock can be created and then acquired by threads before
accessing a critical section, and released after the critical section.

For example:

# create a reentrant lock

lock = RLock()

# acquire the lock

lock.acquire()

# ...

# release the lock

lock.release()
For complete python subject tutorials visit : ns lectures youtube channel

Subprocess module
The subprocess module present in Python(both 2.x and 3.x) is used to run new
applications or programs through Python code by creating new processes. It
also helps to obtain the input/output/error pipes as well as the exit codes of
various commands.
To execute different programs using Python two functions of the subprocess
module are used:
1. subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None,
shell=False)
Parameters:
args=The command to be executed. Several commands can be passed as a
String by separated by “;”.
stdin=Value of standard input stream to be passed as (os.pipe()).
stdout=Value of output obtained from standard output stream.
stderr=Value of error obtained(if any) from standard error stream.
shell=Boolean parameter.If True the commands get executed through a new
shell environment.
Return-Value:
The function returns the return code of the command.If the return code is zero,
the function simply returns(command executed successfully) otherwise
CalledProcessError is being raised.
2. subprocess.check_output(args, *, stdin=None, stderr=None, shell=False,
universal_newlines=False)
Parameters:
args=The command to be executed.Several commands can be passed as a
For complete python subject tutorials visit : ns lectures youtube channel

String by separated by “;”.


stdin=Value of standard input stream to be passed as (os.pipe()).
stdout=Value of output obtained from standard output stream.
stderr=Value of error obtained(if any) from standard error stream.
shell=Boolean parameter.If True the commands get executed through a new
shell environment..
universal_newlines=Boolean parameter.If true files containing stdout and stderr
are opened in universal newline mode.
Return Value:
The function returns the return code of the command.If the return code is zero,
the function simply returns the output as a byte string(command executed
successfully) otherwise CalledProcessError is being raised.

c-program:
#include<stdio.h>
int main()
{
printf("Hello my name is nagendrasai, this is c program ");
return 0;
}

Python 3 code to execute the above programs:

import subprocess
import os

def excute():
s = subprocess.check_call("gcc HelloWorld.c -o out1;./out1", shell = True)

if _ _ file _ _ = _ _ main _ _:
execute()

Output:
Hello my name is nagendrasai, this is c program

Note: Although subprocess module is OS independent these commands must


only be executed in Linux environments. Also according to Python
documentation passing shell=True can be a security hazard if combined with
untrusted input.

Multiprocessing module
For complete python subject tutorials visit : ns lectures youtube channel

multiprocessing is a package that supports spawning processes using an API


similar to the threading module. The multiprocessing package offers both local
and remote concurrency, effectively side-stepping the Global Interpreter Lock by
using sub processes instead of threads. Due to this, the multiprocessing module
allows the programmer to fully utilize multiple processors on a given machine. It
runs on both Unix and Windows.
Python Classes/Objects
Python is an object oriented programming language.

Almost everything in Python is an object, with its properties and methods.

A Class is like an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the keyword class:

Example:

Create a class named MyClass, with a property named x:

Program:

class MyClass:

x=5

print(x)

output:

program2:

class Person:

def fun(self,name,age):

print(" my name is ", name)

print(" my age is ", age)


p1 = Person()

p1.fun("John", 36)

p1.fun("raju", 46)

output:

my name is John
my age is 36
my name is raju
my age is 46

PYTHON CLASS TO REVERSE A STRING:

OUTPUT:

PYTON CLASS TO CALCULATE POWER(X,N)


OUTPUT:
OUTPUT:
For complete python subject tutorials visit : ns lectures youtube channel

Unit-4
GUI PROGRAMMING & WEB PROGRAMMING
GUI PROGRAMMING:
1. TKINTER, tcl and tk

2. steps to create a simple GUI application using Tkinter in Python

3. tkinter geometry() method ( pack(), grid(), place() )

4. Python Tkinter Button, Checkbutton, Radiobutton, Entry &


Label,Frame Listbox

5. Other modules :
Tk interface Extension (Tix), Python Mega Widgets (PMW),
wxWidgets & wxPython, GTK+, PyGTK, EasyGUI

6. Student details form using tkinter

7. Python To display a good morning message in a text box when the


user clicks the button

8. GUI To display sum of two numbers using tkinter.

WEB PROGRAMMING:

9. Client-server communication
Internet
World Wide Web (www)
Hypertext Transfer Protocol (http)
web server
TCP/IP (Transmission Control Protocol/Internet Protocol)
firewall and proxy
web client
URL (Uniform Resource Locator)
Python modules and classes for building web servers
CGI (Common Gateway Interface)
HTTP server

10. urllib module


urlparse module
urlunparse module
urljoin function
For complete python subject tutorials visit : ns lectures youtube channel

11. creating simple web clients


12. python program to read the source code contents of
www.google.com
13. Cookies and sessions
14. Creating simple CGI applications in python
15. http headers used in cgi program, cgi environment variables
For complete python subject tutorials visit : ns lectures youtube channel

TKINTER
Tkinter is a graphical user interface (GUI) toolkit for Python, and the name
"Tkinter" is a combination of "Tk" and "inter".
"Tk" stands for "Tool Kit", which is a popular GUI toolkit that was originally
developed for the Tcl programming language. Tk provides a set of widgets (such
as buttons, labels, and text boxes) that can be used to create a graphical user
interface.
"Inter" is short for "Interface", which refers to the fact that Tkinter is an interface to
the Tk toolkit. In other words, Tkinter provides a way to use the Tk toolkit in
Python, making it possible to create GUI applications in Python using the same
widgets and tools as in Tcl/Tk.
So, the name Tkinter reflects the fact that it is a Python interface to the Tk toolkit,
allowing Python programmers to use the same tools and widgets as Tcl/Tk
programmers.

. It is a built-in Python module that provides a set of tools and widgets for creating
desktop applications with a graphical interface. Tkinter is based on the Tcl/Tk GUI
toolkit, which was originally developed for the Tcl programming language.
With Tkinter, you can create windows, buttons, text boxes, labels, and other GUI
elements, and you can use these elements to create interactive desktop
applications. Tkinter also provides various layout managers that can be used to
organize the widgets within a window.
Tkinter is a popular choice for building GUI applications in Python, particularly for
small to medium-sized applications. It is easy to use, as it comes with a simple
API that is well-documented and easy to learn. Tkinter is also cross-platform,
which means that you can create GUI applications that will run on Windows, Mac,
and Linux.
Overall, Tkinter is a powerful tool for building graphical user interfaces in Python,
making it a great choice for developers who want to create desktop applications
with a GUI.
tcl and tk
In Python, Tcl and Tk refer to two different things:

Tcl (Tool Command Language) is a scripting language that was originally


developed for the Unix operating system. Tcl is a simple, lightweight language that
is easy to embed in other applications. Python includes a module called "Tcl/Tk"
that provides a Python interface to Tcl.

Tk (Tool Kit) is a graphical user interface (GUI) toolkit that was originally
developed for Tcl. Tk provides a set of widgets (such as buttons, text boxes, and
labels) that can be used to create GUI applications. Python includes a module
called "Tkinter" that provides a Python interface to Tk.
For complete python subject tutorials visit : ns lectures youtube channel

Together, Tcl and Tk provide a powerful toolset for creating GUI applications in
Python. Tkinter provides a Python interface to the Tk toolkit, making it possible to
use Tk's widgets and tools in Python. The Tcl/Tk module provides a way to
execute Tcl scripts from within Python.

steps to create a simple GUI application using Tkinter


in Python:

Step1 : Import the Tkinter module:


>>>Import tkinter
Step2: Create the main window:
>>>a=tkinter.tk()
Step3: Set the window properties, such as title and size:
>>>a.title("welcome")
>>>a.geometry("1280×720")
Step4: Run the main event loop to display the window and handle user events:
>>>a.mainloop()
This is just a basic example to get started with Tkinter. You can add more widgets
and functionality to create a more complex GUI application. Also, note that there
are different layout managers available in Tkinter, and each has its own syntax
and parameters. It is important to understand the different layout managers and
choose the one that best fits your application's needs.

EXAMPLE: Simple GUI program by using tkinter.


Tk.py
import tkinter
a=tkinter.Tk()
a.title("welcome")
a.geometry("500x500")
a.mainloop()
output:
command prompt:
python3 tk.py
For complete python subject tutorials visit : ns lectures youtube channel

tkinter geometry() method


In Tkinter, "geometry" refers to the size and position of the window or widgets in
the user interface. The position and size of the window or widget can be controlled
using the geometry() method.
The geometry() method takes a string argument in the format
"widthxheight+Xposition+Yposition", where width and height specify the
dimensions of the window or widget, and Xposition and Yposition specify the
position of the window or widget on the screen. The + sign is used to separate the
dimensions and the position.

In Tkinter, there are three main geometry managers: pack(), grid(), and place().
These managers are used to position and organize widgets within the parent
window or frame. Here is a brief overview of each manager:

1.pack():
The pack() method is a simple layout manager that arranges widgets in a vertical
or horizontal box. Widgets are added one after another and take up the entire
width or height of the window, depending on the orientation. You can also control
the alignment and padding of the widgets.

Syntax

widget.pack( pack_options )

Here is the list of possible options −


For complete python subject tutorials visit : ns lectures youtube channel

 side − Determines which side of the parent widget packs against: TOP (default),
BOTTOM, LEFT, or RIGHT.

Example:
Tk1.py
from tkinter import *
a=Tk()
a.title("welcome")
a.geometry("500x500")
b=Button(a,text="login")
b.pack(side=LEFT)
c=Button(a,text="Submit")
c.pack(side=RIGHT)
a.mainloop()
Output:
Command prompt:
python3 tk1.py

2.grid():
The grid() method allows you to arrange widgets in a grid pattern, like a table. You
specify the row and column number where you want each widget to appear, and
you can also control the size and padding of each cell. This method is useful for
creating complex layouts with multiple widgets.

Syntax
For complete python subject tutorials visit : ns lectures youtube channel

widget.grid( grid_options )
Here is the list of possible options −
 column − The column to put widget in; default 0 (leftmost column).
 padx, pady − How many pixels to pad widget, horizontally and vertically, outside
v's borders.
 row − The row to put widget in; default the first row that is still empty.

Example:
tk2.py
from tkinter import *
a=Tk()
a.title("welcome")
a.geometry("1280x720")

n=Label(a,text="username:")
n.grid(row=0, column=0, pady=10, padx=5)

e1=Entry(a)
e1.grid(row=0, column=1)

p=Label(a,text="password:")
p.grid(row=1, column=0, pady=10, padx=5)

e2=Entry(a)
e2.grid(row=1, column=1)

b=Button(a,text="login")
b.grid(row=3, column=1)

a.mainloop()

Output:
Command prompt:
python3 tk2.py
For complete python subject tutorials visit : ns lectures youtube channel

3.place()
The place() method allows you to specify the exact position of a widget within the
parent window or frame. You can use this method to create pixel-perfect layouts,
but it can be difficult to maintain the layout when the window size changes.

Syntax

widget.place( place_options )

Here is the list of possible options –


 x, y − Horizontal and vertical offset in pixels.

Example:
tk3.py
from tkinter import *
a=Tk()
a.title("students")
a.geometry("400x300")

n=Label(a,text="name:")
n.place(x=50,y=50)

e1=Entry(a)
e1.place(x=100,y=50)

p=Label(a,text="password:")
p.place(x=50,y=100)

e2=Entry(a)
e2.place(x=110,y=100)

a.mainloop()
Output:
Command prompt:
python3 tk3.py
For complete python subject tutorials visit : ns lectures youtube channel

Python Tkinter Button


The button widget is used to add various types of buttons to the python
application. Python allows us to configure the look of the button according to our
requirements. Various options can be set or reset depending upon the
requirements.

We can also associate a method or function with a button which is called when
the button is pressed.

The syntax to use the button widget is given below.

Syntax
W = Button(parent, options)
For complete python subject tutorials visit : ns lectures youtube channel

Example:
tkb.py
from tkinter import *
from tkinter import messagebox
a=Tk()
a.title("welcome")
a.geometry("400x300")
def fun():
messagebox.showinfo("hello","successfully submitted")

b=Button(a,text="submit",bg="red", fg="black",width=5, height=5,command=fun)


b.pack(side=TOP)

b1=Button(a,text="login",bg="blue",fg="white",width=10, height=5,
activebackground="green")
b1.pack(side=BOTTOM)

a.mainloop()

Output:
Command prompt:

python3 tkb.py
For complete python subject tutorials visit : ns lectures youtube channel

Output when you click on submit button

Output when you click on login button:

It will change color to green

Python Tkinter Checkbutton


The Checkbutton is used to track the user's choices provided to the application. In
other words, we can say that Checkbutton is used to implement the on/off
selections.

The Checkbutton can contain the text or images. The Checkbutton is mostly used
to provide many choices to the user among which, the user needs to choose the
one. It generally implements many of many selections.

The syntax to use the checkbutton is given below.


For complete python subject tutorials visit : ns lectures youtube channel

Syntax

w = checkbutton(master, options)

A list of possible options is given below.

Example:
tkcb.py

from tkinter import *


a=Tk()
a.title("engineering branch")
a.geometry("1280x720")

n=Label(a,text="select your branch in engineering")


n.pack()

cb=Checkbutton(a, text="aiml",fg="blue",bg="yellow",width=10, height=3)


cb.pack()

cb1=Checkbutton(a, text="cse",fg="green",bg="orange",width=10, height=3)


cb1.pack()

a.mainloop()

Output:
Command prompt:

python3 tkcb.py
For complete python subject tutorials visit : ns lectures youtube channel

Python Tkinter Radiobutton


The Radiobutton widget is used to implement one-of-many selection in the python
application. It shows multiple choices to the user out of which, the user can select
only one out of them. We can associate different methods with each of the
radiobutton.

We can display the multiple line text or images on the radiobuttons. To keep track
the user's selection the radiobutton, it is associated with a single variable. Each
button displays a single value for that particular variable.

The syntax to use the Radiobutton is given below.

Syntax

w = Radiobutton(top, options)
For complete python subject tutorials visit : ns lectures youtube channel

Example:
tkrb.py

from tkinter import *


a=Tk()
a.title("engineering branch")
a.geometry("1280x720")

n=Label(a,text="select your branch in engineering")


n.pack()

cb=Radiobutton(a, text="aiml",fg="blue",bg="yellow",width=10, height=3, value=1)


cb.pack()

cb1=Radiobutton(a, text="cse",fg="green",bg="orange",width=10, height=3,


value=2)
cb1.pack()

a.mainloop()

Output:
Command prompt:

python3 tkrb.py
For complete python subject tutorials visit : ns lectures youtube channel

Next →← Prev

Python Tkinter Entry & Label


Next →← Prev

Python Tkinter Label

The Label is used to specify the container box where we can place the text or
images. This widget is used to provide the message to the user about other
widgets used in the python application.

There are the various options which can be specified to configure the text or the
part of the text shown in the Label.

The syntax to use the Label is given below.

Syntax

w = Label (master, options)


For complete python subject tutorials visit : ns lectures youtube channel

Python Tkinter Entry

The Entry widget is used to provde the single line text-box to the user to accept a
value from the user. We can use the Entry widget to accept the text strings from
the user. It can only be used for one line of text from the user. For multiple lines of
text, we must use the text widget.

The syntax to use the Entry widget is given below.

Syntax

w = Entry (parent, options)

Example:
tke.py
from tkinter import *
a=Tk()
a.title("students")
a.geometry("400x300")

n=Label(a,text="name:")
For complete python subject tutorials visit : ns lectures youtube channel

n.place(x=50,y=50)

e1=Entry(a)
e1.place(x=100,y=50)

p=Label(a,text="password:")
p.place(x=50,y=100)

e2=Entry(a)
e2.place(x=110,y=100)

a.mainloop()
Output:
Command prompt:
python3 tke.py

Python Tkinter Frame


Python Tkinter Frame widget is used to organize the group of widgets. It acts like
a container which can be used to hold the other widgets. The rectangular areas of
the screen are used to organize the widgets to the python application.

The syntax to use the Frame widget is given below.

Syntax
For complete python subject tutorials visit : ns lectures youtube channel

w = Frame(parent, options)

A list of possible options is given below.

Example:
tkf.py

from tkinter import *


a=Tk()
a.title("welcome")
a.geometry("400x400")

f=Frame(a, width="100",height="100", bg="yellow")


f.pack(side=TOP)

f1=Frame(a, width="100",height="100", bg="green")


f1.pack(side=BOTTOM)

f2=Frame(a, width="100",height="100", bg="blue")


f2.pack(side=LEFT)

f3=Frame(a, width="100",height="100", bg="orange")


f3.pack(side=RIGHT)

b=Button(a,text="submit")
b.pack(side=RIGHT)

b1=Button(a,text="login")
b1.pack(side=LEFT)

a.mainloop()

Output:
For complete python subject tutorials visit : ns lectures youtube channel

Command prompt:

python3 tkf.py

Python Tkinter Listbox


The Listbox widget is used to display the list items to the user. We can place
only text items in the Listbox and all text items contain the same font and
color.

The user can choose one or more items from the list depending upon the
configuration.

The syntax to use the Listbox is given below.


For complete python subject tutorials visit : ns lectures youtube channel

w = Listbox(parent, options)

A list of possible options is given below.

Example:
tkl.py
from tkinter import *

a=Tk()

a.title("welcome")

a.geometry("400x300")

l1=Label(a, text="list of A section students",fg="red", bg="yellow")

l1.place(x=10, y=10)

b=Listbox(a,height=5)

b.insert(1,"srinivas reddy")

b.insert(2,"mahesh vardhan")

b.insert(3,"umar")

b.insert(4,"arpantiwari")

b.place(x=10,y=30)

l2=Label(a, text="list of B section students",fg="black", bg="pink")

l2.place(x=160, y=10)
For complete python subject tutorials visit : ns lectures youtube channel

b1=Listbox(a,height=5)

b1.insert(1,"sudeer")

b1.insert(2,"anurag")

b1.insert(3,"karthikeya")

b1.insert(4,"amrith")

b1.place(x=160,y=30)

a.mainloop()

Output:
Command prompt:

python3 tkl.py

Tk interface Extension (Tix)


For complete python subject tutorials visit : ns lectures youtube channel

The Tk Interface Extension (Tix) is a Python module that provides an


extended set of user interface components for building graphical user
interfaces (GUIs) using the Tkinter library. Tix extends Tkinter by providing
additional widgets and features that are not available in the core Tkinter
library.

Tix was originally developed as an extension for Tcl/Tk, a popular GUI toolkit
for creating desktop applications. It was later ported to Python and is now
included as a standard library module in most Python installations.

Some of the features that Tix adds to Tkinter include:

 Additional widgets, such as the ComboBox, NoteBook, and ScrolledText


widgets.
 Improved support for common GUI patterns, such as dialog boxes, status
bars, and message boxes.
 Improved layout management, with support for flexible grid-based layouts and
resizable panes.
 Improved styling options, with support for customizing the appearance of
widgets using themes and styles.

To create a Tix GUI in Python, you first need to import the Tix module:

>>>import Tix

After importing the module, you can create a Tix application object:

>>>a = Tix.Tk()

This creates a new Tix application window. You can then add Tix widgets to
the window using the various Tix widget classes. For example, to add a
button widget to the window, you would use the Tix.Button widget class:

>>>b = Tix.Button(a, text='Click me!')

>>>b.pack()

>>>a.mainloop()

Python Mega Widgets (PMW)


Python Mega Widgets (PMW) is a set of high-level, object-oriented user
interface components for Python. PMW is built on top of the Tkinter library,
For complete python subject tutorials visit : ns lectures youtube channel

which is included with most Python installations, and provides a set of


additional widgets and features that are not available in Tkinter.

PMW was created in the late 1990s by Paul Mackenzie, hence the name
"Mega Widgets". PMW provides a consistent interface for building complex
and interactive GUIs in Python, making it a powerful tool for desktop
application development.

Some of the features of PMW include:

 A wide range of widgets, including text boxes, list boxes, combo boxes, and
more.
 Improved layout management, with support for flexible grid-based layouts and
resizable panes.
 Improved styling options, with support for customizing the appearance of
widgets using themes and styles.
 Improved event handling, with support for object-oriented event-driven
programming.
 Comprehensive documentation and examples, making it easy to get started
with PMW.

PMW has been used in a wide range of Python applications, from simple
utility programs to large-scale desktop applications. It is actively maintained
and is supported by a large community of developers, which makes it a
popular choice for Python GUI programming.

To use PMW in Python, you first need to install the module. You can install
PMW using pip, the Python package installer, by running the following
command in a terminal or command prompt:

pip install Pmw

After installing PMW, you can import it in your Python script using the
following line:

import Pmw

wxWidgets & wxPython


wxWidgets is an open-source, cross-platform GUI toolkit that provides a
native look and feel on a wide range of operating systems, including
Windows, Linux, and macOS. It is written in C++ and provides a set of
widgets and classes for building graphical user interfaces (GUIs).
For complete python subject tutorials visit : ns lectures youtube channel

wxPython is a Python wrapper for wxWidgets that allows Python developers


to use the wxWidgets toolkit to build native-looking GUI applications in
Python. wxPython provides Python bindings for the wxWidgets C++ classes,
so Python developers can use the same classes and widgets as C++
developers, but with the ease and flexibility of Python programming.

Using wxPython, you can create complex and interactive GUI applications
with native look and feel on a wide range of operating systems. wxPython
provides a wide range of widgets and classes, including buttons, text boxes,
menus, and dialogs, as well as more advanced features such as custom
controls, 2D and 3D graphics, and multimedia playback.

wxPython is easy to learn and use, with comprehensive documentation and a


large and active user community. It supports both Python 2 and Python 3,
and provides support for both classic and Phoenix (the latest version)
versions.

To use wxPython in your Python program, you first need to install the
wxPython module. You can install wxPython using pip, the Python package
installer, by running the following command in a terminal or command prompt:

pip install wxPython

After installing wxPython, you can import it in your Python script using the
following line:

import wx

This will make the wxPython module and its widgets available in your script.
You can then create a wxPython application object, create wxPython widgets
and add them to the application, and configure the widgets and add event
handlers to them as needed.

GTK+
GTK+ stands for "GIMP Toolkit", where "GIMP" originally stood for "General
Image Manipulation Program".

GTK+ is a cross-platform, open-source GUI toolkit that provides a native look


and feel on a wide range of operating systems, including Linux, Windows,
and macOS. It is written in C and provides a set of widgets and classes for
building graphical user interfaces (GUIs).

To use GTK+ in Python, you can use the PyGTK module, which is a set of
Python bindings for the GTK+ library. PyGTK allows Python developers to
For complete python subject tutorials visit : ns lectures youtube channel

use the GTK+ toolkit to build native-looking GUI applications in Python.


PyGTK provides Python bindings for the GTK+ C classes, so Python
developers can use the same classes and widgets as C developers, but with
the ease and flexibility of Python programming.

Using PyGTK, you can create complex and interactive GUI applications with
native look and feel on a wide range of operating systems. PyGTK provides a
wide range of widgets and classes, including buttons, text boxes, menus, and
dialogs, as well as more advanced features such as custom controls, 2D and
3D graphics, and multimedia playback.

PyGTK is easy to learn and use, with comprehensive documentation and a


large and active user community. It supports both Python 2 and Python 3,
and provides support for both classic and PyGObject-based API.

To use PyGTK in your Python program, you first need to install the PyGTK
module. You can install PyGTK using pip, the Python package installer, by
running the following command in a terminal or command prompt:

pip install pygtk

After installing PyGTK, you can import it in your Python script using the
following line:

import gtk

This will make the PyGTK module and its widgets available in your script. You
can then create a PyGTK application object, create PyGTK widgets and add
them to the application, and configure the widgets and add event handlers to
them as needed.

PyGTK
PyGTK is a set of Python bindings for the GTK+ toolkit, which is a cross-
platform, open-source GUI toolkit written in C that provides a native look and
feel on a wide range of operating systems, including Linux, Windows, and
macOS. PyGTK allows Python developers to use the GTK+ toolkit to build
native-looking GUI applications in Python.

PyGTK provides Python bindings for the GTK+ C classes, so Python


developers can use the same classes and widgets as C developers, but with
the ease and flexibility of Python programming. PyGTK provides a wide range
of widgets and classes, including buttons, text boxes, menus, and dialogs, as
well as more advanced features such as custom controls, 2D and 3D
graphics, and multimedia playback.
For complete python subject tutorials visit : ns lectures youtube channel

Using PyGTK, you can create complex and interactive GUI applications with
native look and feel on a wide range of operating systems. PyGTK is easy to
learn and use, with comprehensive documentation and a large and active
user community. It supports both Python 2 and Python 3, and provides
support for both classic and PyGObject-based API.

PyGTK is widely used for developing desktop applications on Linux and other
Unix-like systems, but it can also be used on Windows and macOS. It is
particularly popular for developing GNOME applications on Linux, which use
the GTK+ toolkit as their underlying GUI library.

EasyGUI
EasyGUI is a module for creating simple GUIs (Graphical User Interfaces) in
Python. It provides a simple and easy-to-use interface for creating basic GUI
elements such as buttons, text boxes, message boxes, and more.

With EasyGUI, you can quickly create a basic interface for your Python
program without having to write a lot of code. For example, you can create a
simple window with a message and an OK button with just a few lines of
code:

import easygui

easygui.msgbox('Hello, world!', 'My Title')

This will create a message box with the message "Hello, world!" and the title
"My Title", and an OK button that the user can click to close the window.

EasyGUI is designed to be simple and easy to use, and is aimed at beginners


who want to create basic GUIs without having to learn complex GUI toolkits
such as Tkinter or wxPython. However, it may not be suitable for more
complex applications or for users who require more advanced features.

Student details form using tkinter

Student.py
from tkinter import *
For complete python subject tutorials visit : ns lectures youtube channel

a=Tk()

a.title("student details form")

a.geometry("1280x720")

n=Label(a,text="name:")

n.grid(row=0, column=0, pady=10, padx=5)

e1=Entry(a)

e1.grid(row=0, column=1)

p=Label(a,text="rollno:")

p.grid(row=1, column=0, pady=10, padx=5)

e2=Entry(a)

e2.grid(row=1, column=1)

p=Label(a,text="branch:")

p.grid(row=3, column=0, pady=10, padx=5)

cb=Checkbutton(a, text="aiml")

cb.grid(row=4, column=0)

cb1=Checkbutton(a, text="cse")

cb1.grid(row=5, column=0)
For complete python subject tutorials visit : ns lectures youtube channel

l1=Label(a, text="programming languages known:")

l1.grid(row=6, column=1)

b=Listbox(a,height=5)

b.insert(1,"java")

b.insert(2,"python")

b.insert(3,"devops")

b.insert(4,"c++")

b.grid(row=7, column=1)

cb=Radiobutton(a, text="male",value=1)

cb.grid(row=8, column=0)

cb1=Radiobutton(a, text="female",value=2)

cb1.grid(row=9, column=0)

b=Button(a,text="submit")

b.grid(row=10, column=1)

a.mainloop()

output:
command prompt:
python3 student.py
For complete python subject tutorials visit : ns lectures youtube channel

Python To display a good morning message in a


text box when the user clicks the button
gm.py:
from tkinter import *

a=Tk()

a.title("welcome")
For complete python subject tutorials visit : ns lectures youtube channel

a.geometry("1280x720")

n=Label(a,text="hello:")

n.grid(row=0, column=0)

e1=Entry(a)

e1.grid(row=0, column=1)

def display():

e1.insert(END,"Good Morning!!!")

b=Button(a,text="click me", command=display)

b.grid(row=0, column=2)

a.mainloop()

output:
command prompt:
python3 gm.py
For complete python subject tutorials visit : ns lectures youtube channel

GUI program using tkinter to identify sum of two


numbers
Sum.py
from tkinter import *

def sum():

a=int(t1.get())

b=int(t2.get())

c=a+b

t3.insert(0,c)

a=Tk()

a.geometry('730x1280')

t1=Label(a,text='first number:')

t1.grid(row=0,column=0)

t1=Entry(a)

t1.grid(row=0,column=1)

t2=Label(a,text='second number:')

t2.grid(row=1,column=0)

t2=Entry(a)

t2.grid(row=1,column=1)
For complete python subject tutorials visit : ns lectures youtube channel

t3=Label(a,text='result:')

t3.grid(row=2,column=0)

t3=Entry(a)

t3.grid(row=2,column=1)

b1=Button(a,text='ADD',command=sum)

b1.grid(row=3,column=1)

a.mainloop()

output:
command prompt:
python3 sum.py
For complete python subject tutorials visit : ns lectures youtube channel

Client-server communication
Client-server communication refers to the exchange of data and messages
between two computer programs or processes: the client and the server. In a
client-server architecture, the client is typically a user-facing application or
program that requests services or data from the server. The server, on the
other hand, is responsible for processing those requests and providing the
requested services or data.

The communication between the client and the server is typically mediated
through a network connection. The client initiates the communication by
sending a request to the server over the network, and the server responds to
the request by sending back the requested data or services. This exchange of
data between the client and the server can occur through various protocols
and mechanisms such as HTTP, FTP, SMTP, and many others.

Client-server communication is a fundamental concept in modern computing


and is used in a wide range of applications and systems, including web
applications, database systems, email servers, and many others. The
efficiency and effectiveness of the client-server communication play a crucial
role in determining the overall performance of these systems.

Here's a step-by-step explanation of client-server communication using an


example of a web browser (client) communicating with a web server.

1. User enters a website URL in the web browser: Let's say the user wants to
access the website "www.example.com" and enters the URL in the web
browser.
2. Web browser sends a request to the server: The web browser sends an
HTTP request to the server that hosts the "www.example.com" website. This
request contains information such as the type of request (e.g., GET, POST),
the URL, and any additional data that the server needs to fulfill the request.
3. Server receives and processes the request: The server receives the request
from the web browser and processes it. It checks the requested URL,
accesses the appropriate files or databases, and prepares the data to send
back to the client.
4. Server sends a response to the web browser: After processing the request,
the server sends an HTTP response back to the web browser. This response
contains the requested data, such as an HTML page or an image file, along
with additional information, such as the response code (e.g., 200 OK, 404 Not
Found) and any response headers.
5. Web browser receives and displays the response: The web browser receives
the HTTP response from the server and displays the requested data to the
For complete python subject tutorials visit : ns lectures youtube channel

user. It renders the HTML page, displays the image, or performs any other
necessary actions to present the data to the user.
6. Additional requests and responses: If the web page requires additional
resources, such as CSS files or JavaScript, the web browser sends additional
requests to the server, and the server sends additional responses back to the
web browser to fulfill these requests.

This process continues as the user interacts with the web page and the web
browser sends additional requests to the server. The server processes these
requests and sends back responses to the web browser to update the
displayed content.

Internet
The internet is a global network of computers and servers that are connected
together to allow the exchange of information and communication between
individuals and organizations around the world. It is a decentralized network,
which means that there is no central governing body that controls the internet,
but rather a system of interconnected networks that share information using
standardized communication protocols. The internet allows users to access a
wide range of information and resources, such as websites, email, social
media, online applications, and digital media. It has revolutionized the way we
communicate, work, and access information, and has become an essential
part of daily life for billions of people around the world.
For complete python subject tutorials visit : ns lectures youtube channel

World Wide Web (www)


The World Wide Web, often abbreviated as "WWW" or simply "the web," is a
system of interlinked documents, images, and other resources, accessed
through the internet. The web is built on top of the internet and uses a
standardized set of communication protocols, known as the Hypertext
Transfer Protocol (HTTP) and the HyperText Markup Language (HTML), to
create and share information.

In simpler terms, the internet is the global network of interconnected devices,


while the World Wide Web is a system of linked web pages and digital
resources accessed through the internet.

Web pages are created using HTML, a markup language that allows the
author to structure text and multimedia elements such as images and videos,
and to link to other web pages or resources. Hyperlinks, which are clickable
elements that direct users to other web pages or resources, are a key feature
of the web.

Today, the web has become an essential part of daily life for billions of people
around the world, providing a vast range of information, resources, and
services, such as social media, online shopping, email, and streaming media.

Hypertext Transfer Protocol (http)


HTTP (Hypertext Transfer Protocol) is a set of rules or protocols that allow
web browsers and web servers to communicate with each other over the
internet. HTTP is used to request and transmit web pages, images, videos,
and other resources from web servers to web browsers.

The main features of HTTP are:

1. Stateless: HTTP is a stateless protocol, which means that each request from
the client to the server is independent and does not carry any context from
previous requests. This makes it easier to scale web applications and
reduces the overhead of maintaining state on the server.
2. Connectionless: HTTP is a connectionless protocol, which means that after a
client sends a request to a server and receives a response, the connection is
closed. This can lead to slower performance due to the overhead of
establishing a new connection for each request.
3. Request-response: HTTP is a request-response protocol, meaning that the
client sends a request to the server, and the server responds with the
requested resource or an error message.
For complete python subject tutorials visit : ns lectures youtube channel

4. Idempotent: Some HTTP methods, such as GET and HEAD, are idempotent,
which means that they can be safely repeated multiple times without
changing the state of the server.
5. Extensible: HTTP is an extensible protocol, which means that it can be
extended with new features and functionality. For example, HTTPS (HTTP
Secure) is an extension of HTTP that provides secure communication over
the internet.

Overall, HTTP is a foundational protocol for the World Wide Web and has
enabled the rapid growth of web-based applications and services that we use
today.

web server
A web server is a software program that runs on a computer and is
responsible for serving web pages and other resources to clients over the
internet. When a user requests a web page, the web server receives the
request, processes it, and returns the requested web page to the user's
browser.

Here are two popular web servers:

1. Apache HTTP Server: Apache is a free, open-source web server software


that is used by millions of websites around the world. Apache is known for its
reliability, stability, and security, and it runs on a wide range of operating
For complete python subject tutorials visit : ns lectures youtube channel

systems, including Windows, macOS, and Linux. Apache supports a wide


range of features, including SSL/TLS encryption, virtual hosting, and server-
side scripting. Apache is also highly extensible and can be customized with
various modules and plugins.
2. Nginx: Nginx is a high-performance, open-source web server and reverse
proxy that is used by many popular websites, including Netflix, Airbnb, and
WordPress.com. Nginx is known for its fast and efficient handling of web
traffic and its ability to scale easily to handle high traffic volumes. Nginx is
also highly extensible and supports various plugins and modules, including
SSL/TLS encryption, load balancing, and caching.

Both Apache and Nginx are powerful web servers with their own unique
characteristics and advantages. The choice of web server often depends on
factors such as performance requirements, server hardware, and the web
application being served.

TCP/IP (Transmission Control Protocol/Internet


Protocol)
TCP/IP (Transmission Control Protocol/Internet Protocol) is a set of
communication protocols that are used to enable communication between
different devices over the internet. TCP/IP is the foundation of internet
communication and is used in many different applications, including web
communication.

TCP (Transmission Control Protocol) is responsible for reliable, ordered


transmission of data over the internet, while IP (Internet Protocol) is
responsible for routing data packets between different devices on the internet.

In web communication, TCP/IP is used to transmit data between web


browsers and web servers. When a user types a URL into a web browser, the
browser sends a request to the web server using the HTTP (Hypertext
Transfer Protocol) over TCP/IP. The TCP protocol breaks the request into
smaller packets and sends them over the internet to the web server, which
reassembles them and sends a response back to the client using the same
protocol.

TCP/IP provides several important features that are essential for web
communication, including:

1. Reliable transmission: TCP ensures that data is transmitted reliably over the
internet by verifying that packets are delivered in the correct order and
retransmitting any packets that are lost or corrupted.
For complete python subject tutorials visit : ns lectures youtube channel

2. Routing and addressing: IP provides a standardized system for routing data


packets between devices on the internet, and assigns unique IP addresses to
each device to ensure that data is delivered to the correct destination.
3. Protocol support: TCP/IP supports a wide range of protocols, including HTTP,
SMTP (Simple Mail Transfer Protocol), and FTP (File Transfer Protocol),
making it a versatile and flexible system for web communication.

In summary, TCP/IP is a critical component of web communication, enabling


reliable transmission of data over the internet and supporting a wide range of
protocols and applications.

firewall and proxy


A firewall and a proxy are both computer networking concepts that are used
to provide security, privacy, and control access to network resources. Here's
a brief explanation of each:

Firewall: A firewall is a network security system that monitors and controls


incoming and outgoing network traffic based on a set of predefined security
rules. The purpose of a firewall is to create a barrier between a secure
internal network and an untrusted external network, such as the internet.
Firewalls can be hardware or software-based and can be used to block or
allow traffic based on protocols, ports, IP addresses, and other criteria.

In essence, a firewall acts as a security gatekeeper for network traffic,


preventing unauthorized access and protecting against security threats such
as viruses, malware, and hacking attempts.

Proxy: A proxy server, also known as a "proxy," is an intermediary server that


acts as a gateway between a client and the internet. When a client (such as a
web browser) makes a request for a resource, the request is first sent to the
proxy server, which then forwards the request to the destination server. The
response from the destination server is sent back to the proxy server, which
then forwards the response back to the client.

Proxies can be used for a variety of purposes, including privacy, security, and
content filtering. For example, a proxy can be used to mask the IP address of
the client, making it more difficult for third parties to track their online
activities. Proxies can also be used to filter or block access to certain types of
content or websites, providing an additional layer of control and security.

web client
For complete python subject tutorials visit : ns lectures youtube channel

A web client is a type of software or application that runs on a user's


computer or device and is used to access web-based services or resources
over the internet. In simpler terms, a web client is any software application
that uses a web browser to interact with web servers and web applications.

Web clients can take many forms, from basic web browsers like Google
Chrome, Firefox, or Safari, to more specialized applications like email clients,
FTP clients, and other web-based tools. Web clients are used to access a
wide range of web-based services, including email, social media, online
shopping, streaming media, and more.

In the context of web development, a web client is often referred to as the


front-end of a web application or website. The web client is responsible for
presenting the user interface and allowing users to interact with the web
application, while the back-end (or server-side) of the application handles the
processing of data and the management of resources.

In summary, a web client is any software application that allows a user to


access web-based services and resources over the internet, typically through
the use of a web browser or other specialized application.

Web clients come in many forms and can be used for a wide variety of web-
based services. Here are a few examples of web clients:

1. Web browsers: Web browsers like Google Chrome, Mozilla Firefox, and
Apple Safari are some of the most commonly used web clients. They are
designed to display web pages, images, and other online content.
2. Email clients: Email clients like Microsoft Outlook, Gmail, and Apple Mail are
used to access email accounts over the internet. They provide features such
as email management, filtering, and organization.
3. Social media clients: Social media clients like Twitter, Facebook, and
LinkedIn are used to access social media accounts and interact with friends,
family, and colleagues online.
4. Online shopping clients: Online shopping clients like Amazon, eBay, and Etsy
are used to browse, search, and purchase products online.

These are just a few examples of web clients. There are many other types of
web clients used for various purposes, such as chat clients, streaming media
clients, and more.

URL (Uniform Resource Locator)


For complete python subject tutorials visit : ns lectures youtube channel

A URL (Uniform Resource Locator) is a web address that is used to locate a


specific resource on the internet, such as a web page, image, video, or
document. URLs are used to access and share resources over the internet,
and are commonly used in web browsing, search engines, and social media.

In simpler terms, a URL is a way to tell your web browser where to find a
specific web page or resource. When you type a URL into your web browser,
it uses the information in the URL to connect to the appropriate web server,
request the resource you are looking for, and display it in your browser
window.

For example, if you wanted to visit the Wikipedia website, you would enter the
URL "https://www.wikipedia.org" into your web browser's address bar. Your
browser would then connect to the Wikipedia web server, request the
homepage of the website, and display it in your browser window.

In summary, URLs are an essential part of navigating and accessing


resources on the internet. They provide a standardized way to identify and
locate web pages and other resources, and are used by millions of people
every day to access information, entertainment, and services online.

Python modules and classes for building web


servers
(or)
Python web programming
Python provides several modules and classes for building web servers. Here
are some of the commonly used web server modules and classes in Python,
advanced web clients in python are:

1. HTTP Server: This module provides classes for implementing HTTP servers,
both in the form of a simple HTTP server and a CGI-capable HTTP server. It
is a part of the standard library and can be used to create simple web servers
for testing and development.
2. Flask: Flask is a micro web framework for Python that provides tools and
libraries for building web applications. It is easy to use and can be used to
build web servers that handle requests and generate responses.
3. Django: Django is a powerful web framework for Python that provides a
complete set of tools for building web applications. It includes a web server,
URL routing, database management, and other features that make it a
popular choice for building large-scale web applications.
For complete python subject tutorials visit : ns lectures youtube channel

4. Tornado: Tornado is a scalable and non-blocking web server framework for


Python. It provides a simple and fast way to handle thousands of
simultaneous connections and can be used to build web servers for real-time
applications.
5. CherryPy: CherryPy is a web framework for Python that provides a clean and
easy-to-use interface for building web servers. It is lightweight and can be
used to build small to medium-sized web applications.

These are just a few examples of the commonly used web server modules
and classes in Python. There are many other modules and frameworks
available, each with its own set of features and benefits. Choosing the right
module or framework depends on the requirements of your application, as
well as your personal preferences and experience.

CGI (Common Gateway Interface)


CGI (Common Gateway Interface) is a protocol for web servers to execute
programs or scripts on the server side and send the results back to a web
client (usually a web browser). It is a standard method for creating dynamic
web content and applications.

CGI is typically used to process data submitted by web forms, but it can also
be used for other types of dynamic web content, such as generating graphs,
charts, or other visualizations.

The basic idea behind CGI is that the web server is configured to recognize
certain types of files, typically with a ".cgi" or ".pl" extension. When a web
client requests one of these files, the server runs the script or program and
sends the output back to the client as an HTTP response.

CGI can be used with many different programming languages, including Perl,
Python, and PHP, among others. It provides a flexible and powerful way to
create dynamic web applications and content, enabling web developers to
create custom solutions that meet specific requirements.

However, with the rise of newer web technologies and techniques, such as
server-side scripting frameworks and AJAX, the use of CGI has become less
common in recent years. Nonetheless, it remains an important part of the
history and evolution of the World Wide Web.

simple example of client-server communication using CGI:

1. The client (usually a web browser) sends a request to the web server for a
CGI script. For example, the client might request a web form to fill in some
information.
For complete python subject tutorials visit : ns lectures youtube channel

2. The web server receives the request and identifies the CGI script.
3. The CGI script processes the request and generates a response. For
example, the script might generate an HTML form that includes some input
fields and a submit button.
4. The web server sends the response back to the client as an HTTP response.
5. The client receives the response and displays the HTML form to the user.
6. The user fills in the input fields and clicks the submit button.
7. The client sends the data from the form to the web server using the HTTP
POST method.
8. The web server receives the data and passes it to the CGI script.
9. The CGI script processes the data and generates a response. For example,
the script might generate a confirmation page that displays the data the user
entered.
10. The web server sends the response back to the client as an HTTP
response.
11. The client receives the response and displays the confirmation page to
the user.

In this example, the CGI script acts as a middleman between the client and
the server. It processes the data sent by the client and generates a response
that is sent back to the client. This type of client-server communication using
CGI can be used for a wide range of web applications, from simple form
processing to more complex applications that involve database access,
authentication, and other features.

HTTP server
An HTTP server is a type of web server that accepts and responds to HTTP
(Hypertext Transfer Protocol) requests from clients (usually web browsers). It
provides a way for clients to communicate with a web application or website
hosted on the server.
For complete python subject tutorials visit : ns lectures youtube channel

The HTTP protocol is the foundation of the World Wide Web, and it allows
web clients to request resources (such as HTML pages, images, videos, etc.)
from a server using standardized commands and formats.

An HTTP server typically listens on a specific port (usually port 80 or 443 for
HTTPS), and when a client sends an HTTP request to that port, the server
processes the request and returns an HTTP response. The response typically
includes the requested resource (such as an HTML page) along with any
relevant HTTP headers (such as content type and status codes).

The use of an HTTP server is essential for delivering web applications and
websites to clients over the internet. It allows users to access web content
from anywhere in the world, and it provides a platform for web developers to
build and deploy web applications.

Some popular HTTP servers include Apache HTTP Server, NGINX, and
Microsoft IIS, among others. These servers can be configured to support
different types of web applications and technologies, and they offer a range of
features and customization options for developers and system administrators.

http server module in python:

python provides a simple http.server module that can be used to create an


HTTP server to serve static files or execute simple CGI scripts. Here's an
example of how to use the http.server module to create a simple HTTP
server in Python:

I saved this file in local disk D with name ht.py

ht.py

import http.server

import socketserver

PORT = 8000

Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:

print("Serving at port", PORT)

httpd.serve_forever()
For complete python subject tutorials visit : ns lectures youtube channel

output:

open command prompt in same location i.e., lacal disk D

Now open any web browser like google chrome and type :

http://localhost:8000

it will display all files available in local disk D and you can access that
files

it will display all files available in local disk D and you can access all
files in local disk D
For complete python subject tutorials visit : ns lectures youtube channel

it will display time as soom as you access http://localhost:8000

Once the server is running, you can access it by opening a web browser and
navigating to http://localhost:8000 (assuming you used port 8000 as the
server port). The server will serve files from the current working directory, so
make sure that any files you want to serve are located in that directory or its
subdirectories.

urllib module
The urllib module in Python stands for "Uniform Resource Locator
Library". It is a collection of modules for working with URLs and network
protocols.

The urllib module in Python is a collection of modules for working with URLs
and network protocols. Here's a brief overview of some of the modules in the
urllib package:

1. urllib.request: This module defines functions and classes for opening URLs
and downloading data from the internet. The most commonly used function in
this module is urlopen(), which is used to open a URL and return a file-like
object.
2. urllib.error: This module defines exceptions that are raised when errors
occur during URL opening and retrieval. For example, the HTTPError
exception is raised when an HTTP error occurs, such as a 404 Not Found
error.
3. urllib.parse: This module provides functions for parsing URLs and query
strings. The urlencode() function is particularly useful for encoding
dictionaries and lists as query strings.
4. urllib.robotparser: This module provides a parser for robots.txt files, which
are used by web crawlers to determine which pages on a website can be
crawled.
For complete python subject tutorials visit : ns lectures youtube channel

5. urllib.response: This module defines the response object that is returned by


the urlopen() function.

Here's an example of how to use the urllib.request module to open a URL


and read its contents:

Example:

Ur.py

import urllib.request

url = 'https://www.example.com'

response = urllib.request.urlopen(url)

html = response.read()

print(html)

output:

In this example, we import the urllib.request module and use the urlopen()
function to open the URL 'https://www.example.com'. The response object
is stored in a variable called response, and we read the contents of the
response by calling the read() method on the response object. The resulting
HTML is stored in a variable called html, which we then print to the console.

The urllib module is a powerful tool for working with URLs and network
protocols in Python, and it provides a wide range of functions and classes for
various use cases.
python

urlparse module
In Python, the urlparse module is used to parse URLs and split them into
their various components. Here's an example of how to use the urlparse
module in Python to extract the different components of a URL:

Example:

Ur.py

from urllib.parse import urlparse


For complete python subject tutorials visit : ns lectures youtube channel

url="https://www.youtube.com/@NSlectures/resource?key1=value1&key2=val
ue2#nagendra"

p = urlparse(url)

print(p.scheme) # "https"

print(p.netloc) # " www.youtube.com "

print(p.path) # "/@NSlectures/resource "

print(p.query) # "key1=value1&key2=value2"

print(p.fragment) # "nagendra"

output:

command prompt: python3 ur.py

https

www.youtube.com

/@NSlectures/resource

key1=value1&key2=value2

nagendra

In this example, we first import the urlparse function from the urllib.parse
module. We then define a variable url that contains the URL we want to
parse. We call the urlparse function and pass it the url variable, and store
the result in a new variable called parsed_url.

We can then access the different components of the parsed URL using the
following attributes of the parsed_url object:

 scheme: The protocol or scheme used to access the resource, in this case,
"https".
 netloc: netloc stands for "network location", The domain name and port
number of the server hosting the resource, in this case, " www.youtube.com
".
path: The path to the resource within the server, in this case,
“/@NSlectures/resource".
For complete python subject tutorials visit : ns lectures youtube channel

 query: The query string containing additional parameters, in this case,


"key1=value1&key2=value2".
 fragment: The fragment identifier specifying a specific part of the resource, in
this case, "nagendra".

By using the urlparse function and its various attributes, we can easily
extract the different components of a URL in Python.

urlunparse module
In Python, the urlunparse module is used to construct a URL from its various
components. Here's an example of how to use the urlunparse module in
Python to construct a URL from its different components:

Example:

Urn.py

from urllib.parse import urlunparse

url_parts = ['https', 'www.instagram.com', '/path', '', 'key=value', 'fragment']

url = urlunparse(url_parts)

print(url)

output:

command prompt: python3 urn.py

https://www.instagram.com/path?key=value#fragment

In this example, we first import the urlunparse function from the urllib.parse
module. We then define the different components of the URL we want to
construct as separate variables.

We call the urlunparse function and pass it a tuple containing the various
components of the URL, in the order of the scheme, netloc, path, params,
query, and fragment. We store the result in a new variable called url.

We can then print the value of the url variable to see the constructed URL.

The urlunparse function is a convenient way to construct a URL from its


different components in Python. By using this function and providing the
For complete python subject tutorials visit : ns lectures youtube channel

various components of a URL in the correct order, we can easily create a


valid URL.
urljoin function
Theurljoin function in Python's urllib.parse module is used to construct an
absolute URL by combining a base URL with a relative URL. The syntax for
urljoin is:

Example:

Jn.py

from urllib.parse import urljoin

r = urljoin(“https://www.youtube.com@NSlectures/resource?” ,
“key1=value1&key2=value2#nagendra”)

print(r)

output:

https://www.youtube.com/@NSlectures/resource?key1=value1&key2=value2
#nagendra

creating simple web clients


Python provides several libraries and frameworks for creating web clients,
which are programs that access data or resources from servers via HTTP
requests. Some popular libraries for creating web clients in Python include:

1. Requests: This is a popular Python library for making HTTP requests. It is


easy to use and provides a simple and intuitive API for making GET, POST,
PUT, DELETE, and other types of HTTP requests.
2. urllib: This is a built-in Python library that provides several modules for
working with URLs and making HTTP requests. It is a bit more complex than
Requests, but it provides more low-level control over the HTTP requests.
3. httplib: This is another built-in Python library for making HTTP requests. It is
lower-level than urllib and requires more code to make requests, but it
provides a lot of control over the requests and responses.

python program to read the source code contents of


www.google.com
For complete python subject tutorials visit : ns lectures youtube channel

program:

import urllib.request

print(urllib.request.urlopen("https://www.google.com").read())

output:
b'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="text/html;
charset=UTF-8" http-equiv="Content-Type"><meta
content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script
nonce="I1IeSJ7ROL5MjZg56sprmw">(function(){window.google={kEI:\'Vf_1Y9WIAvHY1sQPjdiQqAw\',kEXPI:\'0,1359409,6058,2
07,4804,2316,383,246,5,1129120,1197759,642,166,379924,16114,28684,22430,1362,12320,4745,12834,4998,13228,3847,38444,159
3,1279,2891,1103,10651,606,57184,3506,6398,9358,3,346,230,1014,1,5445,148,11323,2652,4,1528,2304,29062,13065,13658,13795,
7428,5821,2536,4094,7596,1,11942,30218,2,14016,2715,23024,5679,1020,31122,4568,6259,23418,1252,5835,14967,4333,8,7476,44
5,2,2,1,6959,17667,2006,8155,7381,2,15968,872,19634,7,1922,5784,3995,13880,7511,14763,6305,2006,17769,424,15605,2013,2518
,14,82,2932,1709,8692,6071,802,1622,1778,4977,1747,2040,2124,4328,2226,2426,753,518,2798,3847,2,566,988,2265,765,426,4705,
976,3,1411,20,3,867,136,102,2447,55,846,3819,1296,508,567,6986,181,495,1152,1086,5,442,1206,109,96,585,447,852,1633,2531,26
39,3350,949,2,3,17,2,3,1143,353,933,4492,249,212,2,375,265,272,1047,2033,1827,271,64,670,1,2054,1307,83,293,497,274,475,123,
254,444,34,396,909,31,474,353,10,832,127,87,100,13,773,319,515,510,76,286,34,728,492,426,475,329,692,246,880,1108,35,2,10,3,1
,7,146,3,103,1109,133,2,2380,850,191,631,128,236,199,294,253,377,44,906,46,1,12,1070,1514,102,302,447,498,5,667,4,23,264,71,8
19,541,11,396,891,5241970,209,41,151,8794103,4589,3311,141,795,19735,1,1,346,4356,13,7,4,7,23646905,299193,2862026,118011
6,1964,1007,15666,2893,512,5738,11103,1369,1485\',kBL:\'WEGz\'};google.sn=\'webhp\';google.kHL=\'en-
……………………………………………

Cookies and sessions


Cookies and sessions are two mechanisms used in web development for
managing user data and maintaining user state between requests.

Cookies:

Cookies are small text files that are stored on the user's computer by the
web browser. They are used to store information such as user preferences,
login credentials, and other data that needs to be remembered across
different pages or visits to a website. In Python, the http.cookies module
provides functionality for creating, reading, and setting cookies.

Here's an example of setting a cookie in Python:

from http.cookies import SimpleCookie

cookie = SimpleCookie()

cookie['username'] = 'johndoe'

cookie['username']['expires'] = 3600

print(cookie)
For complete python subject tutorials visit : ns lectures youtube channel

This sets a cookie named 'username' with a value of 'johndoe' and an


expiration time of 1 hour (3600 seconds).

Sessions:

Sessions are a way to maintain state information between requests. Unlike


cookies, session data is stored on the server side, and a session ID is used
to link the user's requests to their session data. In Python, the session object
is typically managed by a web framework such as Django, Flask, or Pyramid.

Creating simple CGI application in python


Program.py

import cgitb

cgitb.enable()#for debugging

print(“content-type:text/html”)

print("<html>")

print("<head>")

print("<title>Hello Friends</title>")

print("</head>")

print("<body>")

print("<h1>Hello Friends</h1>")

print("<h2>my name is nagendra</h2>")

print("<h3>i am from hyderabad</h3>")

print(“<p>my name is ch. nagendrasai, i am from hyderabad</p>”)

print("</body>")

print("</html>")

output:
For complete python subject tutorials visit : ns lectures youtube channel

Example-2
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel
For complete python subject tutorials visit : ns lectures youtube channel

UNIT – 5
DATABASE PROGRAMMING
1. In-memory and Persistent Database Management Systems

2. Database, Types of databases, What is database software?, What is a


database management system (DBMS)?, What is a MySQL database?, What
is Structured Query Language (SQL)?, Database challenges.

3. SQL, SQL Commands, SQL operations, Difference between Open Source


Database and Commercial Database?, What’s the difference between a
database and a spreadsheet?

4. Python Database API, python sqlite3, database API module attributes,


parameter style, connection() function, Connection Object methods

5. Cursor Objects, Cursor Objects attributes and methods

6. SQLite – Constraints, How to Connect Python with SQL Database?

7. Constructors in Python, Types of Python Constructor?

8. Database Exceptions

9. OFFSET , ORDER BY , FILTER BY in SQL

10. Python SQLite – CRUD Operations, Python program to create student and
employee databases, Python program to display, update and delete the
contents of database table

11. Transaction (Begin, Commit, Rollback)

12. Object-relational Managers (ORMs)

13. SQLAlchemy

14. example program that creates a database of students' details using


SQLAlchemy
For complete python subject tutorials visit : ns lectures youtube channel

In-memory and Persistent Database Management


Systems
What is an in-memory database system?

An in-memory database system (IMDS) is a database management


system that stores data entirely in main memory. This differs to traditional
(on-disk/persistent) database systems, which are designed store data on
persistent media. Because working with data in memory is
much faster than writing to and reading from a file system, IMDSs can
perform applications’ data management functions orders of magnitude
faster. Because their design is typically simpler than that of persistent
database systems, IMDSs can also impose significantly lower memory and
CPU requirements.

Simple architecture of in-memory database system.

What is a persistent database system?


persistent storage is any data storage device that retains data after power to
that device is shut off. It is also sometimes referred to as nonvolatile
storage.
on-disk or persistent database systems cache frequently requested data
in memory for faster access, but write database updates, insertions and
deletes through the cache to be stored to disk. On the plus side, byte-for-
byte, disk storage can be cheaper than RAM, and can also take less
For complete python subject tutorials visit : ns lectures youtube channel

physical space when form factor is a consideration (e.g. handheld


electronics).

A hybrid of the two:


With some database systems, databases can be stored all-in-memory, all-
persistent, or have a mix of in-memory tables and persistent tables. This
flexibility enables developers to tailor data management in order to optimize
applications for speed and persistence, and make intelligent trade-offs
between cost-efficiency, power consumption, and physical space-
conserving data storage hardware.

Database
A database is an organized collection of structured information, or data,
typically stored electronically in a computer system. A database is usually
controlled by a database management system (DBMS). Together, the data
and the DBMS, along with the applications that are associated with them,
are referred to as a database system, often shortened to just database.

Data within the most common types of databases in operation today is


typically modeled in rows and columns in a series of tables to make
processing and data querying efficient. The data can then be easily
accessed, managed, modified, updated, controlled, and organized. Most
databases use structured query language (SQL) for writing and querying
data.

Types of databases
There are many different types of databases. The best database for a
specific organization depends on how the organization intends to use the
data.

Relational databases
 Relational databases became dominant in the 1980s. Items in a
relational database are organized as a set of tables with columns and
For complete python subject tutorials visit : ns lectures youtube channel

rows. Relational database technology provides the most efficient and


flexible way to access structured information.

Object-oriented databases
 Information in an object-oriented database is represented in the form of
objects, as in object-oriented programming.

Distributed databases
 A distributed database consists of two or more files located in different
sites. The database may be stored on multiple computers, located in the
same physical location, or scattered over different networks.

Data warehouses
 A central repository for data, a data warehouse is a type of database
specifically designed for fast query and analysis.

NoSQL databases
 A NoSQL, or nonrelational database, allows unstructured and
semistructured data to be stored and manipulated (in contrast to a
relational database, which defines how all data inserted into the
database must be composed). NoSQL databases grew popular as web
applications became more common and more complex.

Graph databases
 A graph database stores data in terms of entities and the relationships
between entities.
 OLTP databases.
 An OLTP database is a speedy, analytic database designed for large
numbers of transactions performed by multiple users.
These are only a few of the several dozen types of databases in use today.
Other, less common databases are tailored to very specific scientific,
financial, or other functions. In addition to the different database types,
changes in technology development approaches and dramatic advances
such as the cloud and automation are propelling databases in entirely new
directions. Some of the latest databases include
For complete python subject tutorials visit : ns lectures youtube channel

Open source databases


 An open source database system is one whose source code is open
source; such databases could be SQL or NoSQL databases.
What is database software?
Database software is used to create, edit, and maintain database files and
records, enabling easier file and record creation, data entry, data editing,
updating, and reporting. The software also handles data storage, backup
and reporting, multi-access control, and security. Strong database security
is especially important today, as data theft becomes more frequent.
Database software is sometimes also referred to as a “database
management system” (DBMS).

Database software makes data management simpler by enabling users to


store data in a structured form and then access it. It typically has a
graphical interface to help create and manage the data and, in some cases,
users can construct their own databases by using database software.

What is a database management system (DBMS)?

A database typically requires a comprehensive database software program


known as a database management system (DBMS). A DBMS serves as an
interface between the database and its end users or programs, allowing
users to retrieve, update, and manage how the information is organized
and optimized. A DBMS also facilitates oversight and control of databases,
enabling a variety of administrative operations such as performance
monitoring, tuning, and backup and recovery.

Some examples of popular database software or DBMSs include MySQL,


Microsoft Access, Microsoft SQL Server, FileMaker Pro, Oracle Database,
and dBASE.

What is a MySQL database?

MySQL is an open source relational database management system based


on SQL. It was designed and optimized for web applications and can run
For complete python subject tutorials visit : ns lectures youtube channel

on any platform. As new and different requirements emerged with the


internet, MySQL became the platform of choice for web developers and
web-based applications. Because it’s designed to process millions of
queries and thousands of transactions, MySQL is a popular choice for
ecommerce businesses that need to manage multiple money transfers. On-
demand flexibility is the primary feature of MySQL.
MySQL is the DBMS behind some of the top websites and web-based
applications in the world, including Airbnb, Uber, LinkedIn, Facebook,
Twitter, and YouTube.

What is Structured Query Language (SQL)?


SQL is a programming language used by nearly all relational databases to
query, manipulate, and define data, and to provide access control. SQL
was first developed at IBM in the 1970s with Oracle as a major contributor,
which led to implementation of the SQL ANSI standard, SQL has spurred
many extensions from companies such as IBM, Oracle, and Microsoft.
Although SQL is still widely used today, new programming languages are
beginning to appear.

Database challenges
Today’s large enterprise databases often support very complex queries and
are expected to deliver nearly instant responses to those queries. As a
result, database administrators are constantly called upon to employ a wide
variety of methods to help improve performance. Some common
challenges that they face include:

 Absorbing significant increases in data volume. The explosion of


data coming in from sensors, connected machines, and dozens of other
sources keeps database administrators scrambling to manage and
organize their companies’ data efficiently.

 Ensuring data security. Data breaches are happening everywhere


these days, and hackers are getting more inventive. It’s more important
than ever to ensure that data is secure but also easily accessible to
users.

 Keeping up with demand. In today’s fast-moving business


environment, companies need real-time access to their data to support
timely decision-making and to take advantage of new opportunities.
For complete python subject tutorials visit : ns lectures youtube channel

 Managing and maintaining the database and


infrastructure. Database administrators must continually watch the
database for problems and perform preventative maintenance, as well as
apply software upgrades and patches. As databases become more
complex and data volumes grow, companies are faced with the expense
of hiring additional talent to monitor and tune their databases.

 Removing limits on scalability. A business needs to grow if it’s going


to survive, and its data management must grow along with it. But it’s very
difficult for database administrators to predict how much capacity the
company will need, particularly with on-premises databases.

 Ensuring data residency, data sovereignty, or latency


requirements. Some organizations have use cases that are better
suited to run on-premises. In those cases, engineered systems that are
pre-configured and pre-optimized for running the database are ideal.
Customers achieve higher availability, greater performance and up to
40% lower cost with Oracle Exadata, according to Wikibon’s recent
analysis (PDF).
Addressing all of these challenges can be time-consuming and can prevent
database administrators from performing more strategic functions.

What is SQL?

 SQL stands for Structured Query Language


 SQL lets you access and manipulate databases
 SQL became a standard of the American National Standards Institute
(ANSI) in 1986, and of the International Organization for
Standardization (ISO) in 1987

What Can SQL do?

 SQL can execute queries against a database


 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
For complete python subject tutorials visit : ns lectures youtube channel

 SQL can create stored procedures in a database


 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

Some of The Most Important SQL Commands:

 SELECT - extracts data from a database


 UPDATE - updates data in a database
 DELETE - deletes data from a database
 INSERT INTO - inserts new data into a database
 CREATE DATABASE - creates a new database
 ALTER DATABASE - modifies a database
 CREATE TABLE - creates a new table
 ALTER TABLE - modifies a table
 DROP TABLE - deletes a table
 CREATE INDEX - creates an index (search key)
 DROP INDEX - deletes an index

There are four basic SQL Operations or SQL Statements:


 SELECT – This statement selects data from database tables.
 UPDATE – This statement updates existing data into database
tables.
 INSERT – This statement inserts new data into database tables.
 DELETE – This statement deletes existing data from database
tables.

Difference between Open Source Database and Commercial


Database

1. Open Source Database: An open-source database is a database


where anyone can easily view the source code and this is open and free
to download. Also for the community version, some small additional and
affordable costs are imposed. Open Source Database provides Limited
technical support to end-users. Here Installation and updates are
administered by the user. For example: MYSQL, PostgreSQL, MongoDB
etc.

2. Commercial Database : Commercial database are that which has


been created for Commercial Purpose only. They are premium and are
For complete python subject tutorials visit : ns lectures youtube channel

not free like Open Source Database. In Commercial Database it is


guaranteed that technical support is provided. In this Installation and
updates are Administrated by software Vendor. For examples: Oracle,
IBM DB2 etc.

Difference between Open Source Database and Commercial


Database:

Sr. Basis of
No. Comparison Open Source Database Commercial Database

Commercial Database
In Open Source Database are that which has been
anyone can easily view created for Commercial
1. Focus the Source code of it. purpose only.

Examples: MYSQL,
PostgreSQL, MongoDB Examples: Oracle, DB2,
2. Examples etc. Splunk etc.

They are free or have They are premium and


additional and affordable are not free like open
3. Cost cost. source database.

The community cannot


The community can see, see, exchange, or
share, and modify the modify the code of
code of open-source commercial DBMS
4. Community DBMS software. software.

The code is not


accessible to
Because the source code unauthorized users and
is open, there is a risk of has a high level of
5. Source Code coding malfunction. protection.

6. Technical It provide limited technical It provide guaranteed


For complete python subject tutorials visit : ns lectures youtube channel

Sr. Basis of
No. Comparison Open Source Database Commercial Database

support support. technical support.

In this software is In this Software is


available under free available under high
7. License licensing. licensing cost.

In this user’s get


In this User’s needs to dedicated support from
rely on Community Vendor’s from where
8. Support Support. one’s buy.

In this Installation and


In this Installation and updates are
Installation Updates are administrated by
9. and Updates administrated by user. Software Vendor.

 There is a single point


of contact for any
 Bug fixes are simple to issues that arise. That
implement without implies, you pay for
having to go through specific needs, and
the approval process there is a party to
at corporate. blame if difficulties
 For any premium develop.
solution, a free open  The licensing is
source alternative with usually obvious, and it
the same or more comes with a
functionality is always guarantee.
accessible.  Developers typically
 Because it is more have a thorough plan
visible by nature, it can in place for the
be inspected for programme and
security concerns, release updates as
10. Benefits which is a big benefit. needed. This allows
For complete python subject tutorials visit : ns lectures youtube channel

Sr. Basis of
No. Comparison Open Source Database Commercial Database

businesses to save
money on the costs of
technical outages and
failures.

 Volunteer Technical
support
 Because of
Compatibility
difficulties, it cannot be
assured that it will work
in each user’s
environment due to
compatibility
difficulties.
 Professionals are
required to manage
and even install the
essential infrastructure
because some of these
difficulties vary from  Strict Licensing
software to hardware. guidelines
 Open source also  Source code cannot
poses a significant be modified so extra
security risk because cost is incurred for
some of it can easily getting more
contain security functionality of
11. Drawbacks exploits. premium featu

Which Database is Better : Commercial or Open Source Database :

In conclusion, it is important to remember that both Commercial and


Open Source database have their own Advantages and Disadvantages. If
we considered which Database is better, then in most cases it makes
For complete python subject tutorials visit : ns lectures youtube channel

sense to choose Open Source as compared to Commercial Database


because :
 Open Source database is Cost-effective.
 Better quality source code.
 More secure.
 More preferred.

What’s the difference between a database and a


spreadsheet?

Databases and spreadsheets (such as Microsoft Excel) are both


convenient ways to store information. The primary differences between the
two are:

 How the data is stored and manipulated


 Who can access the data
 How much data can be stored
Spreadsheets were originally designed for one user, and their
characteristics reflect that. They’re great for a single user or small number
of users who don’t need to do a lot of incredibly complicated data
manipulation. Databases, on the other hand, are designed to hold much
larger collections of organized information—massive amounts, sometimes.
Databases allow multiple users at the same time to quickly and securely
access and query the data using highly complex logic and language.
For complete python subject tutorials visit : ns lectures youtube channel

Python Database API


A database is an organized collection of data, generally stored and
accessed electronically from a computer system. Where databases are more
complex they are often developed using formal design and modeling
techniques.

The database management system (DBMS) is the software that interacts


with end users, applications, and the database itself to capture and analyze
the data. The DBMS software additionally encompasses the core facilities
provided to administer the database. The sum total of the database, the
DBMS and the associated applications can be referred to as a “database
system”. Often the term “database” is also used to loosely refer to any of the
DBMS, the database system or an application associated with the database.
For complete python subject tutorials visit : ns lectures youtube channel

Now Lets understand the meaning of API

Meaning of API (Application Programming Interface)

(Application Programming Interface) API is a language and message format


used by an application program to communicate with the operating system or
some other control program such as a database management system
(DBMS). APIs are implemented by writing function calls in the program.which
provide the linkage to the required subroutine for execution.

Thus, an API implies that a driver or program module is available in the


computer to perform the operation or that software must be linked into the
existing program to perform the tasks.

sqlite3 — DB-API 2.0 interface for SQLite databases

Python SQLite3 module is used to integrate the SQLite database with


Python. It is a standardized Python DBI API 2.0 and provides a
straightforward and simple-to-use interface for interacting with SQLite
For complete python subject tutorials visit : ns lectures youtube channel

databases. There is no need to install this module separately as it comes


along with Python after the 2.5x version.
Databases offer numerous functionalities by which one can manage large
amounts of information easily over the web and high-volume data input and
output over a typical file such as a text file. SQL is a query language and is
very popular in databases. Many websites use MySQL. SQLite is a “light”
version that works over syntax very much similar to SQL. SQLite is a self-
contained, high-reliability, embedded, full-featured, public-domain, SQL
database engine. It is the most used database engine on the world wide
web. Python has a library to access SQLite databases, called sqlite3,
intended for working with this database which has been included with
Python package since version 2.5. SQLite has the following features.
1. Serverless
2. Self-Contained
3. Zero-Configuration
4. Transactional
5. Single-Database

Serverless

Generally, an RDBMS such as MySQL, PostgreSQL, etc., needs a


separate server process to operate. SQLite does not require a server to
run.

Self-Contained

SQLite is self-contained means it does not need any external


dependencies like an operating system or external library. This feature of
SQLite help especially in embedded devices like iPhones, Android phones,
game consoles, handheld media players, etc..

Zero-Configuration

SQLite is zero-configuration means no setup or administration needed.


Because of the serverless architecture, you don’t need to “install” SQLite
before using it. There is no server process that needs to be configured,
started, and stopped.

Transactional

SQLite is Transactional means they are atomic, consistent, isolated, and


durable(ACID). All transactions in SQLite are fully ACID-compliant. In other
words, all changes within a transaction take place completely or not at all.
even when an unexpected situation like application crash, power failure, or
operating system crash occurs.
For complete python subject tutorials visit : ns lectures youtube channel

Single-Database

SQLite is a single database that means it allows a single database


connection to access multiple database files simultaneously. These
features bring many nice features like joining tables in different databases
or copying data between databases in a single command. SQLite also
uses dynamic types for tables. It means you can store any value in any
column, regardless of the data type.
Understanding of SQLite Module Working in Python
Python SQLite is used to demonstrate how to develop Python database
applications with the SQLite database. You will learn how to perform
SQLite database operations from Python. SQLite comes built-in with most
of the computers and mobile devices and browsers. Python’s official sqlite3
module helps us to work with the SQLite database.

Benefits of the Python for Database Programming


1. Python is very popular scripting language for connected with databases.

2. Python ecosystem is very rich and it is easy to use tools for datascience.

3. Due to open source nature, Python is portable for many platforms.

4. Python support Relational Database System.

5. Writing Python code to access database API commands which refers to as DB-
API.

SQLite natively supports the following types:

NULL, INTEGER, REAL, TEXT, BLOB. The following Python types can thus
be sent to SQLite without any problem:
For complete python subject tutorials visit : ns lectures youtube channel

Connection Object methods


Database Connections and Manage Transactions
For complete python subject tutorials visit : ns lectures youtube channel

cursor(factory=Cursor)-The cursor method accepts a single optional


parameter factory. If supplied, this must be a callable returning an instance
of Cursor or its subclasses.

commit()-This method commits the current transaction. If you don’t call this
method, anything you did since the last call to commit() is not visible from other
database connections. If you wonder why you don’t see the data you’ve written
to the database, please check you didn’t forget to call this method.

rollback()-This method rolls back any changes to the database since the last
call to commit().

close()-This closes the database connection. Note that this does not
automatically call commit(). If you just close your database connection without
calling commit() first, your changes will be lost!

Cursor Objects
These objects represent a database cursor, which is used to manage the
context of a fetch operation. Cursors created from the same connection are
not isolated, i.e., any changes done to the database by a cursor are
immediately visible by the other cursors. Cursors created from different
connections can or can not be isolated, depending on how the transaction
support is implemented (see also the connection’s .rollback() and .commit()
methods).

Cursor Objects should respond to the following methods and attributes.

Various Cursor object attributes:


1. description

This read-only attribute is a sequence of 7-item sequences.

Each of these sequences contains information describing one result column:

 name
 type_code
 display_size
 internal_size
 precision
 scale
 null_ok
For complete python subject tutorials visit : ns lectures youtube channel

The first two items (name and type_code) are mandatory, the other five are
optional and are set to None if no meaningful values can be provided.

2. rowcount

This read-only attribute specifies the number of rows that the


last .execute*() produced.

Cursor methods

execute(sql[, parameters])-prepare and execute a database operation.

executemany(sql, seq_of_parameters)-Executes an SQL command against


all parameter sequences or mappings found in the
sequence seq_of_parameters.

fetchone()-Fetches the next row of a query result set, returning a single


sequence, or None when no more data is available.

fetchmany(size=cursor.arraysize)-Fetches the next set of rows of a query


result, returning a list. An empty list is returned when no more rows are
available.

fetchall()-Fetches all (remaining) rows of a query result, returning a list. Note


that the cursor’s arraysize attribute can affect the performance of this
operation. An empty list is returned when no rows are available.

close()-Close the cursor now.

arraysize-Read/write attribute that controls the number of rows returned


by fetchmany(). The default value is 1 which means a single row would be
fetched per call.

SQLite - Constraints
Constraints are the rules enforced on a data columns on table. These are
used to limit the type of data that can go into a table. This ensures the
accuracy and reliability of the data in the database.
Constraints could be column level or table level. Column level constraints
are applied only to one column, whereas table level constraints are applied
to the whole table.
For complete python subject tutorials visit : ns lectures youtube channel

Following are commonly used constraints available in SQLite.


1. NOT NULL Constraint − Ensures that a column cannot have NULL
value.
2. DEFAULT Constraint − Provides a default value for a column when
none is specified.
3. UNIQUE Constraint − Ensures that all values in a column are different.
4. PRIMARY Key − Uniquely identifies each row/record in a database
table.
5. CHECK Constraint − Ensures that all values in a column satisfies
certain conditions.

1. NOT NULL Constraint

By default, a column can hold NULL values. If you do not want a column to
have a NULL value, then you need to define such constraint on this column
specifying that NULL is now not allowed for that column.
A NULL is not the same as no data, rather, it represents unknown data.
Example
For example, the following SQLite statement creates a new table called
COMPANY and adds five columns, three of which, ID and NAME and AGE,
specifies not to accept NULLs.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);

2. DEFAULT Constraint

The DEFAULT constraint provides a default value to a column when the


INSERT INTO statement does not provide a specific value
Example
For example, the following SQLite statement creates a new table called
COMPANY and adds five columns. Here, SALARY column is set to 5000.00
by default, thus in case INSERT INTO statement does not provide a value
for this column, then by default, this column would be set to 5000.00.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
For complete python subject tutorials visit : ns lectures youtube channel

AGE INT NOT NULL,


ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);

3. UNIQUE Constraint

The UNIQUE Constraint prevents two records from having identical values
in a particular column. In the COMPANY table, for example, you might want
to prevent two or more people from having an identical age.
Example
For example, the following SQLite statement creates a new table called
COMPANY and adds five columns. Here, AGE column is set to UNIQUE, so
that you cannot have two records with the same age −
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL UNIQUE,
ADDRESS CHAR(50),
SALARY REAL DEFAULT 50000.00
);

4. PRIMARY KEY Constraint

The PRIMARY KEY constraint uniquely identifies each record in a database


table. There can be more UNIQUE columns, but only one primary key in a
table. Primary keys are important when designing the database tables.
Primary keys are unique IDs.
Example
You already have seen various examples above where we have created
COMPANY table with ID as a primary key.
CREATE TABLE COMPANY(
ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL
);

5. Dropping Constraint
For complete python subject tutorials visit : ns lectures youtube channel

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE


command in SQLite allows the user to rename a table or add a new column
to an existing table. It is not possible to rename a column, remove a column,
or add or remove constraints from a table.

How to Connect Python with SQL Database?

Python is a high-level, general-purpose, and very popular programming


language. Basically, it was designed with an emphasis on code
readability, and programmers can express their concepts in fewer lines of
code. We can also use Python with SQL. In this article, we will learn how
to connect SQL with Python using the ‘MySQL Connector Python module.
The diagram given below illustrates how a connection request is sent to
MySQL connector Python, how it gets accepted from the database and
how the cursor is executed with result data.

SQL connection with Python

Connecting MySQL with Python


To create a connection between the MySQL database and Python,
the connect() method of mysql.connector module is used. We pass the
database details like HostName, username, and the password in the method
call, and then the method returns the connection object.
The following steps are required to connect SQL with Python:
Step 1: Download and Install the free MySQL database .
Step 2: After installing the MySQL database, open your Command prompt.
Step 3: open your Command prompt
For complete python subject tutorials visit : ns lectures youtube channel

Step 4: Now run the commands given below to download and install
“MySQL Connector”. Here, mysql.connector statement will help you to
communicate with the MySQL database.

Download and install “MySQL Connector”

pip install mysql-connector-python

Step 5: Test MySQL Connector


To check if the installation was successful, or if you already installed
“MySQL Connector”, go to your IDE and run the given below code :

Import mysql.connector

If the above code gets executed with no errors, “MySQL Connector” is


ready to be used.
Step 6: Create Connection
Now to connect SQL with Python, run the code given below in your IDE.

import mysql.connector
con = mysql.connector.connect(
host = "localhost",
user = "nagendra",
password = "123456"
)

con.close()

Constructors in Python
Constructor in python is a special method that is called when an object is
created. The purpose of a python constructor is to assign values to the data
members within the class when an object is initialized. In this article, we will
learn what is python constructor, their types, rules to define constructors in
python.

In Python, a constructor is a special method that is called when an object is


created. The purpose of a python constructor is to assign values to the data
members within the class when an object is initialized. The name of the
constructor method is always __init__.
Here is an example of a simple class with a constructor:
For complete python subject tutorials visit : ns lectures youtube channel

Example:

class Person:

def __init__(self):

self.name = "John"

self.age = 30

person = Person()

print(person.name)

print(person.age)

Output:
John
30
In this example, the __init__ method is called when the Person object is
created, and it sets the name and age attributes of the object.
The __init__ method is commonly referred to as the “constructor” because it is
responsible for constructing the object. It is called automatically when the
object is created, and it is used to initialize the object’s attributes.

Types of Python Constructor


In Python, there are two types of constructors:

 Default Constructor: A default constructor is a constructor that takes no


arguments. It is used to create an object with default values for its
attributes.
 Parameterized Constructor: A parameterized constructor is a constructor
that takes one or more arguments. It is used to create an object with
custom values for its attributes.
 Non-Parameterized Constructor: A non-parameterized constructor is a
constructor that does not take any arguments. It is a special method in
Python that is called when you create an instance of a class. The non-
parameterized constructor is used to initialize the default values for the
instance variables of the object.
For complete python subject tutorials visit : ns lectures youtube channel

Database Exceptions
The module should make all error information available through these
exceptions or subclasses thereof:

Warning

Exception raised for important warnings like data truncations while


inserting, etc.

Error

Exception that is the base class of all other error exceptions. You can
use this to catch all errors with one single except statement. Warnings
are not considered errors and thus should not use this class as base.
It must be a subclass of the Python Exception class .

InterfaceError

Exception raised for errors that are related to the database interface
rather than the database itself. It must be a subclass of Error.

DatabaseError

Exception raised for errors that are related to the database. It must be
a subclass of Error.

DataError

Exception raised for errors that are due to problems with the
processed data like division by zero, numeric value out of range, etc. It
must be a subclass of DatabaseError.

OperationalError

Exception raised for errors that are related to the database’s operation
and not necessarily under the control of the programmer, e.g. an
unexpected disconnect occurs, the data source name is not found, a
transaction could not be processed, a memory allocation error
occurred during processing, etc. It must be a subclass
of DatabaseError.

IntegrityError
For complete python subject tutorials visit : ns lectures youtube channel

Exception raised when the relational integrity of the database is


affected, e.g. a foreign key check fails. It must be a subclass
of DatabaseError.

InternalError

Exception raised when the database encounters an internal error, e.g.


the cursor is not valid anymore, the transaction is out of sync, etc. It
must be a subclass of DatabaseError.

ProgrammingError

Exception raised for programming errors, e.g. table not found or


already exists, syntax error in the SQL statement, wrong number of
parameters specified, etc. It must be a subclass of DatabaseError.

NotSupportedError

Exception raised in case a method or database API was used which is


not supported by the database, e.g. requesting a .rollback() on a
connection that does not support transaction or has transactions
turned off. It must be a subclass of DatabaseError.

OFFSET , ORDER BY , FILTER BY in SQL


Let us consider a situation where we need to display only a specific number
of rows within a given range. In this case, we might have to remove a
specific set of rows from the beginning and display them till the upper bound
of the range specified as per requirement. In such scenarios, we use
the OFFSET command in SQL.

Offset in SQL is used to eliminate a set of records from a given table in


order to retrieve a set of records according to the requirement of the
database.

Basically, it is used to find a starting point to display a set of rows as a final


output. By using OFFSET, we discard the desired number of rows from the
beginning of the table till the number mentioned with
the OFFSET command.

How to Use Offset in SQL?

OFFSET in SQL is generally used with the ORDER BY clause with a value
greater than or equal to zero.

Syntax using OFFSET:


For complete python subject tutorials visit : ns lectures youtube channel

SELECT column_names
FROM table_name
ORDER BY column_names
OFFSET n ROWS //n is the number of rows to be excluded.

Example of OFFSET in SQL Server

Let's look at a few examples to learn how to use OFFSET :

Employees table:

Emp_ID Emp_name Emp_gender Emp_age


101 Amar Rathore Male 27
102 Dimple Khanna Female 28
103 Mayuri Chatterji Female 27
104 Karthik Padman Male 30
105 Aisha Khan Female 29
106 Dianna Female 27
107 Jaspreet Male 30

1. Display the contents of the table, removing the first row

Query:

SELECT Emp_name, Emp_gender


FROM employees
ORDER BY age
OFFSET 1 ROWS;

Output:

Emp_name Emp_gender
Mayuri Chatterji Female
Dianna Female
Dimple Khanna Female
Aisha Khan Female
Karthik Padman Male
Jaspreet Male

filter_by is used for simple queries on the column names using regular kwargs,
like

EXAMPLE: db.users.filter_by(name='ramesh')

It will identify column with name “ramesh”


For complete python subject tutorials visit : ns lectures youtube channel

Python SQLite – CRUD Operations


CRUD Operations
The abbreviation CRUD expands to Create, Read, Update and Delete.
These four are fundamental operations in a database. In the sample
database, we will create it, and do some operations. Let’s discuss these
operations one by one with the help of examples.
CREATE
The create command is used to create the table in database. First we will
go through its syntax then understand with an example.
Syntax: CREATE TABLE table_name ( Attr1 Type1, Attr2 Type2, … ,
Attrn Typen )

INSERT
This refers to the insertion of new data into the table. Data is inserted in
the form of a tuple. The number of attributes in the tuple must be equal to
that defined in the relation schema while creating the table.

Syntax: INSERT INTO tableName VALUES ( value1, value2, … valuen )

READ

This refers to reading data from a database. A read statement has three
clauses:
1. SELECT: Takes as the predicate the attributes to be queried, use * for all
attributes.
2. FROM: Takes as the predicate a relation.
3. WHERE: Takes as the predicate a condition, this is not compulsory.
After executing a read statement in python SQLite3, an iterable cursor object is
returned. This can be used to print data.
Example: SELECT NAME, POINTS,

'select * from employee'


For complete python subject tutorials visit : ns lectures youtube channel

UPDATE

This refers to the updating of values already present in the table.


Syntax: UPDATE tableName SET Attribute1 = Value1 , Attribute2 = Value2 , . .
. WHERE condition;

The WHERE clause must be included, else all records in the table will
be updated.

EXAMPLE:

cur.execute('update employee set name="ganesh" where empID="ID511"')

DELETE

This refers to the deletion of the tuple present in the table.


SYNTAX:

DELETE FROM tableName WHERE condition


If WHERE clause is not used then all the records will be deleted.

EXAMPLE:

cur.execute(' delete from employee where empID="ID511" ‘)


For complete python subject tutorials visit : ns lectures youtube channel

1. Python program to create student database


import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
cur.execute('create table if not exists students(name varchar(50), rollno
varchar(50), section varchar(50))')
con.commit()
cur.execute('insert into students values("sai", "511A", "sectionA")')
cur.execute('insert into students values("ramesh", "512A", "sectionB")')
cur.execute('insert into students values("raju", "513A", "sectionC")')
con.commit()
con.close()

output:
In order to check output, you need database viewer
Above program will create database with name mydatabase if database is not
available. If database is already available then it will connect to that database.

this mydatabase contains table with name i.e., students


mydatabase.db>>>
Table:students
name rollno section
sai 511A sectionA
ramesh 512A sectionB
raju 513A sectionC

Python program to create employee database


For complete python subject tutorials visit : ns lectures youtube channel

import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
cur.execute('create table if not exists employee(name varchar(50), empID
varchar(50), salary int )')
con.commit()
cur.execute('insert into employee values("sai", "ID511", 25000)')
cur.execute('insert into employee values("ramesh", "ID512", 10000)')
cur.execute('insert into employee values("raju", "ID513",40000)')
con.commit()
con.close()

output:
In order to check output, you need database viewer
Above program will create database with name mydatabase if database is not
available. If database is already available then it will connect to that database.

this mydatabase contains table with name i.e., employee.

mydatabase.db>>>
Table:employee
name empID salary
sai ID511 25000
ramesh ID512 10000
raju ID513 40000

2. Python program to display the contents of database


table.
For complete python subject tutorials visit : ns lectures youtube channel

There are many ways to display the contents of database table


1. By using for loop
2. By using fetchall() function
3. By using fetchmany() function
4. By using fetchone() function
For example, my database file is mydatabase.db and this database contains table
with name employee.
Employee table contains following information
mydatabase.db>>>
Table:employee
name empID salary
sai ID511 25000
ramesh ID512 10000
raju ID513 40000

Method1- This is Python program to display the contents on my python


terminal By using for loop:
display.py

import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()

b=cur.execute('select * from employee')

for i in b:

print("name=",i[0])

print("empID=",i[1])

print("salary=",i[2])

con.close()
For complete python subject tutorials visit : ns lectures youtube channel

open command prompt :>>> python3 display.py

output:

name= sai

empID= ID511

salary= 25000

name= ramesh

empID= ID512

salary= 10000

name= raju

empID= ID513
salary= 40000

Method 2- This is Python program to display the contents on my python


terminal By using fetchall() function:
By default fetchall()function will display output in the form of list and
each row is represented in the form of tuple.
display.py

import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()

b=cur.execute('select * from employee')

print(b.fetchall())

con.close()

open command prompt :>>> python3 display.py

output:
For complete python subject tutorials visit : ns lectures youtube channel

[('sai', 'ID511', 25000), ('ramesh', 'ID512', 10000), ('raju', 'ID513', 40000)]

Method 3- This is Python program to display the contents on my python


terminal By using fetchone() function:
By default fetchone()function will display only first row in the table and it
will display output in the form of tuple.
display.py

import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()

b=cur.execute('select * from employee')

print(b.fetchone())

con.close()

open command prompt :>>> python3 display.py

output:

('sai', 'ID511', 25000)

Method 4- This is Python program to display the contents on my python


terminal By using fetchmany() function:
By default fetchmany() function will display only first row in the table and
it will display output in the form of tuple.
display.py

import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()
For complete python subject tutorials visit : ns lectures youtube channel

b=cur.execute('select * from employee')

print(b.fetchmany(3)) # here (3) is used to display 3 rows

con.close()

open command prompt :>>> python3 display.py

output:

[('sai', 'ID511', 25000), ('ramesh', 'ID512', 10000), ('raju', 'ID513', 40000)]

3. Python program to update data in employee table


For example, my database file is mydatabase.db and this database contains table
with name employee.
Employee table contains following information
mydatabase.db>>>
Table:employee
name empID salary
sai ID511 25000
ramesh ID512 10000
raju ID513 40000

Now I want to change name “sai” to name “ganesh” whose empID is ID511.

update.py
import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()

b=cur.execute('update employee set name="ganesh" where empID="ID511"')

con.commit()

b=cur.execute('select * from employee')


For complete python subject tutorials visit : ns lectures youtube channel

print(b.fetchmany(3))

con.close()

open command prompt :>>> python3 update.py

output:

[('ganesh', 'ID511', 25000), ('ramesh', 'ID512', 10000), ('raju', 'ID513', 40000)]

4. Python program to delete data in employee table


For example, my database file is mydatabase.db and this database contains table
with name employee.
Employee table contains following information
mydatabase.db>>>
Table:employee
name empID salary
ganesh ID511 25000
ramesh ID512 10000
raju ID513 40000

Now I want to delete complete row, whose empID is ID511

In the above table it will delete complete first row .

delete.py
import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()

b=cur.execute(' delete from employee where empID="ID511" ')

con.commit()

b=cur.execute('select * from employee')

print(b.fetchall())

con.close()
For complete python subject tutorials visit : ns lectures youtube channel

open command prompt :>>> python3 update.py

output:

[ ('ramesh', 'ID512', 10000), ('raju', 'ID513', 40000)]

5. Transaction (Begin, Commit, Rollback):


Generally the SQLite is in auto-commit mode that means SQLite automatically starts
a transaction for each command, process and commit the transaction changes
automatically to database. However, we still can disable auto-commit mode and use
the following three commands to control these transactions to maintain data
consistency and to handle database errors based on our requirements:

 BEGIN – start the transaction;


 COMMIT – commit the transaction that means all the changes saved to
database;
 ROLLBACK – rollback the complete transaction.

Transactional control commands are only used with commands INSERT, UPDATE,
and DELETE. They cannot be used while creating tables or dropping them because
these operations are automatically committed in the database.

ROLLBACK a DELETE transaction


mydatabase.db>>>
Table:employee
name empID salary
ganesh ID511 25000
ramesh ID512 10000
raju ID513 40000

rollback.py
import sqlite3

con=sqlite3.connect("mydatabase.db")

cur=con.cursor()

try:

b=cur.execute(' delete from employee where empID="ID511" ')

except:
For complete python subject tutorials visit : ns lectures youtube channel

print(“failed to delete data”)


cur.execute("ROLLBACK")

con.commit()

con.close()

open command prompt :>>>

python3 rollback.py

output:

[('ganesh', 'ID511', 25000), ('ramesh', 'ID512', 10000), ('raju', 'ID513', 40000)]

From above example, if any exception occur while deleting employee data, then it
will skip try block and it will execute except block.
Except block contains ROLLBACK, this ROLLBACK will undo the complete
transaction.
For complete python subject tutorials visit : ns lectures youtube channel

Object-relational Managers (ORMs)


An object-relational mapper (ORM) is a code library that automates the
transfer of data stored in relational database tables into objects that are
more commonly used in application code.

Why are ORMs useful?


ORMs provide a high-level abstraction upon a relational database that
allows a developer to write Python code instead of SQL to create, read,
update and delete data and schemas in their database. Developers can
use the programming language they are comfortable with to work with a
database instead of writing SQL statements or stored procedures.

What are the advantages of using ORMs?

 It might save a lot of time for whom don’t write in SQL much. So
because you use the language you already were using can speed up
the process.

 ORM makes switching between various relational databases(e.g.


from MySQL to PostgreSQL) much easier because most functions
remain same.

 Some of the queries will perform better than if you wrote them yourself.

What are the disadvantages of using ORMs?


For complete python subject tutorials visit : ns lectures youtube channel

 Because ORM is a different concept, in order to use an ORM, first you


should learn it, which learning something new and adjust can take
time.

 For whom that is good at SQL, using ORM can be less efficient and
useful. Because it won’t give you as much opportunities as you would
get when you write queries yourself.

 In general, because of the fact that ORM abstracts what is happenning


under the hood, it would lead you be less capable to erase the
problems.

 The extra conflicts can appear when setting configuration and so on.

Popular ORM Tools for Python


1. Django
Django is a great tool for building web applications rapidly.
2. web2py
web2py is an open source full-stack Python framework for building fast,
scalable, secure, and data-driven web applications.
3. SQLObject
SQLObject is an object relational manager that provides an object
interface to your database.
4. SQLAlchemy
SQLAlchemy provides persistence patterns designed for efficient and
high-performing database access.

SQLAlchemy
SQLAlchemy is a popular Object Relational Mapper (ORM) library for
Python, that provides a set of high-level APIs to interact with relational
databases such as PostgreSQL, MySQL, and SQLite. It allows
developers to interact with databases in a way that's more Pythonic and
abstracts the underlying SQL queries. This can help reduce the amount
of code that needs to be written and make it easier to maintain the
codebase.

With SQLAlchemy, you can define the structure of your database tables
using Python classes, and then use these classes to perform CRUD
(Create, Read, Update, Delete) operations on the data stored in the
For complete python subject tutorials visit : ns lectures youtube channel

tables. The ORM takes care of converting the Python operations into
SQL statements that can be executed by the database.

SQLAlchemy also provides a powerful and flexible SQL expression


language that can be used to build complex queries, and supports
transactions and other advanced database features.

Overall, SQLAlchemy is a popular choice for developers who want to


interact with relational databases in a more Pythonic way, and provides
a good balance between abstraction and control over the underlying
SQL.

SQLAlchemy provides more flexibility in


issuing raw sql "substantiate this statement”.
Yes, SQLAlchemy provides more flexibility in issuing raw SQL compared
to other Object Relational Mapping (ORM) libraries. With SQLAlchemy,
you have the option to use either the ORM API or raw SQL to interact
with your database. The ORM API provides a convenient and flexible
way to interact with the database, but it may not always provide the full
range of capabilities and performance you need for complex queries or
data manipulation tasks.

In such cases, you can issue raw SQL statements directly to the
database using SQLAlchemy's text method. This gives you complete
control over the SQL statements you execute and allows you to take
advantage of the full range of SQL functionality and performance.
Additionally, you can also use the SQLAlchemy ORM API to build your
raw SQL statements, giving you the best of both worlds - the
convenience and ease of use of the ORM API, combined with the power
and flexibility of raw SQL.

Overall, the ability to issue raw SQL statements, combined with the
flexibility and ease of use provided by the ORM API, make SQLAlchemy
a highly flexible and powerful tool for working with databases.
For complete python subject tutorials visit : ns lectures youtube channel

Here's a simple example to insert data into a database using SQLAlchemy


in Python:

1. Start by importing the required modules:

from sqlalchemy import create_engine, Column, Integer, String


from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

2. Create an engine to connect to the database:

engine = create_engine('sqlite:///mydatabase.db')

Here, the create_engine function creates an engine that will connect to


an SQLite database in a file named mydatabase.db.

3. Define a base for declarative models:

Base = declarative_base()

4. Define a model for the table you want to insert data into:

class Person(Base):
__tablename__ = 'person'
id = Column(Integer, primary_key=True)
name = Column(String)
age = Column(Integer)

5. Create the table in the database:

Base.metadata.create_all(engine)

6. Create a session to manage the connection to the database:

Session = sessionmaker(bind=engine)
session = Session()

7. Create a new object of the model, set its attributes, and add it to the
session:

person = Person(name='John Doe', age=30)


For complete python subject tutorials visit : ns lectures youtube channel

session.add(person)

8. Commit the changes to the database:

session.commit()

Here is an example program that creates a


database of students' details using SQLAlchemy:
from sqlalchemy import create_engine, Column, Integer, String

from sqlalchemy.orm import sessionmaker

from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Student(Base):

__tablename__ = 'students'

id = Column(Integer, primary_key=True)

name = Column(String)

age = Column(Integer)

branch = Column(String)

engine = create_engine('sqlite:///students.db')

Base.metadata.create_all(engine)

Session = sessionmaker(bind=engine)

session = Session()
For complete python subject tutorials visit : ns lectures youtube channel

# Adding a student

data = Student(name='John Doe', age=22, branch='Computer Science')

session.add(data)

session.commit()

# Querying the students

s = session.query(Student).all()

for student in s:

print(student.id, student.name, student.age, student.branch)

# Updating a student

update = session.query(Student).filter(Student.name == 'John Doe').first()

update.age = 23

session.commit()

# Deleting a student

studentdel = session.query(Student).filter(Student.name == 'John


Doe').first()

session.delete(studentdel)

session.commit()
UN IT-5
lenportant Guesbom

method and
Various
uhat is Cunot objedt 1
ploin
O
atbutay d Cursor objeet oire
desrribe
a onstnuctor st ond
whatehat do you menb onverting t o
dernt

Constaurtors
d fu
Norous

dota type and Doa


pesiternt Straget
Stole
Stabe the nead

Corenerd
Stabernurks ed o (oebin,uin
Th SQL
and dopping ata bole

SLANehmy ORM
deta obout PyThon

Cose Study o
bpleyaele datsbase
wiha
aabde,inlert
t» (ieate
wre a prtrn Sit +he databee
ard dhsglo data
USed in
Coosteins
Splain Vori and

elationy
le (veaiq Connectm
databade
reate
Bplan +he Stepsto
what ove exteptons2

in Pythm ond
ad and

Splan ak OPM
orut (onnertioo objet methods
( Espla
Explan SeL objet Ovm with eamp

what mods tbus ?


DG APT

Dikau follwing (ornrmny ued luny methods:


offsetr, O AArby
( wr pmgrarny
rmoQ4) patge SQL SQl:k|
N

what is oRM u - A. prgr


Yom

(Teang
in Datobose)
a are URD openatim

Cord (vret, updeb, yero, delek

6) planblo De-APT mdy 2


rndle Abate ( onnect) P paud, host
onneetion ohets ( ensructom datobose

SQLAD previds more in isuing

Ya
SQL" SStortioate ts Stahrant

plan rmal dbt l mona4eY

You might also like