0% found this document useful (0 votes)
75 views39 pages

E-Book Python Programming

The document provides an overview of the Python programming language. It discusses that Python is an interpreted, object-oriented, cross-platform programming language that is easy to use and open source. It then covers topics such as Python properties, usages, installation, how to execute programs, inner execution, tokens including keywords, identifiers, literals and operators, conditional statements, loops, and switch case statements.

Uploaded by

Mouli Maiti
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
75 views39 pages

E-Book Python Programming

The document provides an overview of the Python programming language. It discusses that Python is an interpreted, object-oriented, cross-platform programming language that is easy to use and open source. It then covers topics such as Python properties, usages, installation, how to execute programs, inner execution, tokens including keywords, identifiers, literals and operators, conditional statements, loops, and switch case statements.

Uploaded by

Mouli Maiti
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 39

qwertyuiopasdfghjklzxcvbnmqwertyui

opasdfghjklzxcvbnmqwertyuiopasdfgh
jklzxcvbnmqwertyuiopasdfghjklzxcvb
nmqwertyuiopasdfghjklzxcvbnmqwer
Python
tyuiopasdfghjklzxcvbnmqwertyuiopas
dfghjklzxcvbnmqwertyuiopasdfghjklzx
[Pick the date]

ADMIN

cvbnmqwertyuiopasdfghjklzxcvbnmq
wertyuiopasdfghjklzxcvbnmqwertyuio
pasdfghjklzxcvbnmqwertyuiopasdfghj
klzxcvbnmqwertyuiopasdfghjklzxcvbn
mqwertyuiopasdfghjklzxcvbnmqwerty
uiopasdfghjklzxcvbnmqwertyuiopasdf
ghjklzxcvbnmqwertyuiopasdfghjklzxc
vbnmqwertyuiopasdfghjklzxcvbnmrty
uiopasdfghjklzxcvbnmqwertyuiopasdf
ghjklzxcvbnmqwertyuiopasdfghjklzxc
INTRODUCTION
Python is the marvellous creature of Guido Van Rossum, a Dutch computer scientist and mathematician
who decided to gift the world with a project he was playing around with over Christmas 1989. BBC
comedy series name ‘Monty Python’s Flying Circus’ from 1970.. He though he needed a unique name, so
just gave the name
Python program is typically one-fifth to one-third the size of equivalent Java or C++ code.
Google, YouTube, Dropbox, Yahoo, Zope Corporation, Industrial Light & Magic,Walt Disney Feature
Animation, Pixar, NASA, NSA, Red Hat, Nokia, IBM, Netflix, Yelp,Intel, Cisco, HP, Qualcomm, and
JPMorgan Chase, just to name a few.
Python is fast enough for our site and allows us to produce maintainable features in record times,
with a minimum of developers.
By
Cuong Do, YouTube.com

Properties of Python
Python is an interpreted language. An interpreted language is a programming language for which most
of its implementations execute instructions directly and freely, without previously compiling a program
into machine-language instructions. The interpreter executes the program directly, translating each
statement into a sequence of one or more subroutines already compiled into machine code.
Python is Object Oriented Programming language. OOP is designed in such a way that one should focus
on an object while programming and not the procedure. An object can be anything that we see around us.
It can be a human (that has some properties like - name, address, DOB and so on) or a car( that has some
properties like – color, type, brand). Object oriented programming brings programming close to real life,
as we are always dealing with an object, performing operations on it, using it's methods and variables etc.
Python is Cross platform or Platform independent. Python first compiles the .py file to an intermediate
file named .pyc called byte code, it is the low level platform independent code. Byte code is interpreted
by PVM(Python Virtual Machine) to machine code
Python is Easy and Open source. An open source programming language means it free to use and the
source code can also be changed as per anyone’s need.

Usages of Python
Python can be used to create Web based application, GUI based Application, Console based application,
Games etc. Python is mainly used in the field of Data analysis, Machine learning, Image processing, Data
science etc

Installing Python
• Install either python 3.7 (latest version)
• Or you can also install Anaconda

• Anaconda is a free open source distribution of the Python and R programming languages for
large-scale data processing, predictive analytics, and scientific computing, that aims to simplify
package management and deployment

We normally use python 3.7, Anaconda is mainly used for Data Analysis and Machine learning and is a
heavy software so generally we avoid to use this. During installation of Python 3.7, you have to check
the add python to path checkbox. If not then after installation you have to set the path for python in

2
your computer. For this you have to go to my computer, then environmental variable, advanced path
setting then in the path variable put the python path.

How to Execute and Run a Python program


1. Interactive mode ie in command prompt

2. Script mode ie create in any editor and save it with .py, then open command prompt and type python
a.py

3. Using IDE. A default IDE in python is IDLE

4. Using jupyter notebook or Spyder of Anaconda (if installed)

Inner Execution of Python Program


Python is both an interpreted and a compiled language. Python first compiles your source code (.py file)
into a format known as byte code, byte code is a lower-level, and platform-independent code. The byte
code (.pyc file) is loaded into the Python runtime and interpreted by a Python Virtual Machine. The
PVM is always present as part of the Python system , and is the component that truly runs your scripts.
Normally, you don't need to do anything and you shouldn't bother, because "Python" is doing the thinking
for you, i.e. it takes the necessary steps automatically to compile the code. Technically, it's just the last
step of what is called the Python interpreter. Each time an interpreted program is run, the interpreter
must convert source code into machine code and also pull in the runtime libraries.

3
Tokens in Python
Tokens can be defined as a punctuator mark, reserved words and each individual word in a statement.
Token is the smallest unit inside the given program.
There are following tokens in Python:

o Keywords.

o Identifiers

o Literals.

o Operators.

Keywords
Keywords are special reserved words which convey a special meaning to the compiler/interpreter. These
words cannot be used as a variable name. A list of Python keywords has been given below.

True False None and as


asset Def class continue break
else finally elif del except
global For if from import
raise Try or return pass
nonlocal In not is lambda

Identifiers
Identifiers are the names given to the fundamental building blocks in a program. These can be variables
,class ,object ,functions , lists , dictionaries etc.

Rules defined for naming Identifiers.


I. An identifier is a long sequence of characters and numbers.
II. No special character except underscore ( _ ) can be used as an identifier.
III. Keyword should not be used as an identifier name.
IV. Python is case sensitive. So using case is significant.
V. First character of an identifier can be character, underscore ( _ ) but not digit.

Python Literals
Literals can be defined as a data that is given in a variable or constant.Like String literals, numeric
literals, Boolean Literals
“python” or ‘python’
A=8

4
Operators In Python –
1. Arithmetic Operators.

2. Relational Operators.

3. Assignment Operators.

4. Logical Operators.

5. Membership Operators.

6. Identity Operators.

7. Bitwise Operators.

All the operators are same as C or Java or Nay other languages except membership operator and Identity
operator which is new to Python

Note- there is no increment/decrement operator in Python

Membership operator
Operator Description Example

in Evaluates to true if it finds a x in y, here in results in a 1 if x is


variable in the specified sequence a member of sequence y.
and false otherwise.

not in Evaluates to true if it does not x not in y, here not in results in a


finds a variable in the specified 1 if x is not a member of
sequence and false otherwise. sequence y.

Identity Operator
Is Returns true if identity of two operands are same, else false

is not Returns true if identity of two operands are not same, else false.

Conditional Statements in Python -


Perhaps the most well-known statement type is the if statement. If is used if a statement is correct, if not
then it will execute else part. If there are more than one condition to satisfy then we have to use elif to
check for other condition
For example:

5
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero’)
... elif x == 0:
... print('Zero’)
... elif x == 1:
... print('Single’)
... else:
... print('More’)
... More

Switch Case –
1. Compiler generates a jump table for switch case statement
2. The switch variable/expression is evaluated once
3. Switch statement looks up the evaluated variable/expression in the jump table and directly decides
which code block to execute.
4. If no match is found, then the code under default case is executed

argument = int(input('Enter the 1st number'))

switcher = {

1: "January",

2: "February",

3: "March",

4: "April",

5: "May",

6: "June",

7: "July",

8: "August",

9: "September",

10: "October",

11: "November",

12: "December"

6
}

print(switcher.get(argument, "Invalid month"))

Loops in Python-
Two type of Loops are there in python
1. While loop
2. For loop

While loop – the logic is same as C, the syntax is


i =0 # initialization

while i<=10: #condition

print(i) # print

i=i+1 # increment

For Loop -
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always
iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define
both the iteration step and halting condition (asC), Python’s for statement iterates over the items of any
sequence (alistorastring), in the order that they appear in the sequence.

>>> words = ['cat', 'window', 'defenestrate’] # Measure some strings:


>>> for w in words:
... print(w, len(w))
... cat 3
window 6
defenestrate 12

If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy.
It generates arithmetic progressions:

It generates arithmetic progressions:


>>> for i in range(5):
... print(i)
... 0
1
2
3
4

range(5, 10)
5 through 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70

7
>>> a = ['Mary', 'had', 'a', 'little', 'lamb’]
>>> for i in range(len(a)):
... print(i, a[i])

... 0 Mary
1 had
2a
3 little
4 lamb

break and continue Statements, and else Clauses on


Loops
The break statement, like in C, breaks out of the smallest enclosing for or while loop. Loop statements
may have an else clause; it is executed when the loop terminates through exhaustion of the list(with for)
or when the condition becomes false (with while), but not when the loop is terminated by a break
statement.
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number’)

... 2 is a prime number


3 is a prime number

4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

Functions in Python:-
The keyword def introduces a function definition. It must be followed by the function name and the
parenthesized list of formal parameters. The statements that form the body of the function start at the next
line, and must be indented. The first statement of the function body can optionally be a string literal; this
string literal is the function’s documentation string, or docstring. (More about docstrings can be found in

8
the section Documentation Strings.) There are tools which use doc strings to automatically produce online
or printed documentation, or to let the user interactively browse through code.

>>> def fib(n): # write Fibonacci series up to n


... """Print a Fibonacci series up to n."""
... a, b = 0, 1
... while a < n:
... print(a, end=' ‘)
... a, b = b, a+b
... print()
... >>> fib(2000) # Now call the function we just defined:

... 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

Parameters and Arguments -


Parameters are the input variables given to a function, it is normally defined during definition of the
function. A function may have with parameters or without parameters. Arguments are the actual values
passed to a function during function calling.

Variable Function Arguments


Up until now functions had fixed number of arguments. In Python there are other ways to define a
function which can take variable number of arguments.

Python Default Argument:-


The most useful form is to specify a default value for one or more arguments. This creates a function
that can be called with fewer arguments than it is defined to allow. If u have not pass any argument it
will automatically accept the default value. If u pass, it will take your value

Python Keyword Arguments


When we call a function with some values, these values get assigned to the arguments according to their
position
As an example for both the above, look below
def printdef( name, age = 35 ):
print("Name: ", name)
print("Age ", age)
printdef( age=50, name="mou" )
printdef( name="mou" )
where if you don’t pass age during function call it will automatically take 35 as its default age. This is
what is default argument
in the above example, you can pass age before passing name by writing age=something. This is what is
called Keyword argument.

Python Arbitrary Arguments


Sometimes, we do not know in advance the number of arguments that will be passed into a
function.Python allows us to handle this kind of situation through function calls with arbitrary number of

9
arguments. In the function definition we use an asterisk (*) before the parameter name to denote this
kind of argument. Here is an example.

def greet(*names):
for name in names:
print("Hello",name)
greet("Mousita","Abhisek","Bijoy","Namita")

Lambda Expression:-
Small anonymous functions can be created with the lambda keyword. This function returns the sum of its
two arguments:

lambda a, b: a+b

Lambda functions can be used wherever function objects are required. They are syntactically restricted to
a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like
nested function definitions, lambda functions can reference variables from the containing scope. Lambda
forms can take any number of arguments but return just one value in the form of an expression. They
cannot contain commands or multiple expressions.

Def f(x): return X**2


Print f(8)

Output 64
G=lambda x: x**2
Print (G)

Output 64

The above example uses a lambda expression to return a function.


Another use is to pass a small function as an argument.
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four’)]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

Difference between normal function and Lambda


function:-
Lets see an example first
# Python code to illustrate cube of a number
def cube(y):
return y*y*y;
g = lambda x: x*x*x 10
print(g(7))
 Without using Lambda : Here, both of them returns the cube of a given number. But,
while using def, we needed to define a function with a name cube and needed to pass a
value to it. After execution, we also needed to return the result from where the function
was called using the return keyword.

 Using Lambda : Lambda definition does not include a “return” statement, it always
contains an expression which is returned. We can also put a lambda definition anywhere
a function is expected, and we don’t have to assign it to a variable at all. This is the
simplicity of lambda functions.

The Module :-
Python has a way to put definitions in a file and use them in a script or in an interactive instance of the
interpreter. Such a file is called a module; definitions from a module can be imported into other modules
or into the main module (the collection of variables that you have access to in a script executed at the top
level and in calculator mode).
A module is a file containing Python definitions and statements. The file name is the module name with
the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the
global variable __name__. use your favourite text editor to create a file called fibo.py in the current
directory with the following contents:

def fib(n):
a, b = 0, 1
while b < n:
print(b, end=' ')
a, b = b, a+b
print()
def add(a,b):

def add(a,b):
c=a+b
return c

Now enter the Python interpreter and import this module with the following command
>>> import fibo
>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.add(100,100)
200
>>> from fibo import fib - > only import fib function from fibo file
>>>from fibo import * -> imports all the functions inside fibo file

11
Python Numbers
There are three numeric types in Python:
 int
 float
 complex

Variables of numeric types are created when you assign a value to them:
Eg
x = 1 # int y = 2.8 # float z = 1j # complex

Python Strings
String literals can be enclosed by either double or single quotes, although single quotes are more
commonly used. Backslash escapes work the usual way within both single and double quoted literals --
e.g. \n \' \". A double quoted string literal can contain single quotes without any fuss (e.g. "I didn't do it")
and likewise single quoted string can contain double quotes. A string literal can span multiple lines, but
there must be a backslash \ at the end of each line to escape the newline. String literals inside triple
quotes, """ or ''', can span multiple lines of text.

Python strings are "immutable" which means they cannot be changed after they are created (Java strings
also use this immutable style). Since strings can't be changed, we construct *new* strings as we go to
represent computed values. So for example the expression ('hello' + 'there') takes in the 2 strings 'hello'
and 'there' and builds a new string 'hellothere'.

Characters in a string can be accessed using the standard [ ] syntax, and like Java and C++, Python uses
zero-based indexing, so if s is 'hello' s[1] is 'e'. If the index is out of bounds for the string, Python raises an
error. The Python style (unlike Perl) is to halt if it can't tell what to do, rather than just make up a default
value. The handy "slice" syntax (below) also works to extract any substring from a string. The len(string)
function returns the length of a string. The [ ] syntax and the len() function actually work on any sequence
type -- strings, lists, etc.. Python tries to make its operations work consistently across different types.
Python newbie gotcha: don't use "len" as a variable name to avoid blocking out the len() function. The '+'
operator can concatenate two strings. Notice in the code below that variables are not pre-declared -- just
assign to them and go.

s = 'hi'

print (s[1]) ## i

print (len(s) ) ## 2

String Methods
(prints) + ' there' ## hi there
Here are some of the most common string methods. A method is like a function, but it runs "on" an
object. If the variable s is a string, then the code s.lower() runs the lower() method on that string object
and returns the result (this idea of a method running on an object is one of the basic ideas that make up
Object Oriented Programming, OOP). Here are some of the most common string methods:

 s.lower(), s.upper() -- returns the lowercase or uppercase version of the string


 s.strip() -- returns a string with whitespace removed from the start and end

12
 s.isalpha()/s.isdigit()/s.isspace()... -- tests if all the string chars are in the various character
classes
 s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given
other string
 s.find('other') -- searches for the given other string (not a regular expression) within s, and
returns the first index where it begins or -1 if not found
 s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced
by 'new'
 s.split('delim') -- returns a list of substrings separated by the given delimiter. The
delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb',
'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace
chars.
 s.join(list) -- opposite of split(), joins the elements in the given list together using the
string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

String Slices
The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings and lists. The slice
s[start:end] is the elements beginning at start and extending up to but not including end. Suppose we have
s = "Hello"
s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4

s[1:] is 'ello' -- omitting either index defaults to the start or end of the string

s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing (this is the pythonic way to
copy a sequence like a string or list)

s[1:100] is 'ello' -- an index that is too big is truncated down to the string length

The standard zero-based index numbers give easy access to chars near the start of the string. As an
alternative, Python uses negative numbers to give easy access to the chars at the end of the string: s[-1] is
the last char 'o', s[-2] is 'l' the next-to-last char, and so on. Negative index numbers count back from the
end of the string:
 s[-1] is 'o' -- last char (1st from the end)
 s[-4] is 'e' -- 4th from the end
 s[:-3] is 'He' -- going up to but not including the last 3 chars.
 s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string.

It is a neat truism of slices that for any index n, s[:n] + s[n:] == s. This works even for n negative or out of
bounds. Or put another way s[:n] and s[n:] always partition the string into two string parts, conserving
all the characters. As we'll see in the list section later, slices work with lists too.

Python Lists:-
Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists
work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first
element at index 0.

13
Eg
colors = ['red', 'blue', 'green'] print colors[0] ## red print colors[2] ## green print len(colors) ## 3
The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4]
yields [1, 2, 3, 4] (this is just like + with strings). The *for* construct -- for var in list -- is an easy way to
look at each element in a list (or other collection). Example below

squares = [1, 4, 9, 16]


sum = 0
for num in squares:
sum += num
print(sum) ## 30

Lists Methods:-
Here are some other common list methods.

 list.append(elem) -- adds a single element to the end of the list. Common error: does not return
the new list, just modifies the original.
 list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.
 list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar
to using extend().
 list.index(elem) -- searches for the given element from the start of the list and returns its index.
Throws a ValueError if the element does not appear (use "in" to check without a ValueError).
 list.remove(elem) -- searches for the first instance of the given element and removes it (throws
ValueError if not present)
 list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is
preferred.)
 list.reverse() -- reverses the list in place (does not return it)
 list.pop(index) -- removes and returns the element at the given index. Returns the rightmost
element if index is omitted (roughly the opposite of append()).

List Slices
Slices work on lists just as with strings, and can also be used to change sub-parts of the list.

list = ['a', 'b', 'c', 'd']

print (list[1:-1] ) ## ['b', 'c']

list[0:2] = 'z' ## replace ['a', 'b'] with ['z']


Tuples:-
print(list) ## ['z', 'c', 'd']

A tuple is a fixed size grouping of elements, such as an (x, y) co-ordinate. Tuples are like lists, except
they are immutable and do not change size (tuples are not strictly immutable since one of the contained
elements could be mutable). Tuples play a sort of "struct" role in Python -- a convenient way to pass
around a little logical, fixed size bundle of values. A function that needs to return multiple values can just
return a tuple of the values. For example, if I wanted to have a list of 3-d coordinates, the natural python
representation would be a list of tuples, where each tuple is size 3 holding one (x, y, z) group. To create a
tuple, just list the values within parenthesis separated by commas. The "empty" tuple is just an empty pair

14
of parenthesis. Accessing the elements in a tuple is just like a list -- len(), [ ], for, in, etc. all work the
same.

tuple = (1, 2, 'hi')

print len(tuple) ## 3

print tuple[2] ## hi

tuple[2] = 'bye' ## NO, tuples cannot be changed

tuple = (1, 2, 'bye') ## this works

Dictionary:-

Python's efficient key/value hash table structure is called a "dict". The contents of a dict can be written
as a series of key:value pairs within braces { }, e.g. dict = {key1:value1, key2:value2, ... }. The "empty
dict" is just an empty pair of curly braces {}.

dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
print (dict ) ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma'}
print (dict['a']) ## Simple lookup, returns 'alpha'
dict['a'] = 6 ## Put new key/value into dict
'a' in dict ## True
## print dict['z'] ## Throws KeyError
if 'z' in dict:
print (dict['z']) ## Avoid KeyError
A for
printloop on a dictionary
(dict.get('z') ) iterates
## Noneover its keys
(instead by default. The keys will appear in an arbitrary order. The
of KeyError)
methods dict.keys() and dict.values() return lists of the keys or values explicitly. There's also an items()
which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value
data in the dictionary. All of these lists can be passed to the sorted() function.

Method Description

15
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

setdefault() Returns the value of the specified key. If the key does not exist: 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

Set:-
A set is an unordered collection of items. Every element is unique (no duplicates) allowed.A set is created
by placing all the items (elements) inside curly braces {}, separated by comma or by using the built-in
function set()

Eg

16
my_set = {1, 2, 3}
print(my_set)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
S={1,2,3,4,3}
Output will be
{1,2,3,4} ->unique

Creating an empty set is a bit tricky.Empty curly braces {} will make an empty dictionary in Python. To
make a set without any elements we use the S=set() will create an empty set. Sets are mutable. But
since they are unordered, indexing have no meaning.We cannot access or change an element of set
using indexing or slicing. Set does not support it. We can add single element using the add() method
andand multiple elements using the update() method. The update() method can take tuples, lists, strings
or other sets as its argument. In all cases duplicates are not allowed

Remove and Pop:-


We can remove any elements of the set by using remove() or discard(). Similarly, we can remove and
return an item using the pop() also Set being unordered, there is no way of determining which item
will be popped. It is completely arbitrary.

List Comprehension:-
List comprehensions provide a concise way to create lists. Common applications are to make new
lists where each element is the result of some operations applied to each member of another sequence
or itterable, or to create a subsequence of those elements that satisfy a certain condition.
Example below without list comprehension
>>> squares = []

>>> for x in range(10):


... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81
Using List Comprehension
squares = [x**2 for x in range(10)]

A list comprehension consists of brackets containing an expression followed by a for clause, then
zero or more for or if clauses. The result will be a new list resulting from evaluating the expression
in the context of the for and if clauses which follow i.

Difference between different Data Structure :-


There are quite a few data structures available. The builtins data structures are: lists, tuples, dictionaries,
strings, sets and frozensets.

17
Lists, strings and tuples are ordered sequences of objects. Unlike strings that contain only characters, list
and tuples can contain any type of objects. Lists and tuples are like arrays. Tuples like strings are
immutables. Lists are mutables so they can be extended or reduced at will. Sets are mutable unordered
sequence of unique elements whereas frozensets are immutable sets.
Lists []
Dictonary {} – with key value pair
Tuple ()
Sets {}
Strings “ “ or ‘ ‘

File Handling :-
File is a named location on disk to store related information. It is used to permanently store data in a non-
volatile memory (e.g. hard disk). Since, random access memory (RAM) is volatile which loses its data
when computer is turned off, we use files for future use of the data. When we want to read from or write
to a file we need to open it first. When we are done, it needs to be closed, so that resources that are tied
with the file are freed.
Hence, in Python, a file operation takes place in the following order.

1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening a File:- Before working with Files you have to open the File. To open a File, Python built in
function open() is used. It returns an object of File which is used with other functions. Having opened the
file now you can perform read, write, etc. operations on the File.
>>> f = open('workfile', ‘mode')
f=open(“c:/folder/filename.txt”,”mode”)
The first argument is a string containing the filename.
The second argument is another string containing a few characters describing the way in which the
file will be used.
Writing to a File: write() method is used to write a string into a file.
>>> f.write(string)
>>> f.write('This is a test') 15
Reading from a File: read() method is used to read data from the File.
>>> f.read()
>>> for line in f:
... print(line, end='')
f.read(4) -> read first 4 data
The read() method returns newline as ‘\n’. Once the end of file is reached, we get empty string on
further reading.
f.tell() -> gets the current file position
f.seek(0) -> brings file cursor to initial position
readline() -> method is used to read individual lines of a file

18
Closing a File: Once you are finished with the operations on File at the end you need to close the
file. It is done by the close() method. close() method is used to close a File.
>>> f .close()
File Mode:-
• r -> It opens in Reading mode. It is default mode of File. Pointer is at beginning of the file.
• r+ -> Opens file for reading and writing. Pointer is at beginning of file.
• W -> Opens file in Writing mode. If file already exists, then overwrite the file else create a new file.
• w+ -> Opens file for reading and writing. If file already exists, then overwrite the file else create a
new file.
• a - >Opens file in Appending mode. If file already exists, then append the data at the end of existing
file, else create a new file.
• a+ -> Opens file in reading and appending mode. If file already exists, then append the data at the
end of existing file, else create a new file.

Renaming and Deleting Files


Python os module provides methods that help you perform file-processing operations, such as renaming
and deleting files. To use this module we need to first import this and then we can write
Os.rename(“currentfilename”, “newfilename”)
Os.remove(“filename”)
You can use the mkdir() method of the os module to create directories in the current directory . You can
use the chdir() method to change the current directory. The chdir() method takes an argument, which is
the name of the directory that you want to make the current directory

Object Oriented Programming:-


Python is an “object-oriented programming language.” This means that almost all the code is
implemented using a special construct called classes. Programmers use classes to keep related things
together. This is done using the keyword “class,” which is a grouping of object-oriented constructs. OOP
is designed in such a way that one should focus on an object while programming and not the procedure.
An object can be anything that we see around us. It can be a human (that has some properties like -
name, address, DOB and so on) or a car( that has some properties like – color, type, brand) . Object
oriented programming brings programming close to real life, as we are always dealing with an object,
performing operations on it, using it's methods and variables etc.

Overview of OOP terminology:-

What is a class and Object?

19
A class is a code template for creating objects. Objects have member variables and have behaviour
associated with them. In python a class is created by the keyword class.
An object is created using the constructor of the class. This object will then be called the instance of the
class. In Python we create class and instances in the following manner

class Snake: # create class


snake = Snake() # create object or instance

Attributes and Methods in class:


A class by itself is of no use unless there is some functionality associated with it. Functionalities are
defined by setting attributes, which act as containers for data and functions related to those attributes.
Those functions are called methods.
Attributes:
You can define the following class with the name Snake. This class will have an attribute name.

class Snake:
name = "python" # set an attribute `name` of the class

You will then be able to access the attributes that are present inside the class using the dot . operator
and the object name as follows-

snake = Snake()
# access the class attribute name inside the class Snake.
print(snake.name)

Methods
Once there are attributes that “belong” to the class, you can define functions that will access the class
attribute. These functions are called methods. When you define methods, you will need to always provide
the first argument to the method with a self keyword.
For example, you can define a class Snake, which has one attribute name and one method change_name.
The method
class Snake:change name will take in an argument new_name along with the keyword self.
name = "python"
def change_name(self, new_name): # note that the first argument is self
self.name = new_name # access the class attribute with the self keyword

20
Instance attributes in python and the init method
You can also provide the values for the attributes at runtime. This is done by defining the attributes inside
the init method. The following example illustrates this.

class Snake:
def __init__(self, name):
self.name = name
def change_name(self, new_name):
self.name = new_name

Class and Instance Variables:-


Generally speaking, instance variables are for data unique to each instance and class variables are for
attributes and methods shared by all instances of the class:

class Dog:
kind = 'canine' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each instance
>>> d = Dog('Fido')
>>> e = Dog('Buddy')
>>> d.kind # shared by all dogs
'canine'
>>> e.kind # shared by all dogs
'canine'
>>> d.name # unique to d
'Fido'
>>> e.name # unique to e
'Buddy'

Underscore (_) in Python


Following are different places where _ is used in Python:
1. Single Underscore:
 In Interpreter
 After a name
 Before a name
2. Double Underscore:

21
1. __leading_double_underscore
2. __before_after__

Single Underscore
In Interpreter: _ returns the value of last executed expression value in Python Prompt/Interpreter

After a name:

Python has their by default keywords which we can not use as the variable name. To avoid such
conflict between python keyword and variable we use underscore after name
Before a name
Leading Underscore before variable/function/method name indicates to programmer that It is for
internal use only, that can be modified whenever class want.
Here name prefix by underscore is treated as non-public. If specify from Import * all the name starts
with _ will not import. Python does not specify truly private so this ones can be call directly from
other modules if it is specified in __all__, We also call it weak Private

Double Underscore (__):-


__leading_double_underscore Leading double underscore tell python interpreter to rewrite name in
order to avoid conflict in subclass.Interpreter changes variable name with class extension and that
feature known as the Mangling.
In Mangling python interpreter modify variable name with ___. So Multiple time It use as the Private
member because another class can not access that variable directly. Main purpose for __ is to use
variable/method in class only If you want to use it outside of the class you can make public api
__BEFORE_AFTER__
This convention is used for special variables or methods (so-called “magic method”) such as__init__,
__len__. These methods provides special syntactic features or does special things

Private Variables in Python


In Python, there is no existence of “Private” instance variables which cannot be accessed except
inside an object. However, a convention is being followed by most Python code and coders i.e., a
name prefixed with an underscore, For e.g. _webtek should be treated as a non-public part of the API
or any Python code, whether it is a function, a method or a data member. While going through this
we would also try to understand the concept of various forms of trailing underscores, for eg., for _ in
range(10), __init__(self).

Mangling and how it works


In Python, there is something called name mangling, which means that there is a limited support for a
valid use-case for class-private members basically to avoid name clashes of names with names
defined by subclasses. Any identifier of the form __geek (at least two leading underscores or at most
one trailing underscore) is replaced with _classname__geek, where classname is the current class
name with leading underscore(s) stripped. As long as it occurs within the definition of the class, this
mangling is done. This is helpful for letting subclasses override methods without breaking intraclass
method calls.

22
Encapsulation or Data Hiding:-
One of the key parts of object-oriented programming is encapsulation, which involves the packaging
of variables and related functions in one simple-to-use object: the instance of a class.
A concept related to this is data hiding, which consists in hiding the implementation details of a
class. In this way the user interface of this class is clean and more intuitive. In other programming
languages, data hiding is done by creating private methods and attributes, to which their external
access to the function is blocked. In Python, however, the philosophy is slightly different “we are all
consenting adults” and therefore there are no particular restrictions on access. So there is nothing that
can deprive an attribute or method in such a way as to make it inaccessible to the outside of the
classroom.

In Python, the so-called weakly-private methods have a single underscore (_) prefixed in their
name. This prefix indicates the presence of a private method, which should not be used outside the
class. But this is just a convention and nothing avoids the opposite. The only real effect it has is to
avoid importing the method when using the wording
In Python, we use double underscore (Or __) before the attributes name and those attributes will not
be directly visible outside.
class MyClass:
# Hidden member of MyClass
__a = 0
# A member method that changes
# __a
def add(self, increment):
self.__a += increment
print (self.__a)
# Driver code

23
myObject = MyClass()
myObject.add(2)
myObject.add(5)

# This line causes error

print (myObject.__a)
Output:-

2
7
Traceback (most recent call last):
File "filename.py", line 13, in
print (myObject.__a)
AttributeError: MyClass instance has
no attribute '__a'

the above program, we tried to access hidden variable outside the class using object and it threw an
exception.
We can access the value of hidden attribute by a tricky syntax: # A Python program to demonstrate that
hidden
# members can be accessed outside a class
class MyClass:
# Hidden member of MyClass
__a = 10
# Driver code
myObject = MyClass()
print(myObject._MyClass__a)
Output:-
10
Private methods are accessible outside their class, just not easily accessible. Nothing in Python is truly
private; internally, the names of private methods and attributes are mangled and unmangled on the fly
to make them seem inaccessible by their given names

Name Notation Behaviour

name Public Can be accessed from


inside and outside
_name Protected Protected member is (in
C++ and Java) accessible
only from within the class
and it’s subclasses
__name Private Can't be seen and
accessed from outside

24
Class Inheritance:-
It refers to defining a new class with little or no modification to an existing class.The new class is
called derived (or child) class and the one from which it inherits is called the base (or parent)
class.

Syntax is

class P: # define parent class


pAttr = 100
def __init__(self):
print( "Calling parent constructor")
def pMethod(self):
print ('Calling parent method')
def setAttr(self, attr):
P.pAttr = attr
def getAttr(self):
print ("Parent attribute :", P.pAttr)
class Ch (P): # define child class
def __init__(self):
print ("Calling child constructor")
Eg
def childMethod(self):
print ('Calling child method')
c = Ch() # instance of child
c.childMethod() # child calls its method
c.pMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
25
Method Overriding in Python:-
As we know that __init__() is the constructor used in every classes. So when we use init() in both the
superclass and subclass, so when we create object of subclass which init to call?????? It’s a
confusion……So it always calls the subclass init() ie the method in the derived class overrides that in
the base class. Now how to call then superclass init(). It can be done using method overriding.
Generally when overriding a base method, we tend to extend the definition rather than simply replace
it. The same is being done by calling the method in base class from the one in derived class
To access the parent member from subclass, we can use either of the two ways
a) Using Parent class name
b) Using super

We can use either


super().__init__(first, last)
or
Person.__init__(self,first,last)
Method overriding is an object-oriented programming feature that allows a subclass to provide a
different implementation of a method that is already defined by its superclass or by one of its
superclasses. The implementation in the subclass overrides the implementation of the superclass by
providing a method with the same name, same parameters or signature, and same return type as the
method of the parent class.

Isinstance() and issubclass() method:-


 The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a
subclass of the superclass sup.

26
 The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an
instance of a subclass of Class

Multiple Inheritance:-
Python supports multiple inheritance. We specify all parent classes as comma separated list in
bracket.eg
Class derived(Base1, Base2):

Eg
class A:
def __init__(self):
self.name = 'Mousita'
self.age = 23
def getName(self):
return self.name

class B:
def __init__(self):
self.name = 'abcd'
self.id = '32'
def getName(self):
return self.name
class C(A, B):
def __init__(self):

27
A.__init__(self)

B.__init__(self)
def getName(self):
return self.name

C1 = C()
print(C1.getName())

in the above example


The name when printed is ‘abcd’ instead of ‘Mousita’. Let’s try to understand what’s happening here. In
the constructor of C, the first constructor called is the one of A. So, the value of name in C becomes same
as the value of name in A. But after that, when the constructor of B is called, the value of name in C is
overwritten by the value of name in B. So, the name attribute of C retains the value ‘abcd’ when printed.
The result would be same even if we declared class C as:

C(B,A)
The hierarchy becomes completely depended on the order of __init__() calls inside the subclass. To
deal with it perfectly, there is a protocol named MRO (Method Resolution Order).
MRO (Method Resolution Order):-
The Python Method Resolution Order defines the class search path used by Python to search for the
right method to use in classes having multi-inheritance. When a class inherits from multiple parents,
Python build a list of classes to search for when it needs to resolve which method has to be called
when one in invoked by an instance. MRO works in a depth first left to right way.
This algorithm is a tree routing, and works this way, deep first, from left to right :

1. Look if method exists in instance class


2. If not, looks if it exists in its first parent, then in the parent of the parent and so on
3. If not, it looks if current class inherits from others classes up to the current instance others
parents.

So in our example, algorithm search path is : D, B, A, C, A. A class cannot appears twice in search
path, so the final version is D, B, C, A:
When it is the first class A occurrence, Python ask to class A : « Are you a good Head » ? And the
answer is « No, I've have not been very kind today, I've tried to stole the place of my child class C
which inherits from me and is in the tail of the search path after me ». So Python removes A from the
search path at this point which becomes D, B, C, A.

GUI PROGRAMMING (TKINTER)


Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI
methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit
shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter is an easy task. To create a tkinter:
1. Importing the module – tkinter
2. Create the main window (container)

28
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

GUI PROGRAMMING (TKINTER)


Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI
methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit
shipped with Python. Python with tkinter outputs the fastest and easiest way to create the GUI
applications. Creating a GUI using tkinter is an easy task. To create a tkinter:
1. Importing the module – tkinter
2. Create the main window (container)
3. Add any number of widgets to the main window
4. Apply the event Trigger on the widgets.

Tkinter Widgets
Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application.
These controls are commonly called widgets.
Let's see the brief introduction to all of these widgets in the Tkinter.
 Button:- Button widget is used to place the buttons in the tkinter.
 Canvas:- Canvas is used to draw shapes in your GUI.
 Checkbutton:- Checkbutton is used to create the check buttons in your
application. You can select more than one option at a time.
 Entry:- Entry widget is used to create input fields in the GUI.
 Frame:- Frame is used as containers in the tkinter.
 Label:- Label is used to create a single line widgets like text, images, etc..,
 Menu:- Menu is used to create menus in the GUI.

Organizing Layout And Widgets


To arrange the layout in the window, we will use Frame, class. Let's create a simple program to see
how the Frame works.
Steps:-
 Frame is used to create the divisions in the window. You can align the frames as you like
with side parameter of pack() method.
 Button is used to create a button in the window. It takes several parameters like text(Value of
the Button), fg(Color of the text), bg(Background color), etc..,

Event-driven programming
Anything that happens in a user interface is an event. We say that an event is fired whenever the user
does something – for example, clicks on a button or types a keyboard shortcut. Some events could
also be triggered by occurrences which are not controlled by the user – for example, a background
task might complete, or a network connection might be established or lost. Our application needs to
monitor, or listen for, all the events that we find interesting, and respond to them in some way if they

29
occur. To do this, we usually associate certain functions with particular events. We call a function
which performs an action in response to an event an event handler – we bind handlers to events.
We have used the command keyword parameter when constructing each button to specify the
function which should handle each button’s click events – both of these functions are object methods.

What is RDBMS?

RDBMS stands for Relational Database Management System. RDBMS is the basis for SQL, and for all
modern database systems like MS SQL Server, IBM DB2, Oracle, MySQL, and Microsoft Access.
A Relational database management system (RDBMS) is a database management system (DBMS) that is
based on the relational model as introduced by E. F. Codd.
SqlLite is also the example of RDBMS.

What is a table?

The data in an RDBMS is stored in database objects which are called as tables. This table is basically a
collection of related data entries and it consists of numerous columns and rows.
Remember, a table is the most common and simplest form of data storage in a relational database. The
following program is an example of a CUSTOMERS table −
----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kolkata | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Rahul | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+

What is a field?
Every table is broken up into smaller entities called fields. The fields in the CUSTOMERS table consist
of ID, NAME, AGE, ADDRESS and SALARY.
A field is a column in a table that is designed to maintain specific information about every record in the
table.

30
What is a Record or a Row?

A record is also called as a row of data is each individual entry that exists in a table. For example, there
are 7 records in the above CUSTOMERS table. Following is a single row of data or record in the
CUSTOMERS table −
----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+

What is a column?

A column is a vertical entity in a table that contains all information associated with a specific field in a
table.
For example, a column in the CUSTOMERS table is ADDRESS, which represents location description
and would be as shown below −

+-----------+
| ADDRESS |
+-----------+
| Ahmedabad |
| Delhi |
| Kota |
| Mumbai |
| Bhopal |
| MP |
| Indore |
+----+------+

What is a NULL value?

A NULL value in a table is a value in a field that appears to be blank, which means a field with a NULL
value is a field with no value.
It is very important to understand that a NULL value is different than a zero value or a field that contains
spaces. A field with a NULL value is the one that has been left blank during a record creation.

SQL is followed by a unique set of rules and guidelines called Syntax. This tutorial gives you a quick
start with SQL by listing all the basic SQL Syntax.
All the SQL statements start with any of the keywords like SELECT, INSERT, UPDATE, DELETE,
ALTER, DROP, CREATE, USE, SHOW and all the statements end with a semicolon (;).
The most important point to be noted here is that SQL is case insensitive, which means SELECT and
select have same meaning in SQL statements. Whereas, MySQL makes difference in table names. So, if
you are working with MySQL, then you need to give table names as they exist in the database.

31
Installation
SQLite3 can be integrated with Python using sqlite3 module, which was written by Gerhard Haring. It
provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249. You do
not need to install this module separately because it is shipped by default along with Python version
2.5.x onwards.
To use sqlite3 module, you must first create a connection object that represents the database and then
optionally you can create a cursor object, which will help you in executing all the SQL statements.

Python sqlite3 module APIs

Following are important sqlite3 module routines, which can suffice your requirement to work with
SQLite database from your Python program. If you are looking for a more sophisticated application, then
you can look into Python sqlite3 module's official documentation.

Sr.No. API & Description

1
sqlite3.connect(database [,timeout ,other optional arguments])
This API opens a connection to the SQLite database file. You can use ":memory:" to open
a database connection to a database that resides in RAM instead of on disk. If database is
opened successfully, it returns a connection object.
When a database is accessed by multiple connections, and one of the processes modifies
the database, the SQLite database is locked until that transaction is committed. The
timeout parameter specifies how long the connection should wait for the lock to go away
until raising an exception. The default for the timeout parameter is 5.0 (five seconds).
If the given database name does not exist then this call will create the database. You can
specify filename with the required path as well if you want to create a database anywhere
else except in the current directory.

2
connection.cursor([cursorClass])
This routine creates a cursor which will be used throughout of your database programming
with Python. This method accepts a single optional parameter cursorClass. If supplied, this
must be a custom cursor class that extends sqlite3.Cursor.

3
cursor.execute(sql [, optional parameters])
This routine executes an SQL statement. The SQL statement may be parameterized (i. e.
placeholders instead of SQL literals). The sqlite3 module supports two kinds of
placeholders: question marks and named placeholders (named style).
For example − cursor.execute("insert into people values (?, ?)", (who, age))

4
connection.execute(sql [, optional parameters])

32
This routine is a shortcut of the above execute method provided by the cursor object and it
creates an intermediate cursor object by calling the cursor method, then calls the cursor's
execute method with the parameters given.

5
cursor.executemany(sql, seq_of_parameters)
This routine executes an SQL command against all parameter sequences or mappings
found in the sequence sql.

6
connection.executemany(sql[, parameters])
This routine is a shortcut that creates an intermediate cursor object by calling the cursor
method, then calls the cursor.s executemany method with the parameters given.

7
cursor.executescript(sql_script)
This routine executes multiple SQL statements at once provided in the form of script. It
issues a COMMIT statement first, then executes the SQL script it gets as a parameter. All
the SQL statements should be separated by a semi colon (;).

8
connection.executescript(sql_script)
This routine is a shortcut that creates an intermediate cursor object by calling the cursor
method, then calls the cursor's executescript method with the parameters given.

9
connection.total_changes()
This routine returns the total number of database rows that have been modified, inserted,
or deleted since the database connection was opened.

10
connection.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.

11
connection.rollback()
This method rolls back any changes to the database since the last call to commit().

12
connection.close()
This method 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!

13
cursor.fetchone()
This method fetches the next row of a query result set, returning a single sequence, or
None when no more data is available.

33
14
cursor.fetchmany([size = cursor.arraysize])
This routine fetches the next set of rows of a query result, returning a list. An empty list is
returned when no more rows are available. The method tries to fetch as many rows as
indicated by the size parameter.

15
cursor.fetchall()
This routine fetches all (remaining) rows of a query result, returning a list. An empty list is
returned when no rows are available.

Connect To Database

Following Python code shows how to connect to an existing database. If the database does not exist, then
it will be created and finally a database object will be returned.

import sqlite3

conn = sqlite3.connect('test.db')

print "Opened database successfully";

Create a Table

Following Python program will be used to create a table in the previously created database.
#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute('''CREATE TABLE COMPANY


(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
print "Table created successfully";

conn.close()

34
When the above program is executed, it will create the COMPANY table in your  test.db and it will
display the following messages −
Opened database successfully
Table created successfully

INSERT Operation
Following Python program shows how to create records in the COMPANY table
created in the above example.
#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (1, 'Paul', 32, 'California', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (2, 'Allen', 25, 'Texas', 15000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )");

conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \


VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )");

conn.commit()
print "Records created successfully";
conn.close()
When the above program is executed, it will create the given records in the COMPANY table and it will
display the following two lines −
Opened database successfully
Records created successfully

SELECT Operation

Following Python program shows how to fetch and display records from the COMPANY table created
in the above example.

35
#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

cursor = conn.execute("SELECT id, name, address, salary from


COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


conn.close()

When the above program is executed, it will produce the following result.
Opened database successfully
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

UPDATE Operation

36
Following Python code shows how to use UPDATE statement to update any record
and then fetch and display the updated records from the COMPANY table.
#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("UPDATE COMPANY set SALARY = 25000.00 where ID = 1")


conn.commit()
print "Total number of rows updated :", conn.total_changes

cursor = conn.execute("SELECT id, name, address, salary from


COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows updated : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 25000.0

ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0

Operation done successfully

37
DELETE Operation

Following Python code shows how to use DELETE statement to delete any record and then fetch and
display the remaining records from the COMPANY table.
#!/usr/bin/python

import sqlite3

conn = sqlite3.connect('test.db')
print "Opened database successfully";

conn.execute("DELETE from COMPANY where ID = 2;")


conn.commit()
print "Total number of rows deleted :", conn.total_changes

cursor = conn.execute("SELECT id, name, address, salary from


COMPANY")
for row in cursor:
print "ID = ", row[0]
print "NAME = ", row[1]
print "ADDRESS = ", row[2]
print "SALARY = ", row[3], "\n"

print "Operation done successfully";


conn.close()
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0

ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0

ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
Operation done successfully

38
THE END

39

You might also like