Python Complete Material Notes by Ns
Python Complete Material Notes by Ns
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
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
Creating Variables
Example program:
x=5
y = "nagendra"
print(x)
print(y)
output:
Nagendra
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:
output:
output is : Nagendra
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
Example:
#This is a comment
print("Hello, World!")
Example:
Python does not really have a syntax for multi line comments.
Example:
#This is a comment
#written in
For complete python tutorials click here : ns lectures youtube channel
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(‘ ‘ ‘)
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:
• int
• float
• complex
Int type:
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:
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
output:
2
3j
Complex() function:
it is used to convert number or string to complex number
program:
a=complex(1,2)
print(a)
print(“real part is :”, a.real)
output:
1+2j
Real part is :1
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:
output:
True
<class-‘bool’>
Example:
Print(3==9)
Output:
False
Strings type:
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 ,
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
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.
Program:
print("Btech")
print("students")
output:
Btech
students
program:
print("students")
output:
Btech
students
For complete python tutorials click here : ns lectures youtube channel
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
as To create an alias
For complete python tutorials click here : ns lectures youtube channel
finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not
or A logical operator
Following are some of the types that are not supported by python
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
output:
9789280
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.
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
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.
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.
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
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:
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
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
1. if statement
2. if-else
3. if-elif-else
4. nested if-else
1. If statement :
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
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
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.
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:
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.
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
output:
Output 1
Enter a number: 43
Odd number
Output 2
Enter a number: 18
Even number
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
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
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
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
Loops statements are used when we need to run same code again and
again, each time with a different value.
1. While Loop
2. For Loop
statements
Output :-
0
1
2
3
4
x=1
while (x == 1):
print(‘hello’)
Output :-
hello
hello
hello
—–
—–
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!!!!!!!!!
statements
Output :-
1
2
3
4
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:
Program:
num = 5
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
Program:
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
• 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:
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
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.
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()
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
Example program:
#declaring a function
def fun():
print("my name is nagendra")
# call a function
fun()
Example program:
#declaring a function
def fun():
print("my name is nagendra")
fun()
fun()
fun()
output:
my name is nagendra
my name is nagendra
my name is nagendra
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)
output:
For complete python tutorials click here : ns lectures youtube channel
Program2:
# Defining a function
fun ( "nagendra")
fun ( "sudeer")
fun ( "ganesh")
output:
Program:
def name():
print(name())
output:
For complete python tutorials click here : ns lectures youtube channel
my name is nagendra
None
Program2
def name():
print(name())
output:
my name is nagendra
Program3
def name():
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.
1. Positional Arguments:
data(“bhavani”, 10)
data(10, “bhavani)
For complete python tutorials click here : ns lectures youtube channel
output:
Note: If you try to pass more arguments, you will get an error.
Program:
data(“bhavani”, 10,”hyderabad”)
output:
error
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
Program1:
# 3 positional arguments
student(rollno=92,section=”B”,name='anurag')
output:
3. Default argument:
Program:
student('anurag', 92 )
output:
Program2:
output:
Note:
4. Variable-length arguments
def
students(*names):
print(names)
print(len(names))
print(type(names))
students("vinny","shruthi","rishitha","rahul")
Output:
4
<class 'tuple'>
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.
Program:
def students(**names):
print(names)
print(len(names))
print(type(names))
students(name="shruthi",rollno=24)
output:
2
<class 'dict'>
For complete python tutorials click here : ns lectures youtube channel
def fun():
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.
def fun():
print(a)
output:
For complete python tutorials click here : ns lectures youtube channel
hello
lambda function
A lambda function can take any number of arguments, but can only have
one expression.
Syntax
lambda arguments : expression
Example
x = lambda a: a + 10
print(x(5))
output:
15
For complete python tutorials click here : ns lectures youtube channel
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():
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
if n == 1:
return 1
else:
return n * factorial(n-1)
n=5
output:
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’>
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
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
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
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the position of where it was
fou
index() Searches the string for a specified value and returns the position of where it was
fo
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
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
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
rindex() Searches the string for a specified value and returns the
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
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.
Program:
print(type(a))
print(len(a))
output:
<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”
Program:
print(a)
output:
Unordered
Program:
a = {1,2,3,4}
print(a)
output:
{ 3,2,1,4}
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.
Program:
print(a)
output:
Program:
print(a)
output:
Access Items
Program:
for x in a:
print(x)
output:
apple
cherry
banana
Program:
print("banana" in a)
output:
True
Set Methods
Python has a set of built-in methods that you can use on sets.
Method Description
difference_update() Removes the items in this set that are also included
intersection_update() Removes the items in this set that are not present
another
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.
add() method:
Program:
a = {"apple", "banana", "cherry"}
a.add("orange")
print(a)
output:
{'cherry', 'banana', 'apple', 'orange'}
To add items from another set into the current set, use
the update() method.
update() method:
Program:
a.update(b)
print(a)
output:
Program:
a.update(b)
print(a)
output:
Remove Item:
remove() method:
Program
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.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
Program:
del a
print(a)
output:
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.
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
b = {1, 2, 3}
c = a.union(b)
print(c)
output:
update()method:
program:
a = {"a", "b" , "c"}
b = {1, 2, 3}
a.update(b)
print(a)
output:
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:
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.intersection_update(b)
print(a)
output:
{'apple'}
symmetric_difference() method:
Program:
c = a.symmetric_difference(b)
print(c)
output:
symmetric_difference_update() method:
Program:
a.symmetric_difference_update(b)
print(a)
output:
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}
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:
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.
program:
a["name"]="rajesh"
print(a)
output:
Program:
a["name2"]="rajesh"
print(a)
output:
You can change the value of a specific item by referring to its key name:
Program:
output:
Program:
if "name" in a:
output:
Update Dictionary
The update() method will update the dictionary with the items from the given
argument.
update() method:
Program:
a.update({"city": "hyderabad"})
print(a)
output:
Removing Items
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.pop("name")
print(a)
output:
popitem() method:
Program:
a.popitem()
print(a)
output:
del keyword:
The del keyword removes the item with the specified key name:
Program:
del a["name"]
print(a)
output:
Program:
del a
print(a)
output:
error
clear() method:
Program:
a.clear()
print(a)
output:
{ }
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.
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
Program:
for x in a:
print(a[x])
output:
ramya
18
INDIA
Copy a Dictionary
There are ways to make a copy, one way is to use the built-in Dictionary
method copy().
Copy( ) method:
Program:
b = a.copy()
print(b)
For complete python tutorials click here : ns lectures youtube channel
output:
dict( ) method:
Program:
b = dict(a)
print(b)
output:
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}}
Create two dictionaries, then create one dictionary that will contain the other
two dictionaries:
PROGRAM:
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
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
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
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:
x = slice(3, 5)
For complete python tutorials click here : ns lectures youtube channel
print(a[
x])
output:
('d', 'e')
3) Xrange():
xrange() – This function returns the generator object that can be used
todisplay numbers only by looping.
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(
).
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.
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.
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
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
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:
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).
"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
Method Description
The key function for working with files in Python is the open() function.
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".
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")
f = open("file.txt", "r")
file.txt
For complete python subject tutorials visit : ns lectures youtube channel
Example
f = open("C:/Desktop/file.txt", "r")
print(f.read())
f.close()
output:
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
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
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:
By calling readline() two times, you can read first two lines:
Example
f = open("C:/Desktop/file.txt", "r")
f.close()
output:
Hel
By looping through the lines of the file, you can read the whole file, line
by line:
Example
for x in f:
print (x)
f.close()
output:
It is a good practice to always close the file when you are done with it.
readlines() method:
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:
Assume we have the following file, located in the Desktop, let file name
is file.txt , let file contains text given below:
file.txt
f.close()
f.close()
output:
For above example, use “a” mode to add text in my file named file.txt.
Program:
f.close()
f.close()
output:
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
Program:
import os
os.remove("file.txt")
program:
a=open("E:/sai.txt","w")
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.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
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:
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
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.
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( )
program:
a=open("sai.txt","r+")
a.seek(6)
print(a.readline())
output:
ramesh
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
In a computer, a file system is the way in which files are named and where
they are placed logically for storage and retrieval.
import os
Now that you’ve imported the module, you can start using its various
functions.
output:
D:\ Python\
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
Renaming a directory
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
$ 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:
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.
$ 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!
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
>>>
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
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
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.
Example:
For complete python subject tutorials visit : ns lectures youtube channel
Import marshal
a=[“nagendra”,10,”btech”]
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.
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
print (list(a.keys()))
output: ['name', 'age', 'marks']
print (list(a.values()))
output: ['Ajay', 25, 75]
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
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
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:
OUTPUT:
error , b value cant be 0
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:
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.
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
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:
Output:
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:
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:
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
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.
b =0
print("The value of a / b is : ")
assertb !=0
print(a /b)
Output :
The value of a / b is :
AssertionError:
a =4
b =0
print(a /b)
Output:
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
Output:
Traceback (most recent call last):
File "expdemo.py", line 3, inprint(a/b)ZeroDivisionError: division by zero
Output:
Enter a number : 23
Enter a number : abc
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'
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:
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).
•
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
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
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
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
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
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
Command -
dir( builtins )
Output:
The built-in namespace creates by the Python interpreter when its starts
up. These are terminated when Python interpreter terminates.
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.
if n%2==0:
else:
num=int(input("enter no:"))
print(evenodd(num))
For complete python subject tutorials visit : ns lectures youtube channel
name Attribute
Example:
Output:
'math'
Example:
>>> name
Output:
' main '
When we run any Python script (i.e. a module), its name attribute
is also set to main
doc Attribute
Example:
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
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
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.
print(dir())
output:
[' builtins__', ' cached__', ' doc__', ' file ', ' loader '
' name ','__package ', ' spec ']
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']
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
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”)
Syntax:
import package_name.module_name
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
UNIT-3
Regular Expressions:
Multithreaded programming:
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 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
x = re.search("^My.*nagendra$",a)
if x:
else:
print("No match")
For complete python subject tutorials visit : ns lectures youtube channel
output:
Example-2:
import re
s = 'my name is nagendra'
print(re.search('nagendra', s))
output:
Function Description
split Returns a list where the string has been split at each
match
Example-1:
import re
x = re.match("my", a)
print(x)
Output:
Example-2:
import re
x = re.match("The", a)
print(x)
Output:
None
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
Example-1:
import re
print(x)
Output:
Example-2:
import re
print(x)
Output:
Example-1:
import re
x = re.findall("My", a)
print(x)
Output:
['my', 'my']
Example-1:
import re
x = re.split("nagendra", a)
print(x)
Output:
Example-1:
import re
x = re.sub("nagendra","rahul", a)
print(x)
Output:
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.
[ ] (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
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
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
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
mn 1 match
man 1 match
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
man 1 match
maaan 1 match
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
{ } (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.
Special
Description
Sequence
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]
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 \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 ['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.
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.
Apart from the functions specified above, the threading module also provides
many classes whose objects are very useful in creating and managing threads.
Object Description
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:
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
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
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.
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
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
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:
lock = RLock()
lock.acquire()
# ...
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
c-program:
#include<stdio.h>
int main()
{
printf("Hello my name is nagendrasai, this is c program ");
return 0;
}
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
Multiprocessing module
For complete python subject tutorials visit : ns lectures youtube channel
Create a Class
Example:
Program:
class MyClass:
x=5
print(x)
output:
program2:
class Person:
def fun(self,name,age):
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
OUTPUT:
Unit-4
GUI PROGRAMMING & WEB PROGRAMMING
GUI PROGRAMMING:
1. TKINTER, tcl and tk
5. Other modules :
Tk interface Extension (Tix), Python Mega Widgets (PMW),
wxWidgets & wxPython, GTK+, PyGTK, EasyGUI
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
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:
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.
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 )
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 )
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
We can also associate a method or function with a button which is called when
the button is pressed.
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")
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
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.
Syntax
w = checkbutton(master, options)
Example:
tkcb.py
a.mainloop()
Output:
Command prompt:
python3 tkcb.py
For complete python subject tutorials visit : ns lectures youtube channel
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.
Syntax
w = Radiobutton(top, options)
For complete python subject tutorials visit : ns lectures youtube channel
Example:
tkrb.py
a.mainloop()
Output:
Command prompt:
python3 tkrb.py
For complete python subject tutorials visit : ns lectures youtube channel
Next →← Prev
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.
Syntax
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.
Syntax
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
Syntax
For complete python subject tutorials visit : ns lectures youtube channel
w = Frame(parent, options)
Example:
tkf.py
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
The user can choose one or more items from the list depending upon the
configuration.
w = Listbox(parent, options)
Example:
tkl.py
from tkinter import *
a=Tk()
a.title("welcome")
a.geometry("400x300")
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.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
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.
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.pack()
>>>a.mainloop()
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.
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:
After installing PMW, you can import it in your Python script using the
following line:
import Pmw
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.
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:
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".
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
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.
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:
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.
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
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.
Student.py
from tkinter import *
For complete python subject tutorials visit : ns lectures youtube channel
a=Tk()
a.geometry("1280x720")
n=Label(a,text="name:")
e1=Entry(a)
e1.grid(row=0, column=1)
p=Label(a,text="rollno:")
e2=Entry(a)
e2.grid(row=1, column=1)
p=Label(a,text="branch:")
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.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
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.grid(row=0, column=2)
a.mainloop()
output:
command prompt:
python3 gm.py
For complete python subject tutorials visit : ns lectures youtube channel
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.
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
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.
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.
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 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
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
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.
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.
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.
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
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 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.
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.
ht.py
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd.serve_forever()
For complete python subject tutorials visit : ns lectures youtube channel
output:
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
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
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
url="https://www.youtube.com/@NSlectures/resource?key1=value1&key2=val
ue2#nagendra"
p = urlparse(url)
print(p.scheme) # "https"
print(p.query) # "key1=value1&key2=value2"
print(p.fragment) # "nagendra"
output:
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
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
url = urlunparse(url_parts)
print(url)
output:
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.
Example:
Jn.py
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
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:
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.
cookie = SimpleCookie()
cookie['username'] = 'johndoe'
cookie['username']['expires'] = 3600
print(cookie)
For complete python subject tutorials visit : ns lectures youtube channel
Sessions:
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("</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
8. Database Exceptions
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
13. SQLAlchemy
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.
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
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
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:
What is SQL?
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.
Sr. Basis of
No. Comparison Open Source Database Commercial Database
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
Serverless
Self-Contained
Zero-Configuration
Transactional
Single-Database
2. Python ecosystem is very rich and it is easy to use tools for datascience.
5. Writing Python code to access database API commands which refers to as DB-
API.
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
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).
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
Cursor methods
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
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
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
);
5. Dropping Constraint
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.
Import mysql.connector
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.
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.
Database Exceptions
The module should make all error information available through these
exceptions or subclasses thereof:
Warning
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
InternalError
ProgrammingError
NotSupportedError
OFFSET in SQL is generally used with the ORDER BY clause with a value
greater than or equal to zero.
SELECT column_names
FROM table_name
ORDER BY column_names
OFFSET n ROWS //n is the number of rows to be excluded.
Employees table:
Query:
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')
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.
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,
UPDATE
The WHERE clause must be included, else all records in the table will
be updated.
EXAMPLE:
DELETE
EXAMPLE:
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.
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.
mydatabase.db>>>
Table:employee
name empID salary
sai ID511 25000
ramesh ID512 10000
raju ID513 40000
import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
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
output:
name= sai
empID= ID511
salary= 25000
name= ramesh
empID= ID512
salary= 10000
name= raju
empID= ID513
salary= 40000
import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
print(b.fetchall())
con.close()
output:
For complete python subject tutorials visit : ns lectures youtube channel
import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
print(b.fetchone())
con.close()
output:
import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
For complete python subject tutorials visit : ns lectures youtube channel
con.close()
output:
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()
con.commit()
print(b.fetchmany(3))
con.close()
output:
delete.py
import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
con.commit()
print(b.fetchall())
con.close()
For complete python subject tutorials visit : ns lectures youtube channel
output:
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.py
import sqlite3
con=sqlite3.connect("mydatabase.db")
cur=con.cursor()
try:
except:
For complete python subject tutorials visit : ns lectures youtube channel
con.commit()
con.close()
python3 rollback.py
output:
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
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.
Some of the queries will perform better than if you wrote them yourself.
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.
The extra conflicts can appear when setting configuration and so on.
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.
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
engine = create_engine('sqlite:///mydatabase.db')
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)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
7. Create a new object of the model, set its attributes, and add it to the
session:
session.add(person)
session.commit()
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
session.add(data)
session.commit()
s = session.query(Student).all()
for student in s:
# Updating a student
update.age = 23
session.commit()
# Deleting a student
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
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
(Teang
in Datobose)
a are URD openatim
Ya
SQL" SStortioate ts Stahrant