E-Book Python Programming
E-Book Python Programming
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.
2. Script mode ie create in any editor and save it with .py, then open command prompt and type python
a.py
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.
Identifiers
Identifiers are the names given to the fundamental building blocks in a program. These can be variables
,class ,object ,functions , lists , dictionaries etc.
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
Membership operator
Operator Description Example
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.
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
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
}
Loops in Python-
Two type of Loops are there in python
1. While loop
2. For loop
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.
If you do need to iterate over a sequence of numbers, the built-in function range() comes in handy.
It generates arithmetic progressions:
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
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.
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.
Output 64
G=lambda x: x**2
Print (G)
Output 64
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:
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
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.
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.
print len(tuple) ## 3
print tuple[2] ## hi
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
items() Returns a list containing a tuple for each key value pair
setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the
specified value
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
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 = []
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.
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.
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:
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 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'
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
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)
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
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
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())
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 :
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.
28
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.
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 |
+----+------+
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.
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.
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')
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.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.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";
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
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";
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
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";
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