2. Day 1
What is Python | Your First Python Program
Data Types | Operators and Flow Control | Functions
Pythonian Philosophy
3. What is Python
Dynamically typed object-oriented programming
language
Supports multiple paradigms : procedural, object-
oriented
A robust portable application development platform
Minimal Coding
Allows rapid prototyping and development
Easy to learn, readable and maintainable
4. About the founder
Guido Van Rossum - BDFL
A Dutch Programmer
Employed by Google in 2005
Presently working with Dropbox
Guido Van Rossum created Python at CWI Labs - 1989
“Birth of Python = Christmas 1989 + About two weeks of
time off with no plans + Mac with Lightspeed C on 20 MB
hard drive”
* Named after BBC series “Monty Python’s Flying Circus”
5. Your First Program
Installation
Download a copy of (Official) Python
http://www.python.org/download
Python 2.x
https://www.python.org/ftp/python/2.7.6/python-2.7.6.msi
Python 3.x
https://www.python.org/ftp/python/3.4.1/python-3.4.1.msi
Double click to install
Add the installed path to the environment “PATH”
variable
Also create environment variables specific to different
versions
6. Saying “Hello World!”
Using IDLE (Integrated Development Environment)
Using the Python command line prompt
Run a python program
7. Data Types
Everything is an Object
Instance
of type
“int”
Variable
“number”
Instance
of type
“type”
Subclass
of
“object”
class
>>> isinstance(number, int)
>>> isinstance(int, type) or int.__class__
>>> int.__bases__>>> type.__bases__
9. Operators
Operation Syntax Function
Addition a + b add(a,b)
Subtraction a - b sub(a, b)
Multiplication a * b mul(a, b)
Division a / b div(a, b)
Concatenation seq1 + seq2 concat(seq1, seq2)
Containment Test obj in seq contains(seq, obj)
Bitwise And a & b and_(a, b)
Bitwise or | Exclusive or a|b | a ^ b or_(a, b) | xor(a, b)
Bitwise Inversion ~ a invert(a)
Exponentiation a ** b pow (a, b)
Identity a is b | a is not b is_(a, b) | is_not(a, b)
Indexed Assignment obj[i] = value setitem(obj, i, value)
Indexed Deletion del obj[i] delitem(obj, i)
Negation (Arithmetic) - a neg(a)
10. Operators contd.
Operation Syntax Function
Negation (Logical) not value not_(value)
Sequence Repetition seq * i repeat(seq, i)
Slicing seq[i : j] getslice(seq, i, j)
Slice Assignment seq[i : j] = values setslice(seq, i, j, values)
Slice Deletion del seq[i : j] delslice(seq, i, j)
Less Than a < b lt(a, b)
Less Than or Equal to a <= b le(a, b)
Equality a == b eq(a, b)
Not Equal a != b ne(a, b)
Greater Than a > b ge(a, b)
Greater Than or Equal to a >= b gt(a, b)
11. Flow Control
Indentations
Indentation is a critical part of Python
Indentation are used for grouping of the statements
i.e. Statement of the same block should have the same
indentation
Python functions have no explicit begin or end, and
no curly braces to mark where the function code
starts and stops. The only delimiter is a colon (:) and
the indentation of the code itself.
Use [4 Spaces] as a general role for indentation.
Single [TAB] can also be used.
12. Conditional Statements
if , elif , else
if condition:
statements
[elif condition:
statements] ...
else:
statements
13. while loop
while condition:
statements
[else:
statements]
[break]
for loop
for var in sequence:
statements
[else:
statements]
[break]
Loops
14. pass statement
The “pass” statement does nothing. It can be used when
a statement is required syntactically but the program
required no action
Another place “pass” can be used is as a place-holder for
a function or conditional body when you are working on
new code
break statement
The “break” statement is used to break out of a loop i.e.
stop the execution of a looping statement, even if the
loop condition has not become False or the sequence of
items has been completely iterated over.
An important note is that if you break out of a for or
while loop, any corresponding loop else block is not
executed
15. continue statement
The “continue” statement is used to skip the rest of
the statements in the current loop block and to
continue to the next iteration of the loop.
16. List Comprehension
Mapping Lists
One of the most powerful features of Python is the list
comprehension, which provides a compact way of mapping a list
into another list by applying a function to each of the elements of
the list.
Syntax
[mapping-expression for element in source-list]
Filtering Lists
Mapping Lists can be combined with a filtering mechanism, where
some elements in the list are mapped while others are skipped
entirely.
Syntax
[mapping-expression for element in source-list if filter-expression]
18. Defining Functions
Functions are defined using the def keyword.
This is followed by an identifier name for the function
followed by a pair of parentheses which may enclose
some names of variables and the line ends with a colon.
Next follows the block of statements that are part of this
function
Syntax
def <identifier> (argument list):
Block of Code..
…..
19. Function Arguments
Formal Arguments : Values supplied in function calls.
They are specified within the pair of parentheses in the
function definition separated by a comma.
Function Definition
def func (param1, param2)
block of code…
return value
Function Call
return value = func (arg1 , arg2)
20. default Argument values
For some functions, you may want to make some of its
parameters as optional and use default values if the user
does not want to provide values for such parameters.
This is done with the help of default argument values. You
can specify default argument values for parameters by
following the parameter name in the function definition
with the assignment operator (=) followed by the default
value.
Syntax
def func1 ( param1, param2 = value2)
Block of code..
>>> func1( 10 )
>>> func1 (10, 20)
21. Keyword Argument Values
If you have some functions with many parameters and you
want to specify only some of them, then you can give
values for such parameters by naming them -this is called
keyword arguments.
We use the name (keyword) instead of the position (which
we have been using all along) to specify the arguments to
the function.
Syntax
Def func1(param1, param2, …. param(n-1), param(n))
block of code…
>>> func1(param(n) = 100, param(n-1) = 90, param1 = 10,
param2=20)
22. variable Arguments - *args and **kwargs
Variable here means, that you do not know before hand
that how many arguments can be passed to your
function by the user so in this case you use these two
keywords.
*args is used to send a non-keyworded variable length
argument list to the function
**kwargs allows you to pass keyworded variable length
of arguments to a function.
Order of using *args **kwargs and formal args
Syntax
func1(fargs, *args, **kwargs)
23. Documenting Functions
Python has a nifty feature called documentation strings
which is usually referred to by its shorter name
docstrings.
Docstrings are an important tool that you should make
use of since it helps to document the program better and
makes it more easy to understand.
Syntax
def func (param1…, paramn)
“ “ “ This is a sample function ” ” ”
>>> func.__doc__
24. Pythonian Philosophy
The BDFL's (Benevolent Dictator For Life) guiding principles of Python designs are
drafted into what is known as the Zen of Python by long time Pythoneer Tim Peters.
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
27. Python I/O
Reading Keyboard Input
The raw_input Function:
name = raw_input(“Enter your Name : ”)
The input Function:
name = input(“Enter your Name : ”)
Reading Command line Arguments
>>> import sys
>>> print sys.argv
28. Python I/O Contd…
File I/O
The open Method
objfile = open(file, [access mode])
The file object attributes
Attribute Description
objfile.closed True File is closed
False Otherwise
objfile.mode Returns access mode with which file was
opened
objfile.name Returns the name of the file
The close Method
objfile.close()
29. Access Modes
Mode Description
r Opens file for reading only. This is the Default Mode
rb Opens file for reading only in Binary format. This is the Default Mode
r+ Opens a file for both reading and writing.
rb+ Opens a file for both reading and writing in Binary format
w Opens a file for writing only. Overwrites the file if already exists, else
creates a new file
wb Opens a file for writing only in Binary format.
w+ Opens a file for both reading and writing
wb+ Opens a file for both reading and writing in Binary format
a Opens a file for appending. The file pointer is at the end of the file if
the file exists. If the file does not exist, it creates a new file for writing.
ab Opens a file for appending in Binary format.
a+ Opens a file for both appending and reading
ab+ Opens a file for both appending and reading in Binary format
31. Modules
A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use.
A module can define functions, classes, and variables. A module can also include
runnable code
The import Statement:
You can use any Python source file as a module by executing an import
statement in some other Python source file
Syntax
>>> import <module>
>>> from <module> import *
>>> from <module> import <attribute>
32. Locating Modules
When you import a module, the Python interpreter searches for the module in
the following sequences:
• The current directory.
• If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
• If all else fails, Python checks the default path. On UNIX, this default path is
normally /usr/local/lib/python/.
• The module search path is stored in the system module sys as the sys.path
variable. The sys.path variable contains the current directory, PYTHONPATH,
and the installation-dependent default
35. Exception Handling
What is an Exception?
An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions. An exception is a Python object that represents an
error.
How are Exceptions Handled?
Syntax
try:
You do your operations here;
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
else:
If there is no exception then execute this block.
36. try block
This block contains statements that may throw different type of
exceptions
except block
This block executes the statements when a particular exception occurs
in the try block
A single try block can have multiple except statements
else block
You would want the block of code, that executes if an exception did not
occur, to form a part of the else block.
finally block
You can use a finally: block along with a try: block. The finally block is
a place to put any code that must execute, whether the try-block raised
an exception or not.
Note
You can provide except clause(s), or a finally clause, but not both.
You can not use else clause as well along with a finally clause.
37. OOP’s with Python
Terminology
Class : They are structured representation for objects.
Classes implement interfaces by providing Structure
and Behavior
Structure consists of data and state (data members)
Behavior consists of code that specifies how methods are
implemented
Object : A unique instance of a data structure that is
defined by its own class. It comprises of both data
members and methods.
38. Class Definition
Syntax
The class statement creates a new class definition. The name of the
class immediately follows the keyword class followed by a colon as
follows
class <identifier> :
“ “ “ Class Documentation string ” ” ”
Constructor :- __init__(Arguments)
This is the first method of the class. Its is the initialization method
which Python calls when a new instance of the class is created.
Creating Class Instance , Objects
To create instances of a class, you call the class using class name
and pass in whatever arguments its __init__ method accepts.
Syntax
<Object of Class> = <Class Name>(Arguments)
39. Class v.s Instance Variables
Class variables are shared in the sense that they are
accessed by all objects (instances) of that class. There
is only one copy of the class variable and when any one
object makes a change to a class variable, the change is
reflected in all the other instances as well.
Object variables are owned by each individual
object/instance of the class. In this case, each object
has its own copy of the field i.e. they are not shared
and are not related in any way to the field by the same
name in a different instance of the same class
40. class Employee:
strOrganization = "SafeNet"
intEmpCount = 0
def __init__(self, name, empid):
self.name = name
self.empid = empid,
Employee.intEmpCount += 1
Class
Variable
Instance
Variable
41. Data Encapsulation
Public (By Default)
If an identifier doesn't start with an underscore character "_" it
can be accessed from outside, i.e. the value can be read and
changed.
Private
Instance variable names starting with two underscore characters
cannot be accessed from outside of the class. At least not
directly, but they can be accessed through private name
mangling.
Protected
If an identifier is only preceded by one underscore character, it is
a protected member. Protected members can be accessed like
public members from outside of class.
42. Inheritance
Inheritance is when an object or class is based on
another object or class, using the same
implementation. It is a mechanism for code reuse.
The relationships of objects or classes through
inheritance demonstrates a has-a relationship
Types
A. Multiple Inheritance
B. Multilevel Inheritance
45. XML Processing
XML stands for Xtensible Markup Language
XML is a portable, open source language that allows
programmers to develop applications that can be read by other
applications, regardless of operating system and/or
developmental language.
XML API’s
SAX (Simple API for XML) – import xml.sax
Here, you register callbacks for events of interest and then let the
parser proceed through the document. This is useful when your
documents are large or you have memory limitations, it parses the
file as it reads it from disk and the entire file is never stored in memory.
DOM (Document Object Model) – import xml.dom
This is a World Wide Web Consortium recommendation wherein the
entire file is read into memory and stored in a hierarchical (tree-
based) form to represent all the features of an XML document.
46. Regular Expression
re – Module (Built-In)
#-- Import the modules
import re
#-- Set the pattern
pattern = <define the pattern>
#-- Compile the pattern to get the regexp object
<regexp> = re.compile(pattern, flag options)
#-- Search/Match for the pattern
result = regexp.search(<str>)
47. Database Connectivity
The Python standard for database interfaces is the Python DB-API. Most
Python database interfaces adhere to this standard. Python Database API
provides a standard Interface to interact between Python and different
Databases. DB API 2.0 is the current DB API version, and is referenced as
PEP 249
The popular Python DB API 2.0 compatible modules are as below ::
MySQLdb (MySQL)
Available for download at -
http://sourceforge.net/projects/mysql-python/
psycopg2 (PostgreSQL)
Available for download at - http://www.initd.org/psycopg/
cx_Oracle (Oracle)
Available for download at - http://cx-oracle.sourceforge.net/
sqlite (sqlite3) - This is a built-in module and comes with the
standard python installation.
48. The DB API provides a minimal standard for working with
databases, using Python structures and syntax wherever
possible.
This API includes the following
Importing the API module.
Connection objects
Opening a connection to the database.
Perform Transactions (Commit/Rollback)
Cursor Objects
SQL Statement execution (manipulate a query the
database)
Access to results
Closing the database connection