SlideShare ist ein Scribd-Unternehmen logo
1 von 62
Tutorial on Python Programming
Second Floor and Third Floor,
5/3 BEML Layout,
Varathur Road,
Thubarahalli,
Kundalahalli Gate,
Bangalore 66
Landmark – Behind Kundalahalli Gate bus stop,
Opposite to SKR Convention Mall,
Next to AXIS Bank.
AboutTIBAcademy
TIB Academy Provides Python Training in Bangalore with Best
Python Experts / Experienced professionals in Automobile
industries, Electronics Robotics Industries, Software Service
providers and many more. TIB Academy in Bangalore offers the
best Python training in Bangalore, like basic Python for
beginners and laterals, Machine Learning and Data Science for
senior experienced professionals and Django framework for
those interested. Apart from Python, TIB offers software
training for many other courses to step into MNCs and Top
Corporates. TIB can help you choose your career path as
Developer, Tester or Admin. And within Developer, you can
choose to be a frontend developer or backend developer or BI
developer or Mobile App developer and there are several other
career paths to choose from.
Python - What, Why and How?
• Python is apowerful scriptinglanguage created by Guido Van
Rossum in 1998.
• Python in itself is afeature rich, object oriented language and can
be used for Rapid Application Development of medium sized
applications.
• Python is ascriptinglanguage of choice of alarge number of the
security professionals, developersand automation engineers. There
isan ever-growingcommunity supportingPython.
• You can get Python asafree download from Official Python website
or asActivePython from ActiveState website. There are other
versionsavailable, but the mentioned onessolve the purpose.
Python Features…• It is free and open source.
• Easy coding- It'smeant for Rapid application development.
Consistent style of codingand usage make your life easier than
rememberingsome 100 shortcutsor tricks.
• Excellent Readability and Maintainability - Proper Indentation of
code is not achoice, rather the way of Python coding. If you pick
Python code by different programmers, you can be sure to see
similar lookingcode.
• It is Object-oriented - OOPis not apatch work for Python, rather an
in-built feature.
• Python include the use of transparent byte-code compilation
for speed, automaticmemory management and garbage
collection, and avery powerful object oriented and modular
design.
• Python shipswith alarge number of modules.
• No semi-intelligence - No ambiguoustype-conversionsor
assumptions.
• Exception Handlingis built into the language.
• It is CrossPlatform compatible.
Syllabus
Introduction
Execution steps
Memory management and Garbage collections
Data Types and Operations
Statements and Syntax
File Operations and Functions
Modules and Packages
Classes and Exceptional Handling
Advanced Concepts
Standard Library Modules
References
Exercises
Roadmap with Python
Command Line Arguments
• Sysmodule comesto the rescue.
• Import sys
• Print sys.argv[0]
• For i in sys.argv[]:
print i
• The type of all the command line argumentsis str.
• Checkingfor input datatypesand type conversion should alwaysbe
done.
Python Interpreter
• Executinginteractively: Open DOSprompt and just type python.
• C:>python ActivePython 2.5.1.1 (ActiveState Software Inc.) based
on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSCv.1310
32 bit (Intel)] on win32 Type "help", "copyright", "credits" or
"license" for more information. >>>
• >>> print "Welcome to Technobeans!" Welcome to Technobeans!
• To come out of the interactive shell, pressCtrl+Zand Enter key.
• When Python interpreter loads, modules/packageswill be available
for importing <Python installation>libsite-packages.
• sys.path.append("C:  My_Scripts") – for importinguser
defined modules.
.pycand .pyo
• Python source code is automatically compiled into Python byte
code by the CPython interpreter. Compiled code is usually stored in
PYC(or PYO) files, and isregenerated when the source isupdated,
or when otherwise necessary.
• Automatic compilation – importingamodule. But the module gets
executed.
• Explicit compilation – py_compile.compile(“module.py”) –
generatesmodule.pyc
• When the Python interpreter is invoked with the -Oflag, optimized
code is generated and stored in ‘.pyo’ files.
• Passingtwo -Oflagsto the Python interpreter (-OO) will cause the
bytecode compiler to perform optimizationsthat could in some rare
casesresult in malfunctioningprograms.
• Aprogram doesn't run any faster when it is read from
a‘.pyc’ or ‘.pyo’ file than when it is read from a‘.py’ file; the only
thingthat'sfaster about ‘.pyc’ or‘.pyo’ filesisthe speed with which
they are loaded.
• When ascript is run by givingitsname on the command line, the
bytecode for the script is never written to a‘.pyc’ or ‘.pyo’ file. Thus,
the startup time of ascript may be reduced by movingmost of its
code to amodule and havingasmall bootstrap script that imports
that module. It is also possible to name a‘.pyc’ or ‘.pyo’ file directly
on the command line.
• The module ‘compileall’{} can create ‘.pyc’ files(or ‘.pyo’ fileswhen -
Ois used) for all modulesin adirectory.
• To distribute aprogram to people who already have Python
installed, you can ship either the PYfilesor the PYCfiles.
• Convert - .py to .exe ->Py2exe helps.
Datatypesavailable in Python
• The important (or rather the most commonly used) base data types
in Python are Numeric Types (numbers - int, long, float), Sequence
Types(string, list, tuple),Mapping Types(dictionary)
and Boolean(True/ False).
• For user-defined types, one hasto declare aclass.
• Out of the mentioned types, we will discussall the Numeric
Types, string(Sequence Type) and Boolean. Otherswill be
diccussed once we have learnt control structuresand some
built-in functions. The stringdatatype will be revisited as
well.
Declare avariable of aparticular type?
• ‘=‘ operator is the key.
• You do not have to use any special definingmethods. You simply
say: var_name =literal, where var_name is the name you choose
for variable and literal is aconstant value of any datatype.
• What’spresnet to the right definesthe type of LHSvariable name.
Everythingin Python is an object. Python findsthe type of a
variable from the value to which points.
• Also, because there is no strict definingstyle, you can point
var_name to any other literal of adifferent datatype.
How do I find the data type
• 2 waysof doingit:
– Type()
– Isinstance(variable, type)
Var =34
Print type(var)
if isinstance(var, int):
print True
GettingUser Input
• raw_input() function is used.
• Python acceptswhatever the end user typestill he or she presses
the “Enter” key, asan input and assignsit to the variable on left
side of the assignment.
• >>> a_var =raw_input("Please enter your name:")
Pleaseenter your name:Tester
>>> a_var 'Tester' >>>
• Whatever comesfrom STDINisalwaysastream of characters.
In your program, you have to convert the stringto the type
you want and in case of conversion error, inform the user
about the incorrectness.
• None asNOInput?
None, Empty!!
• Def foo():
pass
print foo() - None
• list =[]
for i in list:
print i - Empty
• a=raw_input(“enter a:”)
press“enter key” - Empty/ Sometimesreferred asNothing
• None is commonly used for exception handling.
Documentation Strings
• The first line should alwaysbe ashort, concise summary of the
object’spurpose.
• If there are more linesin the documentation string, the second line
should be blank, visually separatingthe summary from the rest of
the description.
• def example():
“””This is just an example.
It doessomething. “””
print “In example”
• print example. doc
Operators
• Addition: +
• Subtraction: -
• Multiplication: *
• Exponentiation: * *
• Division: / and / / (floor or [x])
• Modulus: %
Operators
• Greater than: >
• Lessthan: <
• Greater than or equal to: >=
• Lessthan or equal to: ⇐
• Equal to: ==
• Not equal to: <>!=
Conditional Execution
if / if-else / if-elif-if
• if condition1:
if condition2:
True path
else:
Falsepath
else:
Falsepath
LoopingExecution - while / for
• while condition
: Statements
• for var_name in Sequence/function which outputsa
sequence: statements
Range() - iterate over asequence of numbers.
range(5) =[0,1,2,3,4]
range(5,10) =[5,6,7,8,9]
range(0,10,3) =[0,3,6,9]
• Do-while: Not
available. While True:
if condition:
break
Break, Continue and Pass
• Break: The loop in which this statement is found exitsassoon asit
isreached. The control then jumpsto the outer loop in case of
nested loopsor to the main script.
• Continue: The loop in which this statement is found skipsrest of
the statementsfound after this, in itsbody. The control then jumps
to the beginningof the same loop and the next iteration is started.
• Pass:The passstatement doesnothing. It can be used asa
place-holder for afunction or conditional body when you are
workingon new code.
Sequence datatype
• ASequence type in python isamini built-in datastructurethat contains
elementsin an orderly manner which can be fetched usingindices. There
arethree typesof sequences:
• Stringsand tuplesare immutable in Python, but listsare mutable. (An
immutable object can not modified-in-place. What it meansisthat when a
function/expression triesto modify itscontentsright there itsoriginal
memorylocation, it either failsor createsan altogether new object.).
>>> a_string[0] ="t“ - Invalid
>>> a_list[0] ="My Example“ - Valid
>>> a_tuple[0] ="My Example“ - Invalid
Strings >>
>
a_string = “Chetan Giridhar"
Lists >>> a_list = [“Chetan",”Giridhar"]
Tuples >>> a_tuple =
(“Chetan",”Giridhar")
Operator Overloading
Python supportsoperator overloading.
• Indexing- Gettingan element with the help of an integer index.
• Slicing- Gettingasub-sequenceby usinga special syntaxof lower and
upper index.
• Appending/Extending/Concatenating- Addingelementsat the end of a
sequence.
• Deletingan element - For first occurrence.
• Modifyingan element - At agiven index.
• Sorting- Based on element types.
Workingwith lists
• Defininglists
numList =[2003,2005,2008,2010]
strList =[“IIA”, “Chetan”, “Python”]
• Accessingalist
For x in numList:
print x
print strList[0] or strList[-1]
• Slicingalist
firstHalf =numList[:2]
lastHalf =numList[2:3]
• Addingand removingitems
list.append(“2009”) – end of the list
list.extend(list1) – end of the list
list.insert(index, item) – at aspecified index
Pop(index) – removesthe element at the index
remove(item) – removesthe first occurrence of item.
• Sortingalist
list.sort()
list.reverse()
list =["iia","IIA", "chetan", "python"]
list.sort(key =str.lower)
for i in list:
print I
• Convertingtuple to
list List(tuple)
Stringfunctions• test =‘This is asimple string’
• len(test) =23
• test.count(‘r’) =1
• test.find(‘r’) =18
• test =test.replace(‘simple’, ‘short’)
‘This is short string’
• test.index(‘simple’) =10
• test.split(‘is’) =[‘This ‘, ‘ashort string’]
• ‘some’. join(test.split(‘is’))
• test.upper() and test.lower() and test.lower.capatalize()
• test.lstrip(‘ ‘) and test.rstrip(‘t’)
eval vsexec
• Execfunction will execute Python Code that is contained in str
stringand return the result.
• Eval workssimilar to the exec function except that it only evaluates
the stringasPython expression and returnsthe result.
• def foo():
print "foo“
eval("foo" +"()")
• cards=['king', 'queen', 'jack']
codeStr ="for i in cards:
print i"
exec(codeStr)
What isaPython dictionary?
• APython dictionary is aMapping Type, which is amini data-
structure, containingkey-value pairs.
• Adictionary hasunsorted key-value pairs. It meansthe datain
adictionary is not in any necessary order, unlike asequence type.
This helpsto give Python, alot of freedom in termsof memory
management.
• The key in adictionary should be immutable.
• Akey is alwaysunique. If you use the same key in an assignment,
the value of this key getsupdated, instead of addinganew key with
the same name.
Workingwith dicts…
>>> aDict ={"a" : 1, "b": 3}
>>> type(aDict)
type 'dict‘
>>> aDict.keys() and aDict.values()
>>> aDict.items() - [('a', 1), ('b', 2)]
>>> for key in aDict.keys():
print "Key: " +str(key) +" Value: " +str(aDict[key])
Key: aValue: 1 Key: b Value: 2
>>> aList =[1,2,3]
aDict ={"a" : 1, "b": 3}
aNestedDict ={'key1' : aList, 'key2': aDict}
>>> aNestedDict['key2']['a'] - 1
>>> for key,value in aDict.iteritems()
swapDict[value] =key
Code Reusability in Python
• Implementing code reusability happensthrough the use of
functions, modulesand packages.
• You write the code in generic ways to come up with functions, pack
related functions in a single module (file) and pack multiple related
modulesinside apackage (directory structure).
• Another form of the above is that you write methods(functions)
that belongto aclass(that signifiesauser defined datatype), put
related classesinsideamodule, put related modulesinside a
package.
• Everythingis an object in Python. It would make sense that you
create an object (of aclass) to talk to another object (built on or
your own) rather than codingin the traditional way while beingin
the world of awonderful OOlanguage like Python.
Workingwith functions
• Atypical function
def multiply(operand1,operand2):
return a* b
The above isafunction with name multiply. What it doesis, it takestwo
argumentsand returnsthe product of them.
Here operand1 and operand2are formal parameters. Notethat we did
not define their type in the function definition. So it becomesthe
responsibility of the function body to do typechecking.
The execution of afunction introducesanew symbol table used for the
local variablesof the function. Moreprecisely, all variable assignments
in afunction store the value in the local symbol table; whereasvariable
referencesfirst look in the local symbol table, then in the global
symbol table, and then in the table of built-in names. LGBisthe
mantra.
Default valuescan be used and passed.
Scopingof variables
• In Python, variablesthat are only referenced inside afunction are
implicitly global. If avariable is assigned anew value anywhere
within the function'sbody, it'sassumed to be alocal. If avariable is
ever assigned anew value insidethe function, the variable is
implicitly local, and you need to explicitly declare it as'global'.
• Though abit surprisingat first, amoment'sconsideration explains
this. On one hand, requiringglobal for assigned variablesprovidesa
bar against unintended side-effects. On the other hand, if global
wasrequired for all global references, you'd be usingglobal all the
time. You'd have to declare asglobal every reference to abuilt-in
function or to acomponent of an imported module. This clutter
would defeat the usefulnessof the global declaration for identifying
side-effects.
Rules– makingafunction call
1. Number of arguments- Number of argumentsshould be equal to
the number of formal parametersused in the definition of the
function.
2. Type of arguments- The argument and the corresponding
parameter should have the same datatype.
3. Order of arguments- The argumentsshould have the same order
asthat of the formal parameters, otherwise you might get type
mismatch errorsor unexpected resultsin some cases.
Example:
>>>def printData(name, age):
return "Name: %sAge: %d" %(name,age)
>>> printData("Tester",100) 'Name: Tester Age: 100
if you carefully see the stringformatting used, %sand %d format
specifiersmake Python take care of type checkingautomatically.
PassBy – Value and reference
• Parametersare passed by value.
• Stringsand Tuplesare immutable and hence cant be changed.
• When listsare passed, they get muted and hence it looksasif they
are gettingpassed by references.
Lambda – Anonymousfunctions
• Anonymousfunctions: functionsthat are not bound to aname at
run time.
• g=lambda x: x**2
g(8) – 64
• Lambdadefinition doesnot include a"return" statement -- it
alwayscontainsan expression which isreturned.
• def make_incrementor (n): return lambdax: x +n
The above code defines a function "make_inrementor" that
createsan anonymousfunction on the fly and returnsit. The
returned function incrementsitsargument by the value that
wasspecified when it wascreated.
• f =make_incrementor(2) . f(42) =44.
• >>> foo =[2, 18, 9, 22, 17, 24, 8, 12, 27]
• >>> print filter(lambda x: x %3 == 0, foo)
• [18, 9, 24, 12, 27]
• >>> print map(lambda x: x * 2 +10, foo)
• [14, 46, 28, 54, 44, 58, 26, 34, 64]
• >>> print reduce(lambda x, y: x +y, foo)
• 139
File Handling
• open(filename, mode)
>>> f =open('/tmp/workfile', 'w')
>>> print f
<open file '/tmp/workfile', mode 'w' at 80a0960>
Modes: r, w, a, b, r+, rb, wb, r+b
• f.read(size)
When sizeisomitted or negative, the entire contentsof the file will
be read and returned;
If the end of the file hasbeen reached, f.read() will return an empty
string("").
• f.readline() readsa single line from the file; a newline character (n)
is left at the end of the string, and is only omitted on the last line of
the file if the file doesn’t end in anewline.
• f.readlines() returnsalist containingall the linesof datain the file.
If given an optional parameter sizehint, it readsthat many bytes
from the file and enough more to complete aline, and returnsthe
linesfrom that.
• Read words: Memory efficient, fast, and simpler code:
for line in f:
print line ORfor word in line.split()
• f.write(string) writesthe contentsof string to the file,
returningNone. To write somethingother than astring, it needsto
be converted to astringfirst.
• f.tell() returnsan integer givingthe file object’scurrent position in
the file, measured in bytesfrom the beginningof the file.
• To change the file object’sposition, use f.seek(offset, from_what).
• f.close() to close it and free up any system resourcestaken up by
the open file.
• F.endswitch(“py”) search for fileswith extension py – True/False
Some more file operations
• Import os
• os.remove(filepath)
• os.rename(oldzfile, newFile)
• os.listdir(dirPath)
• os.walk(dirPath)
Pickling
• Way to achieve object serialization in Python.
• Picklingisused when you want to save morecomplexdatatypeslike lists,
dictionaries, or classinstancesin afile.
• Dumpingand parsinglogicisdifficult to develop and maintain.
• Python cPickle module can take almost any Python object and
convert it to astringrepresentation; this processis called pickling.
• pickle is the standard way to make Python objectswhich can be
stored and reused by other programsor by afuture invocation of
the same program
• Reconstructingthe object from the stringrepresentation is
called unpickling.
• Between picklingand unpickling, the stringrepresentingthe object
may have been stored in afile or data, or sent over anetwork
connection to some distant machine.
• If you have an object x, and afile object f that’sbeen opened for
writing, the simplest way to pickle and unpickle the object is:
pickle.dump(x, f) and x =pickle.load(f).
Some Concepts
• code block: Acode block is apiece of Python program text that can
be executed asaunit, such asamodule, aclassdefinition or a
function body.
• Execution frame: Every code block is assigned an execution frame
by Python.
1.Python maintainssome debugginginformation about the code
block asapart of the execution frame.
2.The execution frame determinesthe control flow after the
execution of the code block completes.
3. It definesnamespacesfor the code block
• Namespace: Anamespace is like adictionary. You can consider the
names(identifiers/variable names) askeysof this dictionary and
the correspondingvaluesto be the objectsto which they point to.
Regular Expressions
• Regular expressionsare avery powerful tool in any language. They
allow patternsto be matched against strings.
• Regular expressionsin Python are handled by usingmodule ‘re’.
• Import re
test ='This is for testingregular expressionsin Python.‘
• result =re.search('(Th)(is)',test)
print result.group(0), result.group(1)
• result =re.match(‘regular’, test)
print result – None (match only at the beginningof string)
• ourPattern =re.compile ( '(.*?)(the)' )
testString='This is the dogand the cat.‘
result =ourPattern.match ( testString )
result.group ( 0 )
• Regular expressionsuse the backslash character ('') to indicate
special formsor to allow special charactersto be used without
invokingtheir special meaning.
• What if we want to use ‘’ in file path?
• The solution isto use Python’sraw stringnotation for regular
expression patterns; backslashesare not handled in any
special way in astringliteral prefixed with 'r'.
• f =open(r"c:Windowsnotepad.exe", "r")
• Special characters: ‘.’, ‘^’, ‘$’,’*’,’+’,’?’,{m}, {m,n},’’, ‘| ’, ‘(…)’, ‘d’, ‘D’,
‘s’, ‘S’, ‘w’, ‘W’
• re.split('[a-f]+', '0a3B9’) - ['0', '3', '9']
• someString='I have adream.'
print re.sub ( 'dream', 'dog', someString)
print someString
• Regular Expressionsdon’t change the actual string.
• Regular Expressionsare very helpful but resource intensive. It
should not be used for matchingor findingsimple texts.
Some Concepts…
• An execution frame createstwo kindsof namespacesfor acode
block, namely local and global. The third type of namespace is
called the built-in namespace and is created when the Python
interpreter loads.
• bindingand unbinding:
1.When you define afunction, you bind the formal parameters.
2.You bind aname when you use an import construct (to the
namespace of the block which containsthe import statement).
3.When you define a class or a function, using the class and def
keywords, you bind the names of the functions and classes and
they are available in the containingblock (e.g. amodule)
4. When you do an assignment operation
5.The loop control variable in afor loop construct createsa
dynamic binding
6. In an except clause, when you provide argument to the clause
Modules
• How do I use an existingmodule and the functionsand classes
contained in it?
To use an existingmodule, you need to first create areference to it
in the current namespace. In simple words, you would need to
import amodule to use itsfunctionality.
• How do I know whether amodule is available in current
namespace?
You can use dir() built in command to check what all reference
variablesare available to you in current namespace. You can go one
step ahead and use dir() to see what referencesare available in a
particular object's(e.g. module's) namespace by passingobject as
the argument.
• import random
dir(random)
Modules…
• ImportingModules:
import random
from random import randint
from random import *
import random asRand
• Accessclassesand functionsof module:
For thismodule name and the dot operator should be used.
• Importingmodulesin blocks?
• From <modulename>import <functionanme>
OOPin Python
• Python asalanguage is built in object oriented way. Everythingis an
object in Python and it really meansso.
• When compared with other Object Oriented languageslike C++ and
Java, you will observe that most of the featuresare available in
Python, in amuch simpler way. You will also observe that many of
the accessrelated features(and those loadsof keywordsand rules)
are not there.
• Inheritance
• Multiple inheritance
• Abstraction
• Polymorphism
• Overriding
• Operator Overloading
• Object Instances
Classesin Python
• Creatingaclass:
classMyClass:
pass
• Instantiatingaclass:
a=MyClass()
print a
< main .MyClassinstance at 0x01206A08>
Yes, it does look like a function call, in fact you can very well have a
function and a class with the same name in your Python code. The
syntax for instantiation and function call will look exactly the same.
Python understandsthe type of any variable based on the object to
which it points. So, if MyCode pointsto the body of aclass, it a =
MyCode() instantiatesaclassand if it pointsto afunction body, the
function is called and aholdsitsreturn values.
Amore meaningful Class
• classSimpleClass:
def init (myVal):
self.myVal =myVal
def getValue(self):
return self.myVal
def setValue(self, newVal):
self.myVal =new Val
• The classSimpleClasshasthree methodsinside it.
• The first one hasthe name _ _init_ _ and iscalled the
constructor. The name of thismethod should alwaysbe _init_
_. It takesthe argument myVal. Thisvalue isused to initialize
an object. Thismethod isused frequently to initialize an
object with agiven state, rather than calling a whole set of
functionsto set itsstateafter creation.
• self is aconvention used by Python programmers to depict the
current object reference. Unlike many other OOPlanguages, the
current object reference hasto be explicitly defined in Python class
definitions- instance variablesand methods. The first argument of
every method hasto be self. This argument is used only while
definingthe method, in the method call, it is omitted.
• Inside the _ _init_ _, it saysself.myVal =myVal. This is asimple
assignment operation. Here self.myVal definesan instance variable
(object variable).
• We see two other methods, which look like normal functions. The
difference beingthat they are bound to an object and there is
essentially alot of information which need not be passed to them
asargumentsevery time, asthey have accessto the object
variablesand classvariables(we'll discussabout classvariables
later).
• getValue() returnsthe value of the self.myVal and setValue() setsit
to the value that is passed.
• get and set functionsare called accessorsand mutators
respectively. They have alot of utility in preventingthe private
variablesof aclassfrom gettingmodified inaccurately or
unexpectedly.
• simpleClassObject =SimpleClass(12) print "Value: " +
str(simpleClassObject.getValue()) simpleClassObject.setValue(15)
print "Value: " +str(simpleClassObject.getValue())
• Value: 12
Value: 15
classA:
def init (self):
print "Called A"
def local(self):
print "In local"
def load(self):
print "Loaded from A"
self. local()
classB():
def init (self):
print "Called B"
def load(self):
print "Loaded from B“
classC(B,A):
def init (self):
a=A()
print "In C“
c=C()
c.load()
if hasattr(C, "load"):
print "yes"
Staticanalysisof code
• PyChecker is astatic analysistool that findsbugsin Python source
code and warnsabout code complexity and style.
• Pylint is another tool that checksif a module satisfiesa coding
standard, and also makes it possible to write plug-ins to add a
custom feature.
• Pylint more popularly used.
Exception Handling
• The statementsused to deal with exceptionsare raise and except.
• def throws():
raiseRuntimeError('this is the error message')
def main():
throws()
if name ==' main ':
main()
• Traceback (most recent call last): File "throwing.py", line 10, in
<module> main()
File "throwing.py", line 7, in main throws()
File "throwing.py", line 4, in throwsraise RuntimeError('this isthe
error message')
RuntimeError: this is the error message
• f =None
try:
f =open("aFileName")
f.write(could_make_error())
except IOError:
print "Unable to open file"
except: # catch all exceptions
print "Unexpected error"
else: # executed if no exceptionsare raised
print "File write completed successfully"
finally: # clean-up actions, alwaysexecuted
if f:
f.close()
• Raise – re-raisesthe same exception thrown and dies.
Garbage Collection
• Python'smemory allocation and de-allocation method is automatic.
• Python usestwo strategiesfor memory allocation reference
countingand garbage collection.
• Reference countingworksby countingthe number of timesan
object isreferenced by other objectsin the system. When
referencesto an object are removed, the reference count for
an object isdecremented. When the reference count
becomeszero the object isde-allocated.
• Caveat isthat it cannot handle referencecycles.
• def make_cycle():
l =[ ]
l.append(l)
• Garbage collection is ascheduled activity. Python schedulesgarbage
collection based upon athreshold of object allocationsand object
de-allocations.
• import gc
print gc.get_threshold()
(700,10,10) - This meanswhen the number of allocationsvs. the
number of de-allocationsis greater than 700 the automatic garbage
collector will run.
• The garbage collection can be invoked manually in the
following way:
import gc
gc.collect()
• gc.collect() returnsthe number of objectsit hascollected and
deallocated.
Logging
• Loggingis performed by callingmethodson instancesof
the Logger class.
• The methodsare debug(), info(), warning(), error() and critical(),
which mirror the default levels.
• import logging
LOG_FILENAME='example.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.D
EBUG)
logging.debug('Thismessage should go to the logfile')
• File Contents:
DEBUG:root:Thismessage should go to the logfile.
• Messageswith higher precedence get logged to the
LOG_FILENAME.
Python in Astronomy
• pFitsio or PyFitsand the NumPy, SciPy, astronomical imagesand
tablescan be easily accessed and manipulated asnumerical arrays.
• BoA(Bolometer Analysis Package)
• Astro-WISE(widefield imagingsystem)
• astLib – Python Astronomy Modules- astronomical plots, some
statistics, common calculations, coordinate conversions, and
manipulatingFITSimageswith World Coordinate System
(WCS) information through PyWCSTools
References
• Python.org
• Doughellmann.com
• Devshed.com
• Testingperspective.com
• Network-theory.co.uk
• Boodebr.org
• Stackoverflow.com
Thanks

Weitere ähnliche Inhalte

Was ist angesagt?

Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
Kanchilug
 

Was ist angesagt? (20)

Introduction To Python
Introduction To PythonIntroduction To Python
Introduction To Python
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
 
Python programming
Python  programmingPython  programming
Python programming
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | EdurekaPython Course | Python Programming | Python Tutorial | Python Training | Edureka
Python Course | Python Programming | Python Tutorial | Python Training | Edureka
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)Introduction to the basics of Python programming (part 1)
Introduction to the basics of Python programming (part 1)
 
Python course syllabus
Python course syllabusPython course syllabus
Python course syllabus
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
 
Intro to Python Programming Language
Intro to Python Programming LanguageIntro to Python Programming Language
Intro to Python Programming Language
 
Python basic
Python basicPython basic
Python basic
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction To Programming with Python
Introduction To Programming with PythonIntroduction To Programming with Python
Introduction To Programming with Python
 
Introduction to Python Basics Programming
Introduction to Python Basics ProgrammingIntroduction to Python Basics Programming
Introduction to Python Basics Programming
 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python presentation by Monu Sharma
Python presentation by Monu SharmaPython presentation by Monu Sharma
Python presentation by Monu Sharma
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Phython Programming Language
Phython Programming LanguagePhython Programming Language
Phython Programming Language
 

Ähnlich wie Python Tutorial for Beginner

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
Chetan Giridhar
 

Ähnlich wie Python Tutorial for Beginner (20)

Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Python - Introduction
Python - IntroductionPython - Introduction
Python - Introduction
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
INTERNSHIP REPORT.docx
 INTERNSHIP REPORT.docx INTERNSHIP REPORT.docx
INTERNSHIP REPORT.docx
 
Python indroduction
Python indroductionPython indroduction
Python indroduction
 
Python intro
Python introPython intro
Python intro
 
Python PPT.pptx
Python PPT.pptxPython PPT.pptx
Python PPT.pptx
 
Class_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdfClass_X_PYTHON_J.pdf
Class_X_PYTHON_J.pdf
 
Python_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptxPython_Introduction_Good_PPT.pptx
Python_Introduction_Good_PPT.pptx
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
python classes in thane
python classes in thanepython classes in thane
python classes in thane
 
Complete python toolbox for modern developers
Complete python toolbox for modern developersComplete python toolbox for modern developers
Complete python toolbox for modern developers
 
Fundamentals of python
Fundamentals of pythonFundamentals of python
Fundamentals of python
 
Python for katana
Python for katanaPython for katana
Python for katana
 
3-Module - Basic Python jUST _ aUTOMATE.pptx.pdf
3-Module - Basic Python  jUST _ aUTOMATE.pptx.pdf3-Module - Basic Python  jUST _ aUTOMATE.pptx.pdf
3-Module - Basic Python jUST _ aUTOMATE.pptx.pdf
 
Programming with Python: Week 1
Programming with Python: Week 1Programming with Python: Week 1
Programming with Python: Week 1
 

Mehr von rajkamaltibacademy

Mehr von rajkamaltibacademy (17)

Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Informatica Training Tutorial
Informatica Training Tutorial Informatica Training Tutorial
Informatica Training Tutorial
 
AWS Training Tutorial for Freshers
AWS Training Tutorial for FreshersAWS Training Tutorial for Freshers
AWS Training Tutorial for Freshers
 
.Net Training Tutorial
.Net Training Tutorial.Net Training Tutorial
.Net Training Tutorial
 
CCNA Training Tutorial in bangaore
CCNA Training Tutorial in bangaoreCCNA Training Tutorial in bangaore
CCNA Training Tutorial in bangaore
 
Django Training Tutorial in Bangalore
Django Training Tutorial in BangaloreDjango Training Tutorial in Bangalore
Django Training Tutorial in Bangalore
 
Python Training Tutorial for Frreshers
Python Training Tutorial for FrreshersPython Training Tutorial for Frreshers
Python Training Tutorial for Frreshers
 
Oracle Training Tutorial for Beginners
Oracle Training Tutorial for BeginnersOracle Training Tutorial for Beginners
Oracle Training Tutorial for Beginners
 
Mongodb Training Tutorial in Bangalore
Mongodb Training Tutorial in BangaloreMongodb Training Tutorial in Bangalore
Mongodb Training Tutorial in Bangalore
 
Angular Tutorial Freshers and Experienced
Angular Tutorial Freshers and ExperiencedAngular Tutorial Freshers and Experienced
Angular Tutorial Freshers and Experienced
 
Teradata Tutorial for Beginners
Teradata Tutorial for BeginnersTeradata Tutorial for Beginners
Teradata Tutorial for Beginners
 
Best Core Java Training In Bangalore
Best Core Java Training In BangaloreBest Core Java Training In Bangalore
Best Core Java Training In Bangalore
 
R Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB AcademyR Programming Tutorial for Beginners - -TIB Academy
R Programming Tutorial for Beginners - -TIB Academy
 
Selenium tutorial to Beginners
Selenium tutorial to BeginnersSelenium tutorial to Beginners
Selenium tutorial to Beginners
 
Angularjs Tutorial for Beginners
Angularjs Tutorial for BeginnersAngularjs Tutorial for Beginners
Angularjs Tutorial for Beginners
 
Hadoop Training Tutorial for Freshers
Hadoop Training Tutorial for FreshersHadoop Training Tutorial for Freshers
Hadoop Training Tutorial for Freshers
 
Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 

Kürzlich hochgeladen

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Kürzlich hochgeladen (20)

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 

Python Tutorial for Beginner

  • 1. Tutorial on Python Programming Second Floor and Third Floor, 5/3 BEML Layout, Varathur Road, Thubarahalli, Kundalahalli Gate, Bangalore 66 Landmark – Behind Kundalahalli Gate bus stop, Opposite to SKR Convention Mall, Next to AXIS Bank.
  • 2. AboutTIBAcademy TIB Academy Provides Python Training in Bangalore with Best Python Experts / Experienced professionals in Automobile industries, Electronics Robotics Industries, Software Service providers and many more. TIB Academy in Bangalore offers the best Python training in Bangalore, like basic Python for beginners and laterals, Machine Learning and Data Science for senior experienced professionals and Django framework for those interested. Apart from Python, TIB offers software training for many other courses to step into MNCs and Top Corporates. TIB can help you choose your career path as Developer, Tester or Admin. And within Developer, you can choose to be a frontend developer or backend developer or BI developer or Mobile App developer and there are several other career paths to choose from.
  • 3. Python - What, Why and How? • Python is apowerful scriptinglanguage created by Guido Van Rossum in 1998. • Python in itself is afeature rich, object oriented language and can be used for Rapid Application Development of medium sized applications. • Python is ascriptinglanguage of choice of alarge number of the security professionals, developersand automation engineers. There isan ever-growingcommunity supportingPython. • You can get Python asafree download from Official Python website or asActivePython from ActiveState website. There are other versionsavailable, but the mentioned onessolve the purpose.
  • 4. Python Features…• It is free and open source. • Easy coding- It'smeant for Rapid application development. Consistent style of codingand usage make your life easier than rememberingsome 100 shortcutsor tricks. • Excellent Readability and Maintainability - Proper Indentation of code is not achoice, rather the way of Python coding. If you pick Python code by different programmers, you can be sure to see similar lookingcode. • It is Object-oriented - OOPis not apatch work for Python, rather an in-built feature. • Python include the use of transparent byte-code compilation for speed, automaticmemory management and garbage collection, and avery powerful object oriented and modular design.
  • 5. • Python shipswith alarge number of modules. • No semi-intelligence - No ambiguoustype-conversionsor assumptions. • Exception Handlingis built into the language. • It is CrossPlatform compatible.
  • 6. Syllabus Introduction Execution steps Memory management and Garbage collections Data Types and Operations Statements and Syntax File Operations and Functions Modules and Packages Classes and Exceptional Handling Advanced Concepts Standard Library Modules References Exercises Roadmap with Python
  • 7. Command Line Arguments • Sysmodule comesto the rescue. • Import sys • Print sys.argv[0] • For i in sys.argv[]: print i • The type of all the command line argumentsis str. • Checkingfor input datatypesand type conversion should alwaysbe done.
  • 8. Python Interpreter • Executinginteractively: Open DOSprompt and just type python. • C:>python ActivePython 2.5.1.1 (ActiveState Software Inc.) based on Python 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSCv.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> • >>> print "Welcome to Technobeans!" Welcome to Technobeans! • To come out of the interactive shell, pressCtrl+Zand Enter key. • When Python interpreter loads, modules/packageswill be available for importing <Python installation>libsite-packages. • sys.path.append("C: My_Scripts") – for importinguser defined modules.
  • 9. .pycand .pyo • Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC(or PYO) files, and isregenerated when the source isupdated, or when otherwise necessary. • Automatic compilation – importingamodule. But the module gets executed. • Explicit compilation – py_compile.compile(“module.py”) – generatesmodule.pyc • When the Python interpreter is invoked with the -Oflag, optimized code is generated and stored in ‘.pyo’ files. • Passingtwo -Oflagsto the Python interpreter (-OO) will cause the bytecode compiler to perform optimizationsthat could in some rare casesresult in malfunctioningprograms.
  • 10. • Aprogram doesn't run any faster when it is read from a‘.pyc’ or ‘.pyo’ file than when it is read from a‘.py’ file; the only thingthat'sfaster about ‘.pyc’ or‘.pyo’ filesisthe speed with which they are loaded. • When ascript is run by givingitsname on the command line, the bytecode for the script is never written to a‘.pyc’ or ‘.pyo’ file. Thus, the startup time of ascript may be reduced by movingmost of its code to amodule and havingasmall bootstrap script that imports that module. It is also possible to name a‘.pyc’ or ‘.pyo’ file directly on the command line. • The module ‘compileall’{} can create ‘.pyc’ files(or ‘.pyo’ fileswhen - Ois used) for all modulesin adirectory. • To distribute aprogram to people who already have Python installed, you can ship either the PYfilesor the PYCfiles. • Convert - .py to .exe ->Py2exe helps.
  • 11. Datatypesavailable in Python • The important (or rather the most commonly used) base data types in Python are Numeric Types (numbers - int, long, float), Sequence Types(string, list, tuple),Mapping Types(dictionary) and Boolean(True/ False). • For user-defined types, one hasto declare aclass. • Out of the mentioned types, we will discussall the Numeric Types, string(Sequence Type) and Boolean. Otherswill be diccussed once we have learnt control structuresand some built-in functions. The stringdatatype will be revisited as well.
  • 12. Declare avariable of aparticular type? • ‘=‘ operator is the key. • You do not have to use any special definingmethods. You simply say: var_name =literal, where var_name is the name you choose for variable and literal is aconstant value of any datatype. • What’spresnet to the right definesthe type of LHSvariable name. Everythingin Python is an object. Python findsthe type of a variable from the value to which points. • Also, because there is no strict definingstyle, you can point var_name to any other literal of adifferent datatype.
  • 13. How do I find the data type • 2 waysof doingit: – Type() – Isinstance(variable, type) Var =34 Print type(var) if isinstance(var, int): print True
  • 14. GettingUser Input • raw_input() function is used. • Python acceptswhatever the end user typestill he or she presses the “Enter” key, asan input and assignsit to the variable on left side of the assignment. • >>> a_var =raw_input("Please enter your name:") Pleaseenter your name:Tester >>> a_var 'Tester' >>> • Whatever comesfrom STDINisalwaysastream of characters. In your program, you have to convert the stringto the type you want and in case of conversion error, inform the user about the incorrectness. • None asNOInput?
  • 15. None, Empty!! • Def foo(): pass print foo() - None • list =[] for i in list: print i - Empty • a=raw_input(“enter a:”) press“enter key” - Empty/ Sometimesreferred asNothing • None is commonly used for exception handling.
  • 16. Documentation Strings • The first line should alwaysbe ashort, concise summary of the object’spurpose. • If there are more linesin the documentation string, the second line should be blank, visually separatingthe summary from the rest of the description. • def example(): “””This is just an example. It doessomething. “”” print “In example” • print example. doc
  • 17. Operators • Addition: + • Subtraction: - • Multiplication: * • Exponentiation: * * • Division: / and / / (floor or [x]) • Modulus: %
  • 18. Operators • Greater than: > • Lessthan: < • Greater than or equal to: >= • Lessthan or equal to: ⇐ • Equal to: == • Not equal to: <>!=
  • 19. Conditional Execution if / if-else / if-elif-if • if condition1: if condition2: True path else: Falsepath else: Falsepath
  • 20. LoopingExecution - while / for • while condition : Statements • for var_name in Sequence/function which outputsa sequence: statements Range() - iterate over asequence of numbers. range(5) =[0,1,2,3,4] range(5,10) =[5,6,7,8,9] range(0,10,3) =[0,3,6,9] • Do-while: Not available. While True: if condition: break
  • 21. Break, Continue and Pass • Break: The loop in which this statement is found exitsassoon asit isreached. The control then jumpsto the outer loop in case of nested loopsor to the main script. • Continue: The loop in which this statement is found skipsrest of the statementsfound after this, in itsbody. The control then jumps to the beginningof the same loop and the next iteration is started. • Pass:The passstatement doesnothing. It can be used asa place-holder for afunction or conditional body when you are workingon new code.
  • 22. Sequence datatype • ASequence type in python isamini built-in datastructurethat contains elementsin an orderly manner which can be fetched usingindices. There arethree typesof sequences: • Stringsand tuplesare immutable in Python, but listsare mutable. (An immutable object can not modified-in-place. What it meansisthat when a function/expression triesto modify itscontentsright there itsoriginal memorylocation, it either failsor createsan altogether new object.). >>> a_string[0] ="t“ - Invalid >>> a_list[0] ="My Example“ - Valid >>> a_tuple[0] ="My Example“ - Invalid Strings >> > a_string = “Chetan Giridhar" Lists >>> a_list = [“Chetan",”Giridhar"] Tuples >>> a_tuple = (“Chetan",”Giridhar")
  • 23. Operator Overloading Python supportsoperator overloading. • Indexing- Gettingan element with the help of an integer index. • Slicing- Gettingasub-sequenceby usinga special syntaxof lower and upper index. • Appending/Extending/Concatenating- Addingelementsat the end of a sequence. • Deletingan element - For first occurrence. • Modifyingan element - At agiven index. • Sorting- Based on element types.
  • 24. Workingwith lists • Defininglists numList =[2003,2005,2008,2010] strList =[“IIA”, “Chetan”, “Python”] • Accessingalist For x in numList: print x print strList[0] or strList[-1] • Slicingalist firstHalf =numList[:2] lastHalf =numList[2:3] • Addingand removingitems list.append(“2009”) – end of the list list.extend(list1) – end of the list list.insert(index, item) – at aspecified index
  • 25. Pop(index) – removesthe element at the index remove(item) – removesthe first occurrence of item. • Sortingalist list.sort() list.reverse() list =["iia","IIA", "chetan", "python"] list.sort(key =str.lower) for i in list: print I • Convertingtuple to list List(tuple)
  • 26. Stringfunctions• test =‘This is asimple string’ • len(test) =23 • test.count(‘r’) =1 • test.find(‘r’) =18 • test =test.replace(‘simple’, ‘short’) ‘This is short string’ • test.index(‘simple’) =10 • test.split(‘is’) =[‘This ‘, ‘ashort string’] • ‘some’. join(test.split(‘is’)) • test.upper() and test.lower() and test.lower.capatalize() • test.lstrip(‘ ‘) and test.rstrip(‘t’)
  • 27. eval vsexec • Execfunction will execute Python Code that is contained in str stringand return the result. • Eval workssimilar to the exec function except that it only evaluates the stringasPython expression and returnsthe result. • def foo(): print "foo“ eval("foo" +"()") • cards=['king', 'queen', 'jack'] codeStr ="for i in cards: print i" exec(codeStr)
  • 28. What isaPython dictionary? • APython dictionary is aMapping Type, which is amini data- structure, containingkey-value pairs. • Adictionary hasunsorted key-value pairs. It meansthe datain adictionary is not in any necessary order, unlike asequence type. This helpsto give Python, alot of freedom in termsof memory management. • The key in adictionary should be immutable. • Akey is alwaysunique. If you use the same key in an assignment, the value of this key getsupdated, instead of addinganew key with the same name.
  • 29. Workingwith dicts… >>> aDict ={"a" : 1, "b": 3} >>> type(aDict) type 'dict‘ >>> aDict.keys() and aDict.values() >>> aDict.items() - [('a', 1), ('b', 2)] >>> for key in aDict.keys(): print "Key: " +str(key) +" Value: " +str(aDict[key]) Key: aValue: 1 Key: b Value: 2 >>> aList =[1,2,3] aDict ={"a" : 1, "b": 3} aNestedDict ={'key1' : aList, 'key2': aDict} >>> aNestedDict['key2']['a'] - 1 >>> for key,value in aDict.iteritems() swapDict[value] =key
  • 30. Code Reusability in Python • Implementing code reusability happensthrough the use of functions, modulesand packages. • You write the code in generic ways to come up with functions, pack related functions in a single module (file) and pack multiple related modulesinside apackage (directory structure). • Another form of the above is that you write methods(functions) that belongto aclass(that signifiesauser defined datatype), put related classesinsideamodule, put related modulesinside a package. • Everythingis an object in Python. It would make sense that you create an object (of aclass) to talk to another object (built on or your own) rather than codingin the traditional way while beingin the world of awonderful OOlanguage like Python.
  • 31. Workingwith functions • Atypical function def multiply(operand1,operand2): return a* b The above isafunction with name multiply. What it doesis, it takestwo argumentsand returnsthe product of them. Here operand1 and operand2are formal parameters. Notethat we did not define their type in the function definition. So it becomesthe responsibility of the function body to do typechecking. The execution of afunction introducesanew symbol table used for the local variablesof the function. Moreprecisely, all variable assignments in afunction store the value in the local symbol table; whereasvariable referencesfirst look in the local symbol table, then in the global symbol table, and then in the table of built-in names. LGBisthe mantra. Default valuescan be used and passed.
  • 32. Scopingof variables • In Python, variablesthat are only referenced inside afunction are implicitly global. If avariable is assigned anew value anywhere within the function'sbody, it'sassumed to be alocal. If avariable is ever assigned anew value insidethe function, the variable is implicitly local, and you need to explicitly declare it as'global'. • Though abit surprisingat first, amoment'sconsideration explains this. On one hand, requiringglobal for assigned variablesprovidesa bar against unintended side-effects. On the other hand, if global wasrequired for all global references, you'd be usingglobal all the time. You'd have to declare asglobal every reference to abuilt-in function or to acomponent of an imported module. This clutter would defeat the usefulnessof the global declaration for identifying side-effects.
  • 33. Rules– makingafunction call 1. Number of arguments- Number of argumentsshould be equal to the number of formal parametersused in the definition of the function. 2. Type of arguments- The argument and the corresponding parameter should have the same datatype. 3. Order of arguments- The argumentsshould have the same order asthat of the formal parameters, otherwise you might get type mismatch errorsor unexpected resultsin some cases. Example: >>>def printData(name, age): return "Name: %sAge: %d" %(name,age) >>> printData("Tester",100) 'Name: Tester Age: 100 if you carefully see the stringformatting used, %sand %d format specifiersmake Python take care of type checkingautomatically.
  • 34. PassBy – Value and reference • Parametersare passed by value. • Stringsand Tuplesare immutable and hence cant be changed. • When listsare passed, they get muted and hence it looksasif they are gettingpassed by references.
  • 35. Lambda – Anonymousfunctions • Anonymousfunctions: functionsthat are not bound to aname at run time. • g=lambda x: x**2 g(8) – 64 • Lambdadefinition doesnot include a"return" statement -- it alwayscontainsan expression which isreturned. • def make_incrementor (n): return lambdax: x +n The above code defines a function "make_inrementor" that createsan anonymousfunction on the fly and returnsit. The returned function incrementsitsargument by the value that wasspecified when it wascreated. • f =make_incrementor(2) . f(42) =44.
  • 36. • >>> foo =[2, 18, 9, 22, 17, 24, 8, 12, 27] • >>> print filter(lambda x: x %3 == 0, foo) • [18, 9, 24, 12, 27] • >>> print map(lambda x: x * 2 +10, foo) • [14, 46, 28, 54, 44, 58, 26, 34, 64] • >>> print reduce(lambda x, y: x +y, foo) • 139
  • 37. File Handling • open(filename, mode) >>> f =open('/tmp/workfile', 'w') >>> print f <open file '/tmp/workfile', mode 'w' at 80a0960> Modes: r, w, a, b, r+, rb, wb, r+b • f.read(size) When sizeisomitted or negative, the entire contentsof the file will be read and returned; If the end of the file hasbeen reached, f.read() will return an empty string(""). • f.readline() readsa single line from the file; a newline character (n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in anewline.
  • 38. • f.readlines() returnsalist containingall the linesof datain the file. If given an optional parameter sizehint, it readsthat many bytes from the file and enough more to complete aline, and returnsthe linesfrom that. • Read words: Memory efficient, fast, and simpler code: for line in f: print line ORfor word in line.split() • f.write(string) writesthe contentsof string to the file, returningNone. To write somethingother than astring, it needsto be converted to astringfirst. • f.tell() returnsan integer givingthe file object’scurrent position in the file, measured in bytesfrom the beginningof the file. • To change the file object’sposition, use f.seek(offset, from_what). • f.close() to close it and free up any system resourcestaken up by the open file. • F.endswitch(“py”) search for fileswith extension py – True/False
  • 39. Some more file operations • Import os • os.remove(filepath) • os.rename(oldzfile, newFile) • os.listdir(dirPath) • os.walk(dirPath)
  • 40. Pickling • Way to achieve object serialization in Python. • Picklingisused when you want to save morecomplexdatatypeslike lists, dictionaries, or classinstancesin afile. • Dumpingand parsinglogicisdifficult to develop and maintain. • Python cPickle module can take almost any Python object and convert it to astringrepresentation; this processis called pickling. • pickle is the standard way to make Python objectswhich can be stored and reused by other programsor by afuture invocation of the same program • Reconstructingthe object from the stringrepresentation is called unpickling. • Between picklingand unpickling, the stringrepresentingthe object may have been stored in afile or data, or sent over anetwork connection to some distant machine. • If you have an object x, and afile object f that’sbeen opened for writing, the simplest way to pickle and unpickle the object is: pickle.dump(x, f) and x =pickle.load(f).
  • 41. Some Concepts • code block: Acode block is apiece of Python program text that can be executed asaunit, such asamodule, aclassdefinition or a function body. • Execution frame: Every code block is assigned an execution frame by Python. 1.Python maintainssome debugginginformation about the code block asapart of the execution frame. 2.The execution frame determinesthe control flow after the execution of the code block completes. 3. It definesnamespacesfor the code block • Namespace: Anamespace is like adictionary. You can consider the names(identifiers/variable names) askeysof this dictionary and the correspondingvaluesto be the objectsto which they point to.
  • 42. Regular Expressions • Regular expressionsare avery powerful tool in any language. They allow patternsto be matched against strings. • Regular expressionsin Python are handled by usingmodule ‘re’. • Import re test ='This is for testingregular expressionsin Python.‘ • result =re.search('(Th)(is)',test) print result.group(0), result.group(1) • result =re.match(‘regular’, test) print result – None (match only at the beginningof string) • ourPattern =re.compile ( '(.*?)(the)' ) testString='This is the dogand the cat.‘ result =ourPattern.match ( testString ) result.group ( 0 )
  • 43. • Regular expressionsuse the backslash character ('') to indicate special formsor to allow special charactersto be used without invokingtheir special meaning. • What if we want to use ‘’ in file path? • The solution isto use Python’sraw stringnotation for regular expression patterns; backslashesare not handled in any special way in astringliteral prefixed with 'r'. • f =open(r"c:Windowsnotepad.exe", "r") • Special characters: ‘.’, ‘^’, ‘$’,’*’,’+’,’?’,{m}, {m,n},’’, ‘| ’, ‘(…)’, ‘d’, ‘D’, ‘s’, ‘S’, ‘w’, ‘W’ • re.split('[a-f]+', '0a3B9’) - ['0', '3', '9']
  • 44. • someString='I have adream.' print re.sub ( 'dream', 'dog', someString) print someString • Regular Expressionsdon’t change the actual string. • Regular Expressionsare very helpful but resource intensive. It should not be used for matchingor findingsimple texts.
  • 45. Some Concepts… • An execution frame createstwo kindsof namespacesfor acode block, namely local and global. The third type of namespace is called the built-in namespace and is created when the Python interpreter loads. • bindingand unbinding: 1.When you define afunction, you bind the formal parameters. 2.You bind aname when you use an import construct (to the namespace of the block which containsthe import statement). 3.When you define a class or a function, using the class and def keywords, you bind the names of the functions and classes and they are available in the containingblock (e.g. amodule) 4. When you do an assignment operation 5.The loop control variable in afor loop construct createsa dynamic binding 6. In an except clause, when you provide argument to the clause
  • 46. Modules • How do I use an existingmodule and the functionsand classes contained in it? To use an existingmodule, you need to first create areference to it in the current namespace. In simple words, you would need to import amodule to use itsfunctionality. • How do I know whether amodule is available in current namespace? You can use dir() built in command to check what all reference variablesare available to you in current namespace. You can go one step ahead and use dir() to see what referencesare available in a particular object's(e.g. module's) namespace by passingobject as the argument. • import random dir(random)
  • 47. Modules… • ImportingModules: import random from random import randint from random import * import random asRand • Accessclassesand functionsof module: For thismodule name and the dot operator should be used. • Importingmodulesin blocks? • From <modulename>import <functionanme>
  • 48. OOPin Python • Python asalanguage is built in object oriented way. Everythingis an object in Python and it really meansso. • When compared with other Object Oriented languageslike C++ and Java, you will observe that most of the featuresare available in Python, in amuch simpler way. You will also observe that many of the accessrelated features(and those loadsof keywordsand rules) are not there. • Inheritance • Multiple inheritance • Abstraction • Polymorphism • Overriding • Operator Overloading • Object Instances
  • 49. Classesin Python • Creatingaclass: classMyClass: pass • Instantiatingaclass: a=MyClass() print a < main .MyClassinstance at 0x01206A08> Yes, it does look like a function call, in fact you can very well have a function and a class with the same name in your Python code. The syntax for instantiation and function call will look exactly the same. Python understandsthe type of any variable based on the object to which it points. So, if MyCode pointsto the body of aclass, it a = MyCode() instantiatesaclassand if it pointsto afunction body, the function is called and aholdsitsreturn values.
  • 50. Amore meaningful Class • classSimpleClass: def init (myVal): self.myVal =myVal def getValue(self): return self.myVal def setValue(self, newVal): self.myVal =new Val • The classSimpleClasshasthree methodsinside it. • The first one hasthe name _ _init_ _ and iscalled the constructor. The name of thismethod should alwaysbe _init_ _. It takesthe argument myVal. Thisvalue isused to initialize an object. Thismethod isused frequently to initialize an object with agiven state, rather than calling a whole set of functionsto set itsstateafter creation.
  • 51. • self is aconvention used by Python programmers to depict the current object reference. Unlike many other OOPlanguages, the current object reference hasto be explicitly defined in Python class definitions- instance variablesand methods. The first argument of every method hasto be self. This argument is used only while definingthe method, in the method call, it is omitted. • Inside the _ _init_ _, it saysself.myVal =myVal. This is asimple assignment operation. Here self.myVal definesan instance variable (object variable). • We see two other methods, which look like normal functions. The difference beingthat they are bound to an object and there is essentially alot of information which need not be passed to them asargumentsevery time, asthey have accessto the object variablesand classvariables(we'll discussabout classvariables later).
  • 52. • getValue() returnsthe value of the self.myVal and setValue() setsit to the value that is passed. • get and set functionsare called accessorsand mutators respectively. They have alot of utility in preventingthe private variablesof aclassfrom gettingmodified inaccurately or unexpectedly. • simpleClassObject =SimpleClass(12) print "Value: " + str(simpleClassObject.getValue()) simpleClassObject.setValue(15) print "Value: " +str(simpleClassObject.getValue()) • Value: 12 Value: 15
  • 53. classA: def init (self): print "Called A" def local(self): print "In local" def load(self): print "Loaded from A" self. local() classB(): def init (self): print "Called B" def load(self): print "Loaded from B“ classC(B,A): def init (self): a=A() print "In C“ c=C() c.load() if hasattr(C, "load"): print "yes"
  • 54. Staticanalysisof code • PyChecker is astatic analysistool that findsbugsin Python source code and warnsabout code complexity and style. • Pylint is another tool that checksif a module satisfiesa coding standard, and also makes it possible to write plug-ins to add a custom feature. • Pylint more popularly used.
  • 55. Exception Handling • The statementsused to deal with exceptionsare raise and except. • def throws(): raiseRuntimeError('this is the error message') def main(): throws() if name ==' main ': main() • Traceback (most recent call last): File "throwing.py", line 10, in <module> main() File "throwing.py", line 7, in main throws() File "throwing.py", line 4, in throwsraise RuntimeError('this isthe error message') RuntimeError: this is the error message
  • 56. • f =None try: f =open("aFileName") f.write(could_make_error()) except IOError: print "Unable to open file" except: # catch all exceptions print "Unexpected error" else: # executed if no exceptionsare raised print "File write completed successfully" finally: # clean-up actions, alwaysexecuted if f: f.close() • Raise – re-raisesthe same exception thrown and dies.
  • 57. Garbage Collection • Python'smemory allocation and de-allocation method is automatic. • Python usestwo strategiesfor memory allocation reference countingand garbage collection. • Reference countingworksby countingthe number of timesan object isreferenced by other objectsin the system. When referencesto an object are removed, the reference count for an object isdecremented. When the reference count becomeszero the object isde-allocated. • Caveat isthat it cannot handle referencecycles. • def make_cycle(): l =[ ] l.append(l)
  • 58. • Garbage collection is ascheduled activity. Python schedulesgarbage collection based upon athreshold of object allocationsand object de-allocations. • import gc print gc.get_threshold() (700,10,10) - This meanswhen the number of allocationsvs. the number of de-allocationsis greater than 700 the automatic garbage collector will run. • The garbage collection can be invoked manually in the following way: import gc gc.collect() • gc.collect() returnsthe number of objectsit hascollected and deallocated.
  • 59. Logging • Loggingis performed by callingmethodson instancesof the Logger class. • The methodsare debug(), info(), warning(), error() and critical(), which mirror the default levels. • import logging LOG_FILENAME='example.log' logging.basicConfig(filename=LOG_FILENAME,level=logging.D EBUG) logging.debug('Thismessage should go to the logfile') • File Contents: DEBUG:root:Thismessage should go to the logfile. • Messageswith higher precedence get logged to the LOG_FILENAME.
  • 60. Python in Astronomy • pFitsio or PyFitsand the NumPy, SciPy, astronomical imagesand tablescan be easily accessed and manipulated asnumerical arrays. • BoA(Bolometer Analysis Package) • Astro-WISE(widefield imagingsystem) • astLib – Python Astronomy Modules- astronomical plots, some statistics, common calculations, coordinate conversions, and manipulatingFITSimageswith World Coordinate System (WCS) information through PyWCSTools
  • 61. References • Python.org • Doughellmann.com • Devshed.com • Testingperspective.com • Network-theory.co.uk • Boodebr.org • Stackoverflow.com