SlideShare a Scribd company logo
1 of 49
An Introduction
By Karthik Prakash
Day 1
What is Python | Your First Python Program
Data Types | Operators and Flow Control | Functions
Pythonian Philosophy
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
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”
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
Saying “Hello World!”
 Using IDLE (Integrated Development Environment)
 Using the Python command line prompt
 Run a python program
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__
Data Types and Containers
 Integer <type 'int'>
 Float <type 'float'>
 Boolean <type 'bool'>
 Long <type 'long'>
 String <type 'str'>
 Unicode Strings <type 'unicode'>
 List <type 'list'>
 Tuple <type 'tuple'>
 Dictionary <type 'dict'>
 Sets <type 'set'>
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)
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)
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.
Conditional Statements
if , elif , else
if condition:
statements
[elif condition:
statements] ...
else:
statements
 while loop
while condition:
statements
[else:
statements]
[break]
 for loop
for var in sequence:
statements
[else:
statements]
[break]
Loops
 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
 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.
 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]
Functions
 Defining Functions
 Function Arguments (Default, keyword, Variable)
 Documenting Functions
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..
…..
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) 
 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)
 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)
 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)
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__
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!
Day 1 Ends
Day 2
Python I/O|CSV , Configuration File Handling|
Excel Connectivity|
Modules
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
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()
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
Exercises
Reading and Writing CSV files
Reading and Writing Configuration files
Reading and Writing Excel Files
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>
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
Day 2 Ends
Day 3
Exception Handling|
OO with Python
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.
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.
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.
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)
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
class Employee:
strOrganization = "SafeNet"
intEmpCount = 0
def __init__(self, name, empid):
self.name = name
self.empid = empid,
Employee.intEmpCount += 1
Class
Variable
Instance
Variable
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.
 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
Day 3 Ends
Day 4
XML Processing
Regular Expression| DB Connectivity
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.
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>)
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.
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
Day 4 Ends

More Related Content

What's hot

Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
4. python functions
4. python   functions4. python   functions
4. python functionsin4400
 
Python Interview Questions For Freshers
Python Interview Questions For FreshersPython Interview Questions For Freshers
Python Interview Questions For Fresherszynofustechnology
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Ranel Padon
 
python Function
python Function python Function
python Function Ronak Rathi
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & styleKevlin Henney
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Jaganadh Gopinadhan
 

What's hot (20)

Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
4. python functions
4. python   functions4. python   functions
4. python functions
 
Python Interview Questions For Freshers
Python Interview Questions For FreshersPython Interview Questions For Freshers
Python Interview Questions For Freshers
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 
python Function
python Function python Function
python Function
 
Advance python
Advance pythonAdvance python
Advance python
 
Python Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & stylePython Foundation – A programmer's introduction to Python concepts & style
Python Foundation – A programmer's introduction to Python concepts & style
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
Python libraries
Python librariesPython libraries
Python libraries
 
Python recursion
Python recursionPython recursion
Python recursion
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Functions in python
Functions in python Functions in python
Functions in python
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python cheat-sheet
Python cheat-sheetPython cheat-sheet
Python cheat-sheet
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 
Python revision tour i
Python revision tour iPython revision tour i
Python revision tour i
 
Python basics
Python basicsPython basics
Python basics
 
Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python Let’s Learn Python An introduction to Python
Let’s Learn Python An introduction to Python
 

Similar to Python and You Series

Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .tarunsharmaug23
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3Ahmet Bulut
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxShivamDenge
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfdata2businessinsight
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptxNileshBorkar12
 
presentation_intro_to_python
presentation_intro_to_pythonpresentation_intro_to_python
presentation_intro_to_pythongunanandJha2
 
presentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptpresentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptMohitChaudhary637683
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxcargillfilberto
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxdrandy1
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxmonicafrancis71118
 
Functions in C++
Functions in C++Functions in C++
Functions in C++home
 

Similar to Python and You Series (20)

Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Functions in Python Syntax and working .
Functions in Python Syntax and working .Functions in Python Syntax and working .
Functions in Python Syntax and working .
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Programming with Python - Week 3
Programming with Python - Week 3Programming with Python - Week 3
Programming with Python - Week 3
 
Shivam PPT.pptx
Shivam PPT.pptxShivam PPT.pptx
Shivam PPT.pptx
 
Government Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptxGovernment Polytechnic Arvi-1.pptx
Government Polytechnic Arvi-1.pptx
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Automation Testing theory notes.pptx
Automation Testing theory notes.pptxAutomation Testing theory notes.pptx
Automation Testing theory notes.pptx
 
presentation_intro_to_python
presentation_intro_to_pythonpresentation_intro_to_python
presentation_intro_to_python
 
presentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.pptpresentation_intro_to_python_1462930390_181219.ppt
presentation_intro_to_python_1462930390_181219.ppt
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
 
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docxCOMM 166 Final Research Proposal GuidelinesThe proposal should.docx
COMM 166 Final Research Proposal GuidelinesThe proposal should.docx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 

Recently uploaded

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 

Recently uploaded (20)

Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 

Python and You Series

  • 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__
  • 8. Data Types and Containers  Integer <type 'int'>  Float <type 'float'>  Boolean <type 'bool'>  Long <type 'long'>  String <type 'str'>  Unicode Strings <type 'unicode'>  List <type 'list'>  Tuple <type 'tuple'>  Dictionary <type 'dict'>  Sets <type 'set'>
  • 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]
  • 17. Functions  Defining Functions  Function Arguments (Default, keyword, Variable)  Documenting Functions
  • 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!
  • 26. Day 2 Python I/O|CSV , Configuration File Handling| Excel Connectivity| Modules
  • 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
  • 30. Exercises Reading and Writing CSV files Reading and Writing Configuration files Reading and Writing Excel Files
  • 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
  • 44. Day 4 XML Processing Regular Expression| DB Connectivity
  • 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