SlideShare une entreprise Scribd logo
1  sur  99
Python Programming
ASDT
Introduction
• Python was conceived in the late 1980s and its
implementation was started in December
1989 by Guido van Rossum at CWI (National
Research Institute for Mathematics and
Computer Science, located at the Science Park
Amsterdam in the Netherlands)
• Python 2.0 was released on 16 October 2000,
with many major new features including a full
garbage collector and support for unicode.
• Python 3.0, a major, backwards-incompatible
release, was released on 3 December2008
after a long period of testing.
• Many of its major features have also been
back ported to the backwards-compatible
Python 2.6 and 2.7.
• Python is a general-purpose, high-level
programming language whose design
philosophy emphasizes code readability.
• Python's syntax allows programmers to
express concepts in fewer lines of code than
would be possible in languages such as C, and
the language provides constructs intended to
enable clear programs on both a small and
large scale.
• Python supports multiple programming paradigms, including
object-oriented, imperative and functional programming
styles.
• It features a fully dynamic type system and automatic
memory management, similar to that of Scheme, Ruby, Perl
and Tclm and has a large and comprehensive standard library.
• Like other dynamic languages, Python is often used as a
scripting language, but is also used in a wide range of non-
scripting contexts.
• Using third-party tools, Python code can be packaged into
standalone executable programs. Python interpreters are
available for many operating systems.
features
• Python is a general-purpose(not domain-specific), high-level
programming language
• Design philosophy of Python emphasizes code readability
• Python combine remarkable power with very clear syntax
• Python standard library is large and comprehensive
• Its use of indentation for block delimiters is unique among
popular programming languages
• Python supports multiple programming paradigms , primarily
but not limited to object-oriented, imperative and, to a lesser
extent, functional programming styles.
• It features a fully dynamic type system and automatic memory
management, similar to that of scheme Ruby, Perl and Tcl.
• Python is used as a scripting language but is also used in a
wide range of non-scripting contexts.
• Python interpreters are available for many operating systems.
• The reference implementation of python is free and open
source software and has a community-based development
model
• Cpython is managed by the non-profit Python Software
Foundation
• Python uses dynamic typing and a combination of reference
counting and a cycle-detecting garbage collector for memory
management.
• An important feature of Python is dynamic name resolution
(late binding), which binds method and variable names during
program execution.
Python language implementations
• CPython is the default, most-widely used
implementation of the python programming
language, its written in C.
• Jython successor of JPython, is an implementation of
the Python programming language written in Java.
• Jython includes almost all of the modules in the
standard Python programming language distribution
Jython compiles to Java Byte Code.
• IronPython is an implementation of the Python
programming language targetting the .Net
Framework.
Zen of python
• Long time Pythoneer Tim Peters succinctly
channels the BDFL's guiding principles for
Python's design into 20 aphorisms, only 19 of
which have been written down.
• Van Rossum is Python's principal author, and
his continuing central role in deciding the
direction of Python is reflected in the title
given to him by the Python community,
Benevolent Dictator for Life (BDFL).
Zen of python…
• The core philosophy of the language is summarized
by the document "PEP 20 (The Zen of Python)",
which includes aphorisms such as….
• PEP contains the index of all “Python Enhancement
Proposals”, known as PEPs. PEP numbers are
assigned by the PEP editors, and once assigned are
never changed.
• Latest Pep number is 208 specifies the Reworking the
Coercion Model.
Zen…
https://pydanny-event-notes.readthedocs.org/en/latest/PyconAU2011/zen_of_python.html
•Beautiful is better than ugly.
def gcd(a,b): while b != 0: a, b = b, a % b return a
•Explicit is better than implicit.
File openings are not that explicit, The : in Python is lovely and explicit
•Simple is better than complex.
Something simple is easily knowable
Something complex is not
Automatic memory management means code is simpler
That we can define getter/setters and override existing ones in Python is
awesome.
Getting length of objects is simple in python:
l = [1,2,3,4,5,6,7,8] len(l)
• Complex is better than complicated.
• Flat is better than nested.
Inheritance flattening
Keep object inheritance shallow
Multiple inheritance keeps things shallow but things get more complex
Break up complex structure
Keep your if/elif/else use as light as possible
Smaller code == Better code
• Sparse is better than dense.
Is this a style guide thing?
whitespace?
naming standards
• Readability counts.
Readability is the number 1 reason why organizations select Python
if (x == y);
{ // logic
};
// a day wasted
• Special cases aren't special enough to break the
rules. Everything is an object
• Although practicality beats purity
Sometimes the rules need to be broken:
>>> class Two(int): ... pass ...
>>> print(Two(1)) 1
>>> Two.__str__ = lambda x: '2'
>>> print(Two(1)) 2
• Errors should never pass silently
Errors should not be fatal
Don’t blame the user for bugs in Python
• Check out except Exception at the bottom!
logging.exception(error) captures the entire error to the logs!
try:
handle_a_client()
except socket.error, e:
log.warning('client went away: %s', e)
except Exception, e:
logging.exception(e) # This captures the whole traceback!!!
• In the face of ambiguity, refuse the temptation to
guess.
1 + '1' # blows up in Python, not in other languages
# We like this behavior!
Also, remove the ambiguity and whack some parenthesis
• There should be one - and preferably only one-
obvious way to do it
– Protocols:
• DB API
• WSGI
• File API
• Although that way may not be obvious at first unless
you’re Dutch
– Guido can be quirky
– Community feedback keeps BDFL in check
• Now is better than never
– Fix the problem now
– Try it in your shell, and your tests
– Perfection is the enemy of the good
– Python 3 was years in the making, but much less than Perl 6.
• Although never is often better than right now.
– Things that ain’t gonna happen
– Adding ‘?’ to identifiers in Python
• If the implementation is hard to explain, it’s a bad
idea.
– If you can’t say it, don’t do it
• If the implementation is easy to explain, it may be a
good idea.
– Just because you can explain your idea, if it has no point then it
shouldn’t be included.
• Namespaces are one honking great idea – let’s do
more of those!
– locals > nonlocals > globals > builtins
– Me (pydanny) loves this about Python
Python interpretter
• Invoking python interpreter
• The interpreter is usually installed as
/usr/bin/python
• On windows ..C:python27
• Set path=%path%;C:python27
• End of file character is control-Z on win ,in linux it
is ctrl-D
Zen in conclusion
• Unless explicitly silenced. In the facse 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!
• Argument Passing:-
Use sys.argv to retrieve arguments
– Sys.argv[0] is the python command file name
– Sys.argv[1] is the first argument
– Sys.argv[2] the second argument etc
#argument passing
Import sys
Print “Number of arguments”,len(sys.argv)
If len(sys.argv) > 1:
print “first arguement”, sys.argv[1]
else:
print “No argument passed”
Executable python scripts
• On unix systems, python can be made directly
executable, like shell scripts, by putting the
line
#! /usr/bin/env python
• Use command “chmod +x myfile.py” to make
python file as executable file
• #! /usr/bin/env python
Print “hello world”
Source code encoding
• For using non ASCII charactors in your python
program use
# -*- coding: iso-8859-1 -*-
#! /usr/bin/env python
# -*- coding: iso-8859-1 -*-
print “hello world”
Python Data types
• In python every thing is an object, including a
numeric value is also an object
• Variable is a place holder to store anything
for example
a=7
b=893.34
c=”hello world”
d=[45,78,”hello”]
e=MyClass()
f={'name':,'jack','age':,18}
Numbers
Myvar=7
Myvar=433.89
myvar=343434343L
Expression
Myvar=78*(32+34) +34**3
• String
mystring='hello'
• mystring1=”hello world”
• Mystring2=”””hello world”””
• Mystr='''hello world'''
>>>len(mystr)
>>>mystr.upper()
>>>mystr.title() 'Hello World'
>>>mystr.split(' ') ['Hello','World']
>>>mystr.zfill(20) '000000000Hello World'
>>mystr.rjust(12) ' Hello World'
>>>mystr.ljust(12) 'Hello World '
• myvar=”hello world”
>>>myvar[0] 'H'
>>>myvar[1] 'e'
>>>myvar[8] 'r'
>>>myvar[-1] 'd'
>>>myvar[-2] 'l'
>>>myvar[2:] 'llo world”
>>>myvar[5:] “ world”
>>>myvar[:-2] “hello wor”
>>>myvar[2:-2] 'llo wor”
• Myvar*3 'Hello worldHello worldHello world'
• Myvar + “ok123” 'Hello Worldok123'
Myvar='Hello World'
Print myvar.upper() #HELLO WORLD
Print myvar*2 #”Hello worldHello World”
Print myvar.split(' ') # ['Hello','World']
a=myvar.lower().replace(' ', '')
Print a*4
#
helloworldhelloworldhelloworldhelloworld
List
>>>lst=['29',34.43,'grabber',95]
>>>lst[2] #'grabber'
>>> del lst[2] # removes item 2
>>>lst #['29',34.43,95]
>>>lst.append('help')
>>>lst #['29',34.43,95,'help']
>>>lst[0] # '29'
>>>lst[-1] #'help'
>>>lst[1:-1] #[45,2]
>>>lst*2 #['29',34.43,95,'help','29',34.43,'help']
>>>lst +[100,200] #['29',34.43,'help',100,200]
List Methods
append(x) Add x to the end of the list
extend(L) Add all items in sequence L to the
end of list
insert(i,x) insert x at a position i
remove(x) remove first item equal to x
pop(i) remove item at position i
Pop() remove item at the end of list
index(x) return index of first item equal to x
count(x) count occurances of x
Dictionaries
>>> a={'abc':24.5,'mo': 'fo', 'answer':90}
>>>a['abc'] #24.5
>>>a['mo'] #'fo'
>>>a['answer'] #90
>>>a.keys() #['answer','mo','abc']
>>>a.values() #[90,'fo',24.5]
>>>a.has_key('abc') #True
>>>a.has_key('xyz') #false
>>>a.get('abc',0) #24.5
>>>a.get('xyz'0) +0
>>>a.items() #[('answer',90),('y',77),('mo','fo'),('abc',24.5)]
>>>a #{'answer':90,'mo':'fo','abc':24.5}
>>>a.update({'x':67,'y':77})
>>>a
#{'answer':90,'y':77,'mo':'fo','abc':24.5,'x':67}
>>>dir(a) # can apply on the dictionary a
['clear','copy','fromkeys','get','has_key','items','i
teritems','iterkeys','itemvalues','keys','pop','p
opitem','setdefault','update','values','viewite
ms','viewkeys','viewvalues']
>>>a.pop('x') #67
>>>a
#{'answer':90,'y':77,'mo':'fo','abc':24.5}
>>>a.pop('y') #77
>>>a
{'answer':90,'mo':'fo','abc':24.5}
Input Output
Print
Print 'Hello'
Print 'world'
Print 'hello world'
input
a=input(“enter an integer value:”)
#Enter an integer value:89
Print a
#89
>>> a=raw_input(“enter a string:”)
#Enter a string:Python
>>>Print a
#python
format
Python uses c language printf style to format strings,use the
same syntax of printf for string formating
>>>a=”Name=%s and age=%d” %('jack',19)
>>>Print a
#Name=Jack and age=19
Built in functions
>>>dir()
['__builtins__','__doc__','__name__','__package__']
>>>dir(__builtins__)
['abs','all','any','apply','basestring','bin','bool','buffer','bytearray',
'bytes','callable','char','classmethod','cmp','coerce','compile','
complex','copyright','credits','delattr','dict'.................... ......... ]
Builtins-continued
>>>round(7.6) #8.0
>>>round(7.4) #7.0
>>>abs(-78) #78
>>int(“67”) #67
>>>len(“hello world”)#11
>>>min(78,6,3,4,90) #3
>>>max(78,6,3,4,90) #90
>>>range(10) # [0,1,2,3,4,5,6,7,8,9]
>>>range(10,20)
>>>a=78
>>>b=90
>>>c=eval(“a+b”)
>>>c #168
>>>basket=['apple','orange','apple','pear','orange','banana']
>>>list(set(basket))
['orange','pear','apple','banana']
>>>questions=['name','quest','favourite color']
>>>answers=['lancelot','the holy grail','blue']
>>>zip(questions,answers)
[('name','lancelot'),('quest','the holy grail'),('favorite color','blue')]
The for loop
The for loop in python has the ability to iterate
over the items of any sequence such as a list or
a string.
For i in range(6):
Print i
##0 1 2 3 4 5
For i in range(1,10,2):
Print i # 1 3 5 7 9
A=['alpha','beta','gama','delta']:
For i in a:
Print i
# alpha beta gama delta
For i in range(100):
if i < 50: continue
print i
if i ==55: break
# 50 51 52 52 53 54 55
a=['tic','tac','toe']
for i,v in enumerate(a):
Print i, v
# 0 tic
#1tac
#2toe
X=1
While true:
if x>10: break
print x
x=x+2
# 1 3 5 7 9
a=[[1,2,3],[4,5,6],[7,8,9]]
for list in a:
For x in list:
print x # 1 2 3 4 5 6 7 8 9
string=”hello world”
for x in string:
print x
# h e l l o w o r l d
import time
start =time.clock()
for x in range(1000000):
pass
stop = time.clock()
While :-The while loop continues until the expression
becomesfalse.the expression has to be a logical expression and
must return either a true or a false value.
While expression:
statement(s)
#! /usr/bin/python
count=0
while (count<9):
print 'the count is :' , count
count =count+1
Print “good bye!”
Functions
• Python everything is an object
• A callable object is an object that can accept some
arguments(parameters) and return an object.
• Functions can be stored in any variable,list or dictionary,just
like integers in c language
• A function is the simplest callable object in python
Function definition
Def hello1():
Print “hello world”
Return
Def hello2():
***hello world function***
Print “hello world”
Return
Hello1()
Hello2()
Function is a value which can be stored in any
variable
a=hello1
b=hello2
a()
b()
Print dir(b)
Print b.func_name
Print b.func_doc
• Function Arguments
• You can call a function by using the following
types of formal arguments:-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
• Syntax
• Def functionname(parameters):
“function-docstring”
function-suite
return expression
Ex:
Def myfn(a,b):
C=a*b
Return c
D=myfn(8,9)
Print d
Function with default value
• Def myfn(a,b=7):
C=a*b
return c
D=myfn(8,9)
Print d
E=myfn(8)
Print e
Function with variable number of arguments
Def print (format,*args):
out=format % args
Print out
Printf(A=%08.3f b=%d c=%dn”,34.89,56,78)
# a=0034.890 B=56 c=78
Def pr(*a):
Print len(a)
Print a
Pr(67,78)
Pr(6,8,9) # 2 (67,78)
3 (6,8,9)
Function with keyword arguments
Functions can also be called keyword arguments of the form
keyword=value.
Def mydict(var,**dict):
Print “var :” var
keys=dict.keys()
values=dict.values()
Print keys
Print values
Return
Mydict(78,alpha=34,beeta=89,gama='koil')
#var:78
['alpha','beeta','gama'] [34,89,'koil']
Function can return more than one value:-
Def xyz(a,b):
c=a+b
d=a-b
e =a*b
return c,d,e
x,y,z=xyz(5,6)
Print x
Print y
Print z#11 -1 30
Anonymous functions
You can use the lambda keyword to create small
anonymous functions.These functions are
called anonymous because they are not
declared in the standard manner by using the
def keyword
Syntax
Lambda[arg1 [,arg2,…..argn]]:expression
• Python supports the creation of anonymous
functions (i.e. functions that are not bound to
a name) at runtime, using a construct called
"lambda". This is not exactly the same as
lambda in functional programming languages,
but it is a very powerful concept that's well
integrated into Python and is often used in
conjunction with typical functional concepts
like filter(), map() and reduce().
• #!/usr/bin/python
• # Function definition is here
sum = lambda arg1, arg2: arg1 + arg2;
# Now you can call sum as a function
print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
• This would produce following result:
Value of total : 30
Value of total : 40
• Ex:2
• >>> def make_incrementor (n): return lambda
x: x + n
>>>
>>> f = make_incrementor(2)
>>> g = make_incrementor(6)
>>>
>>> print f(42), g(42)
o/p :44 48
>>>
>>> print make_incrementor(22)(33)
55
• Ex3:>>> def make_incrementor (n): return lam
bda x: x + n
>>>
>>> f = make_incrementor(2)
>>> g = make_incrementor(6)
>>>
>>> print f(42), g(42)
44 48
>>>
>>> print make_incrementor(22)(33)
55
Date and time
• Time module:- in time module the function
time.time() returns the current system time in
ticks since 12.00am,Jan 1 1970.The “tick”
floating-point numbers in units of seconds.
• Import time
ticks=time.time()
print “number of ticks since 12:00am,january
1,1970:”,ticks
Getting current time
• Import time
Localtime=time.localtime(time.time())
Print list(localtime)
Output can be in the following mode
2012,02,07,12,30,3,328,0]
Index field values
0 4-digit year 2008
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 61(60 or 61 are leap-
seconds)
6 Day of Week 0 to 6(0 is Monday)
7 Day of Year 1 to 366(julian day)
8 Daylight savings -1,0,1,-1 means library
determines DST
How to install modules
• In linux tar –zxvf module-name.tar.gz
cd module-name
python setup.py install
classes
• Compared with other programming
languages,Pythons class mechanism adds
classes with a minimum of new syntax and
semantics.
• Python classes provides all the standard
features of object oriented programming
• The class inheritance mechanism allows
multiple base classes
• A derived class can override any methods of
its base class or classes
• A method can call the method of a base class
with the same name.
• Objects can contain arbitrary amounts and
kinds of data
• Class are created at runtime, and can be
modified further after creation
• In c++ terminology,normally clas members are
public
• All member functions are virtual
• Classes themselves are objects.This provides
semantics for importing and renaming
• Built-in types can be used as base classes for
extension by the user.
• Most built-in operation with special
syntax(arithemetic,subscripting) can be
redefined for class instances.
• class HelloWorld:
def __init__(self):
self.outText = "Hello World"
def printOut(self):
print self.outText
myHelloWorld = HelloWorld()
myHelloWorld.printOut()
• When the object instance "myHelloWorld" of
object type "HelloWorld" is initialized (where
"myHelloWorld" is assigned as type
"HelloWorld") the initializer is called, in this
case setting "self.outText" to "Hello World".
If you've ever used C++, it's a constructor. You
use it to create the initial conditions that the
object should have (default values and such).
It can also take parameters after "self" like any
other function.
• Just as a side note:
self is actually just a randomly chosen word,
that everyone uses, but you could also use
this, foo, or myself or anything else you want,
it's just the first parameter of every non static
method for a class. This means that the word
self is not a language construct but just a
name
• >>> class A:
... def __init__(s):
... s.bla = 2
...
>>>
>>> a = A()
>>> a.bla
2
The constructor and destructor
functions
Regular Expression
Regular Expression
• Regular expressions are also called Res or
regexes or regex patterns.
• They are essentially a tiny, highly specialized
programming language embedded inside
python and made available through the re
module
• They uses some special characters for pattern
matching
• A regular expression is a special sequence of characters that
helps you match or find other strings or sets of strings, using a
specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world.
• The module re provides full support for Perl-like regular
expressions in Python. The re module raises the exception
re.error if an error occurs while compiling or using a regular
expression.
• We would cover two important functions, which would be
used to handle regular expressions. But a small thing first:
There are various characters, which would have special
meaning when they are used in regular expression. To avoid
any confusion while dealing with regular expressions, we
would use Raw Strings as r'expression'.
Special characters
• ‘.’(dot) in the default mode, this matches any
character except a newline. If the dotall flag
has been specified, this matches any character
including newline.
• ‘^’(caret) matches the start of the string, and
in multiline mode also matches immediately
after each newline.
• ‘$’ matches the end of the string or just before
the newline at the end of the string, and in
multiline mode also matches before a
newline.
• ‘*’ causes the resulting RE to match 0 or more
repetitions of the preceding RE, as many
repetitions as are possible. ab* will match a,
ab or a followed by any number of b’s
• ‘+’ causes the resulting RE to match 1 or more
repetitions of the preceding RE.ab+ will match
a followed by any non-zero number of b’s;it
will not match just a.
• ‘?’ causes the resulting RE to match 0 or 1
repetitions of the preceding RE
• {m}: Specifes that exactly m copies of the
previous RE should be matched; fewer
matches cause the entire RE not to match. For
example, a{6} will match exactly six 'a'
characters, but not five
• {m,n}: causes resulting RE to match from m to
n repetitions of the preceding RE, attempting
to match as many repetitions as possible. For
example, a{3,5} will match from 3 to 5 'a'
characters. Omitting m species a lower bound
of zero, and omitting n species an infinite
upper bound.
• number:- matches the contents of the group
of the same number. For example, (.+)1
matches the ‘the the’ or ‘55 55’, but not ‘ the
end’ string.
• d :- when Unicode flag is not specified
,matches any decimal digit ; this is equivalent
to the set [0-9].
• s :- when Unicode flag is not specified
,matches any white space character.
• s$:-when LOCALE and unicode flags are not
specified ,matches any non-white space
character.
• w:-matches any alphanumeric character and
the underscore. Equivalent to the set of [a-z A-
Z 0-9 _]
• Findall :-It searches all patterns and returns as
a list.
• Ex:
• >>> import re
• >>>a=“hello 234789 world 63678 ok 1 ok 1115
alpha 88 beta 999g”
• re.findall(“d+”,a) results all digits from the
above string.
• D is any character other than numeric
character
• D+ matches data other than ‘numeric data’
• Re.findall(“D+”,a) results all data other than
numeric data.
• {2,} matches two or more numeric characters
• "[ai]" represent any one of the character 'a' or
'i'
• "p[ai]t" matchs pat or pit
Matching and searching
• Python offers 2 different primitive operations
based on regular expressions :match checks
for a match only at the beginning of the string,
while search checks for a match anywhere in
the string.
The match Function
• This function attempts to match RE pattern to string
with optional flags.
Here is the syntax for this function −
re.match(pattern, string, flags=0)
Here is the description of the parameters:
Parameter Description
pattern This is the regular expression to be matched.
string This is the string, which would be searched to
match the pattern at the beginning of string.
flags You can specify different flags using bitwise OR (|).
The re.match function returns a match object on success, None on failure.
We usegroup(num) or groups() function of match object to get matched
expression.
• Example
#!/usr/bin/python
import re line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
When the above code is executed, it produces following result −
• matchObj.group() : Cats are smarter than dogs
• matchObj.group(1) : Cats
• matchObj.group(2) : smarter
• The search Function
This function searches for first occurrence of RE pattern within
string with optional flags.
• Here is the syntax for this function:
re.search(pattern, string, flags=0)
Match Object Methods Description
group(num=0) This method returns entire match
(or specific subgroup num)
groups() This method returns all matching
subgroups in a tuple (empty if there
weren't any)
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1) print
"searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"
When the above code is executed, it produces following result −
• matchObj.group() : Cats are smarter than dogs
• matchObj.group(1) : Cats
• matchObj.group(2) : smarter
• Search and Replace
One of the most important re methods that use regular
expressions is sub.
Syntax
re.sub(pattern, repl, string, max=0)
• This method replaces all occurrences of the RE pattern in
string with repl, substituting all occurrences unless max
provided. This method returns modified string.
#!/usr/bin/python
import re
phone = "2004-959-559 # This is Phone Number"
# Delete Python-style comments
num = re.sub(r'#.*$', "", phone)
print "Phone Num : ", num
# Remove anything other than digits
num = re.sub(r'D', "", phone)
print "Phone Num : ", num
When the above code is executed, it produces the following
result −
• Phone Num : 2004-959-559
• Phone Num : 2004959559
Database
• Installing mysql in linux
• In terminal=>
#Sudo apt-get update
#Sudo apt-get upgrade
#Sudo apt-get install mysql-server
#Sudo apt-get install python-mysqldb
Commands to get mysql prompt
• The standard tool for interacting with MySQL
is the mysql client program. To get started,
issue the following command at your prompt:
• Mysql –u root -p
• You will be prompted to enter the root MySQL
user's password. Enter the password you
assigned when you installed MySQL, and you'll
be presented with the MySQL monitor display:
• Welcome to the MySQL monitor.
Commands end with ; or g.
Your MySQL connection id is 41
Server version: 5.4.37-1 ubuntu 12. 4 L
TS(Ubuntu)
mysql>
• SQL is actually three separate sub-languages
• ● DDL: Data Definition Language
• – Used to create and maintain database structures
• ● DCL: Data Control Language
• – Used to specify who gets which access to what
• ● DML: Data Manipulation Language
• – Day-to-day query and update of the data model
• – Probably about 99.9% of what we do with databases!
• Data Control Language
• GRANT SELECT, UPDATE (name, address) ON emp TO steve
• ● This is almost exclusively used by the DBA
• ● Not covered in the remainder of this tutorial
Create database and users
• Let's create a database and assign a user to it.
Issue the following commands at the MySQL
prompt:
• CREATE DATABASE testdb;
• CREATE USER 'testuser'@localhost IDENTIFIED
BY 'CHANGEME';
• GRANT ALL PRIVILEGES ON testdb.* TO
'testuser'@localhost;
• exit
Create table
• You can create and populate the example
table with these statements:
• mysql -u testuser -p
Mysql>USE testdb;
Mysql>CREATE TABLE shop (article INT(4)
UNSIGNED ZEROFILL DEFAULT '0000' NOT
NULL,dealer CHAR(20) DEFAULT '' NOT
NULL,price DOUBLE(16,2) DEFAULT '0.00' NOT
NULL, PRIMARY KEY(article, dealer));
Insert -select
Mysql>INSERT INTO shop
VALUES(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'
B',1.45),(3,'C',1.69),(3,'D',1.25),(4,'D',19.95);
Mysql>SELECT * FROM shop;
Python DB API
Designed to give Python programs access
to RDBMS features using standard calls.
Each compliant module interfaces to a
particular RDBMS engine
Some Well-Known Database Modules
Module Database
MySQLdb MySQL
cx_Oracle Oracle
psycopg PostgreSQL
psycopg2 PostgreSQL
mxODBC Any RDBMS with ODBC drivers
kinterbasdb Firebird/Interbase
adodbapi Windows ADO data sources
pydb2 DB/2
MySQLdb module
• MySQLdb is a thin Python wrapper around
mysql. It is compatible with the Python DB
API, which makes the code more portable.
Using this model is the preferred way of
working with the MySQL.
• Example
• mysql> create user 'testuser'@'localhost'
• identified by 'xyz123';
• mysql> create database testdatabase;
• mysql> grant all on *.* to 'testuser'@'localhost';
• mysql> use testdatabase;
• mysql> create table student(Id INT PRIMARY KEY
• AUTO_INCREMENT, Name VARCHAR(25));
• mysql> insert into student (name) values ('Tom'),
• (‘Ren'), ('Harry');
Database fetch using fetchall()
import MySQLdb as mdb
import sys
con=mdb.connect(‘localhost’,’usrname’,’xyz123’,’testdatabase’);
if con:
cur=con.cursor()
cur.execute(“select * from student”)
rows=cur.fetchall()
for row in rows:
print row
Exception in datbase
Import MySQLdb as mdb
Import sys
Try:
conn=mdb.connect(‘localhost’,’testuser’,’passwd’,’testdb’);
cursor=conn.cursor()
cursor.execute(“Delete from writers where id=5”)
cursor.execute(“delete from writers where id=4”)
conn.commit()
Except mdb.Error, e:
conn.rollback()
print “Error %d: %s” %(e.args[0],e.args[1])
sys.exit(1)
Cursor.close()
Conn.close()

Contenu connexe

Similaire à Python Programming1.ppt

Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 

Similaire à Python Programming1.ppt (20)

python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptx
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)
 
What is python
What is pythonWhat is python
What is python
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx4_Introduction to Python Programming.pptx
4_Introduction to Python Programming.pptx
 
python classes in thane
python classes in thanepython classes in thane
python classes in thane
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming Basics
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
 
Python presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, BiharPython presentation of Government Engineering College Aurangabad, Bihar
Python presentation of Government Engineering College Aurangabad, Bihar
 
An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()An Introduction To Python - Python, Print()
An Introduction To Python - Python, Print()
 
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 basics
Python basicsPython basics
Python basics
 
Unit1 pps
Unit1 ppsUnit1 pps
Unit1 pps
 
Python_Introduction&DataType.pptx
Python_Introduction&DataType.pptxPython_Introduction&DataType.pptx
Python_Introduction&DataType.pptx
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 

Dernier

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Python Programming1.ppt

  • 2. Introduction • Python was conceived in the late 1980s and its implementation was started in December 1989 by Guido van Rossum at CWI (National Research Institute for Mathematics and Computer Science, located at the Science Park Amsterdam in the Netherlands) • Python 2.0 was released on 16 October 2000, with many major new features including a full garbage collector and support for unicode.
  • 3. • Python 3.0, a major, backwards-incompatible release, was released on 3 December2008 after a long period of testing. • Many of its major features have also been back ported to the backwards-compatible Python 2.6 and 2.7.
  • 4. • Python is a general-purpose, high-level programming language whose design philosophy emphasizes code readability. • Python's syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C, and the language provides constructs intended to enable clear programs on both a small and large scale.
  • 5. • Python supports multiple programming paradigms, including object-oriented, imperative and functional programming styles. • It features a fully dynamic type system and automatic memory management, similar to that of Scheme, Ruby, Perl and Tclm and has a large and comprehensive standard library. • Like other dynamic languages, Python is often used as a scripting language, but is also used in a wide range of non- scripting contexts. • Using third-party tools, Python code can be packaged into standalone executable programs. Python interpreters are available for many operating systems.
  • 6. features • Python is a general-purpose(not domain-specific), high-level programming language • Design philosophy of Python emphasizes code readability • Python combine remarkable power with very clear syntax • Python standard library is large and comprehensive • Its use of indentation for block delimiters is unique among popular programming languages • Python supports multiple programming paradigms , primarily but not limited to object-oriented, imperative and, to a lesser extent, functional programming styles. • It features a fully dynamic type system and automatic memory management, similar to that of scheme Ruby, Perl and Tcl.
  • 7. • Python is used as a scripting language but is also used in a wide range of non-scripting contexts. • Python interpreters are available for many operating systems. • The reference implementation of python is free and open source software and has a community-based development model • Cpython is managed by the non-profit Python Software Foundation • Python uses dynamic typing and a combination of reference counting and a cycle-detecting garbage collector for memory management. • An important feature of Python is dynamic name resolution (late binding), which binds method and variable names during program execution.
  • 8. Python language implementations • CPython is the default, most-widely used implementation of the python programming language, its written in C. • Jython successor of JPython, is an implementation of the Python programming language written in Java. • Jython includes almost all of the modules in the standard Python programming language distribution Jython compiles to Java Byte Code. • IronPython is an implementation of the Python programming language targetting the .Net Framework.
  • 9. Zen of python • Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down. • Van Rossum is Python's principal author, and his continuing central role in deciding the direction of Python is reflected in the title given to him by the Python community, Benevolent Dictator for Life (BDFL).
  • 10. Zen of python… • The core philosophy of the language is summarized by the document "PEP 20 (The Zen of Python)", which includes aphorisms such as…. • PEP contains the index of all “Python Enhancement Proposals”, known as PEPs. PEP numbers are assigned by the PEP editors, and once assigned are never changed. • Latest Pep number is 208 specifies the Reworking the Coercion Model.
  • 11. Zen… https://pydanny-event-notes.readthedocs.org/en/latest/PyconAU2011/zen_of_python.html •Beautiful is better than ugly. def gcd(a,b): while b != 0: a, b = b, a % b return a •Explicit is better than implicit. File openings are not that explicit, The : in Python is lovely and explicit •Simple is better than complex. Something simple is easily knowable Something complex is not Automatic memory management means code is simpler That we can define getter/setters and override existing ones in Python is awesome. Getting length of objects is simple in python: l = [1,2,3,4,5,6,7,8] len(l)
  • 12. • Complex is better than complicated. • Flat is better than nested. Inheritance flattening Keep object inheritance shallow Multiple inheritance keeps things shallow but things get more complex Break up complex structure Keep your if/elif/else use as light as possible Smaller code == Better code • Sparse is better than dense. Is this a style guide thing? whitespace? naming standards
  • 13. • Readability counts. Readability is the number 1 reason why organizations select Python if (x == y); { // logic }; // a day wasted • Special cases aren't special enough to break the rules. Everything is an object
  • 14. • Although practicality beats purity Sometimes the rules need to be broken: >>> class Two(int): ... pass ... >>> print(Two(1)) 1 >>> Two.__str__ = lambda x: '2' >>> print(Two(1)) 2 • Errors should never pass silently Errors should not be fatal Don’t blame the user for bugs in Python • Check out except Exception at the bottom! logging.exception(error) captures the entire error to the logs! try: handle_a_client() except socket.error, e: log.warning('client went away: %s', e) except Exception, e: logging.exception(e) # This captures the whole traceback!!!
  • 15. • In the face of ambiguity, refuse the temptation to guess. 1 + '1' # blows up in Python, not in other languages # We like this behavior! Also, remove the ambiguity and whack some parenthesis • There should be one - and preferably only one- obvious way to do it – Protocols: • DB API • WSGI • File API
  • 16. • Although that way may not be obvious at first unless you’re Dutch – Guido can be quirky – Community feedback keeps BDFL in check • Now is better than never – Fix the problem now – Try it in your shell, and your tests – Perfection is the enemy of the good – Python 3 was years in the making, but much less than Perl 6. • Although never is often better than right now. – Things that ain’t gonna happen – Adding ‘?’ to identifiers in Python
  • 17. • If the implementation is hard to explain, it’s a bad idea. – If you can’t say it, don’t do it • If the implementation is easy to explain, it may be a good idea. – Just because you can explain your idea, if it has no point then it shouldn’t be included. • Namespaces are one honking great idea – let’s do more of those! – locals > nonlocals > globals > builtins – Me (pydanny) loves this about Python
  • 18. Python interpretter • Invoking python interpreter • The interpreter is usually installed as /usr/bin/python • On windows ..C:python27 • Set path=%path%;C:python27 • End of file character is control-Z on win ,in linux it is ctrl-D
  • 19. Zen in conclusion • Unless explicitly silenced. In the facse 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!
  • 20. • Argument Passing:- Use sys.argv to retrieve arguments – Sys.argv[0] is the python command file name – Sys.argv[1] is the first argument – Sys.argv[2] the second argument etc
  • 21. #argument passing Import sys Print “Number of arguments”,len(sys.argv) If len(sys.argv) > 1: print “first arguement”, sys.argv[1] else: print “No argument passed”
  • 22. Executable python scripts • On unix systems, python can be made directly executable, like shell scripts, by putting the line #! /usr/bin/env python • Use command “chmod +x myfile.py” to make python file as executable file • #! /usr/bin/env python Print “hello world”
  • 23. Source code encoding • For using non ASCII charactors in your python program use # -*- coding: iso-8859-1 -*- #! /usr/bin/env python # -*- coding: iso-8859-1 -*- print “hello world”
  • 24. Python Data types • In python every thing is an object, including a numeric value is also an object • Variable is a place holder to store anything for example a=7 b=893.34 c=”hello world” d=[45,78,”hello”] e=MyClass() f={'name':,'jack','age':,18}
  • 26. • String mystring='hello' • mystring1=”hello world” • Mystring2=”””hello world””” • Mystr='''hello world''' >>>len(mystr) >>>mystr.upper() >>>mystr.title() 'Hello World' >>>mystr.split(' ') ['Hello','World'] >>>mystr.zfill(20) '000000000Hello World' >>mystr.rjust(12) ' Hello World' >>>mystr.ljust(12) 'Hello World '
  • 27. • myvar=”hello world” >>>myvar[0] 'H' >>>myvar[1] 'e' >>>myvar[8] 'r' >>>myvar[-1] 'd' >>>myvar[-2] 'l' >>>myvar[2:] 'llo world” >>>myvar[5:] “ world” >>>myvar[:-2] “hello wor” >>>myvar[2:-2] 'llo wor” • Myvar*3 'Hello worldHello worldHello world' • Myvar + “ok123” 'Hello Worldok123'
  • 28. Myvar='Hello World' Print myvar.upper() #HELLO WORLD Print myvar*2 #”Hello worldHello World” Print myvar.split(' ') # ['Hello','World'] a=myvar.lower().replace(' ', '') Print a*4 # helloworldhelloworldhelloworldhelloworld
  • 29. List >>>lst=['29',34.43,'grabber',95] >>>lst[2] #'grabber' >>> del lst[2] # removes item 2 >>>lst #['29',34.43,95] >>>lst.append('help') >>>lst #['29',34.43,95,'help'] >>>lst[0] # '29' >>>lst[-1] #'help' >>>lst[1:-1] #[45,2] >>>lst*2 #['29',34.43,95,'help','29',34.43,'help'] >>>lst +[100,200] #['29',34.43,'help',100,200]
  • 30. List Methods append(x) Add x to the end of the list extend(L) Add all items in sequence L to the end of list insert(i,x) insert x at a position i remove(x) remove first item equal to x pop(i) remove item at position i Pop() remove item at the end of list index(x) return index of first item equal to x count(x) count occurances of x
  • 31. Dictionaries >>> a={'abc':24.5,'mo': 'fo', 'answer':90} >>>a['abc'] #24.5 >>>a['mo'] #'fo' >>>a['answer'] #90 >>>a.keys() #['answer','mo','abc'] >>>a.values() #[90,'fo',24.5] >>>a.has_key('abc') #True >>>a.has_key('xyz') #false >>>a.get('abc',0) #24.5 >>>a.get('xyz'0) +0 >>>a.items() #[('answer',90),('y',77),('mo','fo'),('abc',24.5)]
  • 32. >>>a #{'answer':90,'mo':'fo','abc':24.5} >>>a.update({'x':67,'y':77}) >>>a #{'answer':90,'y':77,'mo':'fo','abc':24.5,'x':67} >>>dir(a) # can apply on the dictionary a ['clear','copy','fromkeys','get','has_key','items','i teritems','iterkeys','itemvalues','keys','pop','p opitem','setdefault','update','values','viewite ms','viewkeys','viewvalues']
  • 34. Input Output Print Print 'Hello' Print 'world' Print 'hello world'
  • 35. input a=input(“enter an integer value:”) #Enter an integer value:89 Print a #89 >>> a=raw_input(“enter a string:”) #Enter a string:Python >>>Print a #python
  • 36. format Python uses c language printf style to format strings,use the same syntax of printf for string formating >>>a=”Name=%s and age=%d” %('jack',19) >>>Print a #Name=Jack and age=19
  • 38. Builtins-continued >>>round(7.6) #8.0 >>>round(7.4) #7.0 >>>abs(-78) #78 >>int(“67”) #67 >>>len(“hello world”)#11 >>>min(78,6,3,4,90) #3 >>>max(78,6,3,4,90) #90 >>>range(10) # [0,1,2,3,4,5,6,7,8,9] >>>range(10,20)
  • 40. The for loop The for loop in python has the ability to iterate over the items of any sequence such as a list or a string. For i in range(6): Print i ##0 1 2 3 4 5 For i in range(1,10,2): Print i # 1 3 5 7 9
  • 41. A=['alpha','beta','gama','delta']: For i in a: Print i # alpha beta gama delta For i in range(100): if i < 50: continue print i if i ==55: break # 50 51 52 52 53 54 55
  • 42. a=['tic','tac','toe'] for i,v in enumerate(a): Print i, v # 0 tic #1tac #2toe X=1 While true: if x>10: break print x x=x+2 # 1 3 5 7 9
  • 43. a=[[1,2,3],[4,5,6],[7,8,9]] for list in a: For x in list: print x # 1 2 3 4 5 6 7 8 9 string=”hello world” for x in string: print x # h e l l o w o r l d import time start =time.clock() for x in range(1000000): pass stop = time.clock()
  • 44. While :-The while loop continues until the expression becomesfalse.the expression has to be a logical expression and must return either a true or a false value. While expression: statement(s) #! /usr/bin/python count=0 while (count<9): print 'the count is :' , count count =count+1 Print “good bye!”
  • 45. Functions • Python everything is an object • A callable object is an object that can accept some arguments(parameters) and return an object. • Functions can be stored in any variable,list or dictionary,just like integers in c language • A function is the simplest callable object in python
  • 46. Function definition Def hello1(): Print “hello world” Return Def hello2(): ***hello world function*** Print “hello world” Return Hello1() Hello2()
  • 47. Function is a value which can be stored in any variable a=hello1 b=hello2 a() b() Print dir(b) Print b.func_name Print b.func_doc
  • 48. • Function Arguments • You can call a function by using the following types of formal arguments:- • Required arguments • Keyword arguments • Default arguments • Variable-length arguments
  • 49. • Syntax • Def functionname(parameters): “function-docstring” function-suite return expression Ex: Def myfn(a,b): C=a*b Return c D=myfn(8,9) Print d
  • 50. Function with default value • Def myfn(a,b=7): C=a*b return c D=myfn(8,9) Print d E=myfn(8) Print e
  • 51. Function with variable number of arguments Def print (format,*args): out=format % args Print out Printf(A=%08.3f b=%d c=%dn”,34.89,56,78) # a=0034.890 B=56 c=78 Def pr(*a): Print len(a) Print a Pr(67,78) Pr(6,8,9) # 2 (67,78) 3 (6,8,9)
  • 52. Function with keyword arguments Functions can also be called keyword arguments of the form keyword=value. Def mydict(var,**dict): Print “var :” var keys=dict.keys() values=dict.values() Print keys Print values Return Mydict(78,alpha=34,beeta=89,gama='koil') #var:78 ['alpha','beeta','gama'] [34,89,'koil']
  • 53. Function can return more than one value:- Def xyz(a,b): c=a+b d=a-b e =a*b return c,d,e x,y,z=xyz(5,6) Print x Print y Print z#11 -1 30
  • 54. Anonymous functions You can use the lambda keyword to create small anonymous functions.These functions are called anonymous because they are not declared in the standard manner by using the def keyword Syntax Lambda[arg1 [,arg2,…..argn]]:expression
  • 55. • Python supports the creation of anonymous functions (i.e. functions that are not bound to a name) at runtime, using a construct called "lambda". This is not exactly the same as lambda in functional programming languages, but it is a very powerful concept that's well integrated into Python and is often used in conjunction with typical functional concepts like filter(), map() and reduce().
  • 56. • #!/usr/bin/python • # Function definition is here sum = lambda arg1, arg2: arg1 + arg2; # Now you can call sum as a function print "Value of total : ", sum( 10, 20 ) print "Value of total : ", sum( 20, 20 ) • This would produce following result: Value of total : 30 Value of total : 40
  • 57. • Ex:2 • >>> def make_incrementor (n): return lambda x: x + n >>> >>> f = make_incrementor(2) >>> g = make_incrementor(6) >>> >>> print f(42), g(42) o/p :44 48 >>> >>> print make_incrementor(22)(33) 55
  • 58. • Ex3:>>> def make_incrementor (n): return lam bda x: x + n >>> >>> f = make_incrementor(2) >>> g = make_incrementor(6) >>> >>> print f(42), g(42) 44 48 >>> >>> print make_incrementor(22)(33) 55
  • 59. Date and time • Time module:- in time module the function time.time() returns the current system time in ticks since 12.00am,Jan 1 1970.The “tick” floating-point numbers in units of seconds. • Import time ticks=time.time() print “number of ticks since 12:00am,january 1,1970:”,ticks
  • 60. Getting current time • Import time Localtime=time.localtime(time.time()) Print list(localtime) Output can be in the following mode 2012,02,07,12,30,3,328,0]
  • 61. Index field values 0 4-digit year 2008 1 Month 1 to 12 2 Day 1 to 31 3 Hour 0 to 23 4 Minute 0 to 59 5 Second 0 to 61(60 or 61 are leap- seconds) 6 Day of Week 0 to 6(0 is Monday) 7 Day of Year 1 to 366(julian day) 8 Daylight savings -1,0,1,-1 means library determines DST
  • 62. How to install modules • In linux tar –zxvf module-name.tar.gz cd module-name python setup.py install
  • 63. classes • Compared with other programming languages,Pythons class mechanism adds classes with a minimum of new syntax and semantics. • Python classes provides all the standard features of object oriented programming • The class inheritance mechanism allows multiple base classes • A derived class can override any methods of its base class or classes
  • 64. • A method can call the method of a base class with the same name. • Objects can contain arbitrary amounts and kinds of data • Class are created at runtime, and can be modified further after creation • In c++ terminology,normally clas members are public • All member functions are virtual
  • 65. • Classes themselves are objects.This provides semantics for importing and renaming • Built-in types can be used as base classes for extension by the user. • Most built-in operation with special syntax(arithemetic,subscripting) can be redefined for class instances.
  • 66. • class HelloWorld: def __init__(self): self.outText = "Hello World" def printOut(self): print self.outText myHelloWorld = HelloWorld() myHelloWorld.printOut()
  • 67. • When the object instance "myHelloWorld" of object type "HelloWorld" is initialized (where "myHelloWorld" is assigned as type "HelloWorld") the initializer is called, in this case setting "self.outText" to "Hello World". If you've ever used C++, it's a constructor. You use it to create the initial conditions that the object should have (default values and such). It can also take parameters after "self" like any other function.
  • 68. • Just as a side note: self is actually just a randomly chosen word, that everyone uses, but you could also use this, foo, or myself or anything else you want, it's just the first parameter of every non static method for a class. This means that the word self is not a language construct but just a name
  • 69. • >>> class A: ... def __init__(s): ... s.bla = 2 ... >>> >>> a = A() >>> a.bla 2
  • 70. The constructor and destructor functions
  • 72. Regular Expression • Regular expressions are also called Res or regexes or regex patterns. • They are essentially a tiny, highly specialized programming language embedded inside python and made available through the re module • They uses some special characters for pattern matching
  • 73. • A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world. • The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression. • We would cover two important functions, which would be used to handle regular expressions. But a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.
  • 74. Special characters • ‘.’(dot) in the default mode, this matches any character except a newline. If the dotall flag has been specified, this matches any character including newline. • ‘^’(caret) matches the start of the string, and in multiline mode also matches immediately after each newline. • ‘$’ matches the end of the string or just before the newline at the end of the string, and in multiline mode also matches before a newline.
  • 75. • ‘*’ causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. ab* will match a, ab or a followed by any number of b’s • ‘+’ causes the resulting RE to match 1 or more repetitions of the preceding RE.ab+ will match a followed by any non-zero number of b’s;it will not match just a. • ‘?’ causes the resulting RE to match 0 or 1 repetitions of the preceding RE
  • 76. • {m}: Specifes that exactly m copies of the previous RE should be matched; fewer matches cause the entire RE not to match. For example, a{6} will match exactly six 'a' characters, but not five • {m,n}: causes resulting RE to match from m to n repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, a{3,5} will match from 3 to 5 'a' characters. Omitting m species a lower bound of zero, and omitting n species an infinite upper bound.
  • 77. • number:- matches the contents of the group of the same number. For example, (.+)1 matches the ‘the the’ or ‘55 55’, but not ‘ the end’ string. • d :- when Unicode flag is not specified ,matches any decimal digit ; this is equivalent to the set [0-9]. • s :- when Unicode flag is not specified ,matches any white space character. • s$:-when LOCALE and unicode flags are not specified ,matches any non-white space character.
  • 78. • w:-matches any alphanumeric character and the underscore. Equivalent to the set of [a-z A- Z 0-9 _] • Findall :-It searches all patterns and returns as a list. • Ex: • >>> import re • >>>a=“hello 234789 world 63678 ok 1 ok 1115 alpha 88 beta 999g” • re.findall(“d+”,a) results all digits from the above string.
  • 79. • D is any character other than numeric character • D+ matches data other than ‘numeric data’ • Re.findall(“D+”,a) results all data other than numeric data. • {2,} matches two or more numeric characters • "[ai]" represent any one of the character 'a' or 'i' • "p[ai]t" matchs pat or pit
  • 80. Matching and searching • Python offers 2 different primitive operations based on regular expressions :match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string.
  • 81. The match Function • This function attempts to match RE pattern to string with optional flags. Here is the syntax for this function − re.match(pattern, string, flags=0) Here is the description of the parameters: Parameter Description pattern This is the regular expression to be matched. string This is the string, which would be searched to match the pattern at the beginning of string. flags You can specify different flags using bitwise OR (|). The re.match function returns a match object on success, None on failure. We usegroup(num) or groups() function of match object to get matched expression.
  • 82. • Example #!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) if matchObj: print "matchObj.group() : ", matchObj.group() print "matchObj.group(1) : ", matchObj.group(1) print "matchObj.group(2) : ", matchObj.group(2) else: print "No match!!" When the above code is executed, it produces following result − • matchObj.group() : Cats are smarter than dogs • matchObj.group(1) : Cats • matchObj.group(2) : smarter
  • 83. • The search Function This function searches for first occurrence of RE pattern within string with optional flags. • Here is the syntax for this function: re.search(pattern, string, flags=0) Match Object Methods Description group(num=0) This method returns entire match (or specific subgroup num) groups() This method returns all matching subgroups in a tuple (empty if there weren't any)
  • 84. #!/usr/bin/python import re line = "Cats are smarter than dogs"; searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) if searchObj: print "searchObj.group() : ", searchObj.group() print "searchObj.group(1) : ", searchObj.group(1) print "searchObj.group(2) : ", searchObj.group(2) else: print "Nothing found!!" When the above code is executed, it produces following result − • matchObj.group() : Cats are smarter than dogs • matchObj.group(1) : Cats • matchObj.group(2) : smarter
  • 85. • Search and Replace One of the most important re methods that use regular expressions is sub. Syntax re.sub(pattern, repl, string, max=0) • This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string.
  • 86. #!/usr/bin/python import re phone = "2004-959-559 # This is Phone Number" # Delete Python-style comments num = re.sub(r'#.*$', "", phone) print "Phone Num : ", num # Remove anything other than digits num = re.sub(r'D', "", phone) print "Phone Num : ", num When the above code is executed, it produces the following result − • Phone Num : 2004-959-559 • Phone Num : 2004959559
  • 87. Database • Installing mysql in linux • In terminal=> #Sudo apt-get update #Sudo apt-get upgrade #Sudo apt-get install mysql-server #Sudo apt-get install python-mysqldb
  • 88. Commands to get mysql prompt • The standard tool for interacting with MySQL is the mysql client program. To get started, issue the following command at your prompt: • Mysql –u root -p • You will be prompted to enter the root MySQL user's password. Enter the password you assigned when you installed MySQL, and you'll be presented with the MySQL monitor display:
  • 89. • Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 41 Server version: 5.4.37-1 ubuntu 12. 4 L TS(Ubuntu) mysql>
  • 90. • SQL is actually three separate sub-languages • ● DDL: Data Definition Language • – Used to create and maintain database structures • ● DCL: Data Control Language • – Used to specify who gets which access to what • ● DML: Data Manipulation Language • – Day-to-day query and update of the data model • – Probably about 99.9% of what we do with databases! • Data Control Language • GRANT SELECT, UPDATE (name, address) ON emp TO steve • ● This is almost exclusively used by the DBA • ● Not covered in the remainder of this tutorial
  • 91. Create database and users • Let's create a database and assign a user to it. Issue the following commands at the MySQL prompt: • CREATE DATABASE testdb; • CREATE USER 'testuser'@localhost IDENTIFIED BY 'CHANGEME'; • GRANT ALL PRIVILEGES ON testdb.* TO 'testuser'@localhost; • exit
  • 92. Create table • You can create and populate the example table with these statements: • mysql -u testuser -p Mysql>USE testdb; Mysql>CREATE TABLE shop (article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL,dealer CHAR(20) DEFAULT '' NOT NULL,price DOUBLE(16,2) DEFAULT '0.00' NOT NULL, PRIMARY KEY(article, dealer));
  • 93. Insert -select Mysql>INSERT INTO shop VALUES(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,' B',1.45),(3,'C',1.69),(3,'D',1.25),(4,'D',19.95); Mysql>SELECT * FROM shop;
  • 94. Python DB API Designed to give Python programs access to RDBMS features using standard calls. Each compliant module interfaces to a particular RDBMS engine
  • 95. Some Well-Known Database Modules Module Database MySQLdb MySQL cx_Oracle Oracle psycopg PostgreSQL psycopg2 PostgreSQL mxODBC Any RDBMS with ODBC drivers kinterbasdb Firebird/Interbase adodbapi Windows ADO data sources pydb2 DB/2
  • 96. MySQLdb module • MySQLdb is a thin Python wrapper around mysql. It is compatible with the Python DB API, which makes the code more portable. Using this model is the preferred way of working with the MySQL. • Example
  • 97. • mysql> create user 'testuser'@'localhost' • identified by 'xyz123'; • mysql> create database testdatabase; • mysql> grant all on *.* to 'testuser'@'localhost'; • mysql> use testdatabase; • mysql> create table student(Id INT PRIMARY KEY • AUTO_INCREMENT, Name VARCHAR(25)); • mysql> insert into student (name) values ('Tom'), • (‘Ren'), ('Harry');
  • 98. Database fetch using fetchall() import MySQLdb as mdb import sys con=mdb.connect(‘localhost’,’usrname’,’xyz123’,’testdatabase’); if con: cur=con.cursor() cur.execute(“select * from student”) rows=cur.fetchall() for row in rows: print row
  • 99. Exception in datbase Import MySQLdb as mdb Import sys Try: conn=mdb.connect(‘localhost’,’testuser’,’passwd’,’testdb’); cursor=conn.cursor() cursor.execute(“Delete from writers where id=5”) cursor.execute(“delete from writers where id=4”) conn.commit() Except mdb.Error, e: conn.rollback() print “Error %d: %s” %(e.args[0],e.args[1]) sys.exit(1) Cursor.close() Conn.close()