SlideShare ist ein Scribd-Unternehmen logo
1 von 138
Downloaden Sie, um offline zu lesen
Beginning Python

                                    Ankur Shrivastava

                                  Linux User’s Group Manipal


                                    January 29, 2010




Ankur Shrivastava (LUG Manipal)         Beginning Python       January 29, 2010   1 / 44
Who are we?



     Linux User’s Group Manipal
     Life, Universe and FOSS!!
     Believers of Knowledge Sharing
     Most technologically focused
     “group” in University
     LUG Manipal is a non profit
     “Group” alive only on voluntary
     work!!
     http://lugmanipal.org




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   2 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   3 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask
      Slides are based on Documentation so discussions are really
      important, slides are for later reference!!




Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   3 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask
      Slides are based on Documentation so discussions are really
      important, slides are for later reference!!
      Please dont consider sessions as Class (i hate classes)




Ankur Shrivastava (LUG Manipal)   Beginning Python              January 29, 2010   3 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask
      Slides are based on Documentation so discussions are really
      important, slides are for later reference!!
      Please dont consider sessions as Class (i hate classes)
      Speaker is just like any person sitting next to you




Ankur Shrivastava (LUG Manipal)   Beginning Python              January 29, 2010   3 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask
      Slides are based on Documentation so discussions are really
      important, slides are for later reference!!
      Please dont consider sessions as Class (i hate classes)
      Speaker is just like any person sitting next to you
      Documentation is really important




Ankur Shrivastava (LUG Manipal)   Beginning Python              January 29, 2010   3 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask
      Slides are based on Documentation so discussions are really
      important, slides are for later reference!!
      Please dont consider sessions as Class (i hate classes)
      Speaker is just like any person sitting next to you
      Documentation is really important
      Google is your friend




Ankur Shrivastava (LUG Manipal)   Beginning Python              January 29, 2010   3 / 44
Points To Remember!!!


      If you have problem(s) don’t hesitate to ask
      Slides are based on Documentation so discussions are really
      important, slides are for later reference!!
      Please dont consider sessions as Class (i hate classes)
      Speaker is just like any person sitting next to you
      Documentation is really important
      Google is your friend
      If you have questions after this workshop mail me or come to LUG
      Manipal’s forums
      http://forums.lugmanipal.org



Ankur Shrivastava (LUG Manipal)   Beginning Python              January 29, 2010   3 / 44
What is Python?




      Python is a general purpose, object oriented, high level, interpreted
      language
      Developed in early 90’s by Guido Van Rossum
      Its Simple, Portable, Open Source and Powerfull.


Ankur Shrivastava (LUG Manipal)   Beginning Python           January 29, 2010   4 / 44
What we will learn?




      History, Features and basic detail
      Language Basics
      Control Flow
      Functions
      Modules
      File I/O




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   5 / 44
What we require?

      Python interpreter
      Gnu/Linux − > Already installed in all distro’s
      Mac − > Already Installed, if not download http://python.org
      Windows − > Install Python from Python folder provided to you or
      download from http://python.org




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   6 / 44
What we require?

      Python interpreter
      Gnu/Linux − > Already installed in all distro’s
      Mac − > Already Installed, if not download http://python.org
      Windows − > Install Python from Python folder provided to you or
      download from http://python.org
      Text Editor
      Gnu/Linux − > Vim/Emacs/Gedit/Kate/Geany any editor will do
      Mac − > Vim/TextMate or any other Unix like text editor
      Windows − > Notpad++, provided in Notepadpp folder or download
      http://notepad-plus.sourceforge.net
      Don’t use Notepad (MS) for editing code, always use Notepad++




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   6 / 44
What we require?

      Python interpreter
      Gnu/Linux − > Already installed in all distro’s
      Mac − > Already Installed, if not download http://python.org
      Windows − > Install Python from Python folder provided to you or
      download from http://python.org
      Text Editor
      Gnu/Linux − > Vim/Emacs/Gedit/Kate/Geany any editor will do
      Mac − > Vim/TextMate or any other Unix like text editor
      Windows − > Notpad++, provided in Notepadpp folder or download
      http://notepad-plus.sourceforge.net
      Don’t use Notepad (MS) for editing code, always use Notepad++
      Documentation for Python present in Docs folder, web
      http://python.org/doc/
      Set editor to expand tab to 4 spaces.

Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   6 / 44
Where is it used?



      Used extensively in web => Django, TurboGears, Plone, etc
      communicating with Databases => MySQL, PostgreSQL, Oracle, etc
      Desktop GUI => GTK+, QT, Tk, etc
      Scientific Computing => Scipy, Scientific Python, etc
      Network Programming with frameworks/libraries like Twisted, etc
      Software Development => SCons, Buildbot, Roundup, etc
      Games and 3D graphics => pyGame, PyKyra, etc




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   7 / 44
Difference from C/C++/Java




      No pointers ( similar to Java )




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   8 / 44
Difference from C/C++/Java




      No pointers ( similar to Java )
      No prior compilation to Bytecode(?), directly interpreted




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   8 / 44
Difference from C/C++/Java




      No pointers ( similar to Java )
      No prior compilation to Bytecode(?), directly interpreted
      Includes garbage collector(?)




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   8 / 44
Difference from C/C++/Java




      No pointers ( similar to Java )
      No prior compilation to Bytecode(?), directly interpreted
      Includes garbage collector(?)
      Can be used in Procedure(?)/Object Oriented(?) approach/style




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   8 / 44
Difference from C/C++/Java




      No pointers ( similar to Java )
      No prior compilation to Bytecode(?), directly interpreted
      Includes garbage collector(?)
      Can be used in Procedure(?)/Object Oriented(?) approach/style
      English like syntax




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   8 / 44
Difference from C/C++/Java




      No pointers ( similar to Java )
      No prior compilation to Bytecode(?), directly interpreted
      Includes garbage collector(?)
      Can be used in Procedure(?)/Object Oriented(?) approach/style
      English like syntax
      Very good for scripting




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   8 / 44
Versions of Python


      What do you mean by versions, Python is a language ?




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   9 / 44
Versions of Python


      What do you mean by versions, Python is a language ?
      Ans) Python as a language keeps on evolving and new features are
      being added to the language, here by versions we refer to the python
      interpreter version, new features are added to python interpreter in
      every release.




Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   9 / 44
Versions of Python


      What do you mean by versions, Python is a language ?
      Ans) Python as a language keeps on evolving and new features are
      being added to the language, here by versions we refer to the python
      interpreter version, new features are added to python interpreter in
      every release.
      important versions are Python 2.6/2.7 and 3.0/3.1
      we will focus on Python 2.6/2.7 and not Python 3.0/3.1
      Python 3.0/3.1 is the future of Python and has non compatible
      changes from Python 2.X, currently there is less support of Python
      3.X and it will take a few years before it matches with that of Python
      2.X



Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   9 / 44
Interactive session



      What is interactive session ?




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   10 / 44
Interactive session



      What is interactive session ?
      Allows you to test your idea/logic/code and play arround with it,
      works as a shell, you can try out almost anything but whatever you
      type is note saved.




Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   10 / 44
Interactive session



      What is interactive session ?
      Allows you to test your idea/logic/code and play arround with it,
      works as a shell, you can try out almost anything but whatever you
      type is note saved.
      How to start an interactive session ?




Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   10 / 44
Interactive session



      What is interactive session ?
      Allows you to test your idea/logic/code and play arround with it,
      works as a shell, you can try out almost anything but whatever you
      type is note saved.
      How to start an interactive session ?
      On Linux open terminal and type python
      On Windows, open Python in program files.




Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   10 / 44
Interactive session



      What is interactive session ?
      Allows you to test your idea/logic/code and play arround with it,
      works as a shell, you can try out almost anything but whatever you
      type is note saved.
      How to start an interactive session ?
      On Linux open terminal and type python
      On Windows, open Python in program files.
      to exit an interactive session type quit() or
      press Ctrl + D on Unix like machine
      press Ctrl + Z on Windows machine




Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   10 / 44
Language Basics




Ankur Shrivastava (LUG Manipal)       Beginning Python   January 29, 2010   11 / 44
Indentation

      In Python indentation is very important.
      There are no end/begin delimiteres like { }
      Grouping of statements are done on basis of their indentation.
      Statements at same indentation are grouped together in a single
      block.
      Its recommended to use 4 spaces instead of tabs.
      # marks start of comment (single line)




Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   12 / 44
Indentation

      In Python indentation is very important.
      There are no end/begin delimiteres like { }
      Grouping of statements are done on basis of their indentation.
      Statements at same indentation are grouped together in a single
      block.
      Its recommended to use 4 spaces instead of tabs.
      # marks start of comment (single line)

sample code
a = 10
if a/10 == 1:
   print ‘‘i think’’ # notice 4 spaces before this print
   print ‘‘the value was’’ # and this print
   print ‘‘10’’ # and this print

Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   12 / 44
Numbers




      Integer numbers =>
      decimal -> 1, 44, -44, 2309
      octal -> 01, 022, 077
      hexadecimal -> 0x1, 0x23, 0x3f
      long -> 121212L, 2323232938238293829382938293283293825L




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   13 / 44
Numbers




      Integer numbers =>
      decimal -> 1, 44, -44, 2309
      octal -> 01, 022, 077
      hexadecimal -> 0x1, 0x23, 0x3f
      long -> 121212L, 2323232938238293829382938293283293825L
      Floating point => 0.0, 0.32, 2.23e2




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   13 / 44
Numbers




      Integer numbers =>
      decimal -> 1, 44, -44, 2309
      octal -> 01, 022, 077
      hexadecimal -> 0x1, 0x23, 0x3f
      long -> 121212L, 2323232938238293829382938293283293825L
      Floating point => 0.0, 0.32, 2.23e2
      Complex numbers => 10+10j, 1+2j, 3-4j where j = −11/2




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   13 / 44
String

      There is no character data type in python
      Strings can be quoted in single (’,“) or triple (”’,“““) quotes
      Special characters can be inserted by using the escape character 
      Some commonly used escape sequesces =>
       for a  in string
      ’ for ’ in a string
      ” for “ in a string
      n for a newline
      r for cariage return
      t for tab




Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   14 / 44
String

      There is no character data type in python
      Strings can be quoted in single (’,“) or triple (”’,“““) quotes
      Special characters can be inserted by using the escape character 
      Some commonly used escape sequesces =>
       for a  in string
      ’ for ’ in a string
      ” for “ in a string
      n for a newline
      r for cariage return
      t for tab

Example
>>>s = ’Line contaning ’ and  in itself’
>>>print s
Line contaning ’ and  in itself
Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   14 / 44
Tuple
      Tuple is an immutable(?) ordered sequence of items(?)




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   15 / 44
Tuple
      Tuple is an immutable(?) ordered sequence of items(?)
      Tuples can be considered as constant array
      There can have nesting of tuples one inside other
      Elements in a Tuple does not have to be of same type
      Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
      Elements can be accessed in way similar to an array




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   15 / 44
Tuple
      Tuple is an immutable(?) ordered sequence of items(?)
      Tuples can be considered as constant array
      There can have nesting of tuples one inside other
      Elements in a Tuple does not have to be of same type
      Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
      Elements can be accessed in way similar to an array

Example
>>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
>>> t[0]




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   15 / 44
Tuple
      Tuple is an immutable(?) ordered sequence of items(?)
      Tuples can be considered as constant array
      There can have nesting of tuples one inside other
      Elements in a Tuple does not have to be of same type
      Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
      Elements can be accessed in way similar to an array

Example
>>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
>>> t[0]
1
>>> t[4]




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   15 / 44
Tuple
      Tuple is an immutable(?) ordered sequence of items(?)
      Tuples can be considered as constant array
      There can have nesting of tuples one inside other
      Elements in a Tuple does not have to be of same type
      Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
      Elements can be accessed in way similar to an array

Example
>>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
>>> t[0]
1
>>> t[4]
’abc’
>>> t[6]


Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   15 / 44
Tuple
      Tuple is an immutable(?) ordered sequence of items(?)
      Tuples can be considered as constant array
      There can have nesting of tuples one inside other
      Elements in a Tuple does not have to be of same type
      Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
      Elements can be accessed in way similar to an array

Example
>>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11))
>>> t[0]
1
>>> t[4]
’abc’
>>> t[6]
(10,11)
Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   15 / 44
List

       List is a mutable ordered sequence of items
       Items in a list can be added or removed
       There can have nesting of lists one inside other
       Elements in a List does not have to be of same type
       Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
       Data access and assignment similar to an array




 Ankur Shrivastava (LUG Manipal)   Beginning Python    January 29, 2010   16 / 44
List

       List is a mutable ordered sequence of items
       Items in a list can be added or removed
       There can have nesting of lists one inside other
       Elements in a List does not have to be of same type
       Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
       Data access and assignment similar to an array

Example
>>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
>>> l[0]




 Ankur Shrivastava (LUG Manipal)   Beginning Python    January 29, 2010   16 / 44
List

       List is a mutable ordered sequence of items
       Items in a list can be added or removed
       There can have nesting of lists one inside other
       Elements in a List does not have to be of same type
       Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
       Data access and assignment similar to an array

Example
>>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
>>> l[0]
1
>>> l[6]




 Ankur Shrivastava (LUG Manipal)   Beginning Python    January 29, 2010   16 / 44
List

       List is a mutable ordered sequence of items
       Items in a list can be added or removed
       There can have nesting of lists one inside other
       Elements in a List does not have to be of same type
       Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
       Data access and assignment similar to an array

Example
>>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
>>> l[0]
1
>>> l[6]
[10,11]
>>> l[6][0]

 Ankur Shrivastava (LUG Manipal)   Beginning Python    January 29, 2010   16 / 44
List

       List is a mutable ordered sequence of items
       Items in a list can be added or removed
       There can have nesting of lists one inside other
       Elements in a List does not have to be of same type
       Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
       Data access and assignment similar to an array

Example
>>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]]
>>> l[0]
1
>>> l[6]
[10,11]
>>> l[6][0]
10
 Ankur Shrivastava (LUG Manipal)   Beginning Python    January 29, 2010   16 / 44
Dictionaries
      Dictionaries are containers which store items in key/value pairs(?).
      Dictionaries are mutable but does not have any defined sequence.
      Key can be any integer or string and Value can be any item.
      As in Dictionaries values can be accessed by using the key.
      Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
      Value can be accessed using the key and keys are unique.




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   17 / 44
Dictionaries
      Dictionaries are containers which store items in key/value pairs(?).
      Dictionaries are mutable but does not have any defined sequence.
      Key can be any integer or string and Value can be any item.
      As in Dictionaries values can be accessed by using the key.
      Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
      Value can be accessed using the key and keys are unique.

Example
>>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
>>> d[’key’]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   17 / 44
Dictionaries
      Dictionaries are containers which store items in key/value pairs(?).
      Dictionaries are mutable but does not have any defined sequence.
      Key can be any integer or string and Value can be any item.
      As in Dictionaries values can be accessed by using the key.
      Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
      Value can be accessed using the key and keys are unique.

Example
>>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
>>> d[’key’]
’value’
>>> d[1]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   17 / 44
Dictionaries
      Dictionaries are containers which store items in key/value pairs(?).
      Dictionaries are mutable but does not have any defined sequence.
      Key can be any integer or string and Value can be any item.
      As in Dictionaries values can be accessed by using the key.
      Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
      Value can be accessed using the key and keys are unique.

Example
>>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
>>> d[’key’]
’value’
>>> d[1]
’value’
>>> d[’abc’]


Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   17 / 44
Dictionaries
      Dictionaries are containers which store items in key/value pairs(?).
      Dictionaries are mutable but does not have any defined sequence.
      Key can be any integer or string and Value can be any item.
      As in Dictionaries values can be accessed by using the key.
      Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
      Value can be accessed using the key and keys are unique.

Example
>>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] }
>>> d[’key’]
’value’
>>> d[1]
’value’
>>> d[’abc’]
[1, 2, 3, 4]
Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   17 / 44
Index and Slices
      List, Tuple, String, etc can be sliced to get part of data from them.
      Index -> similar to array index refers to position of data.
      Slice -> use to reterive data within particular index.

Example
>>> s = “LUG MANIPAL”
>>> s[0]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   18 / 44
Index and Slices
      List, Tuple, String, etc can be sliced to get part of data from them.
      Index -> similar to array index refers to position of data.
      Slice -> use to reterive data within particular index.

Example
>>> s = “LUG MANIPAL”
>>> s[0]
’L’
>>> s[2]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   18 / 44
Index and Slices
      List, Tuple, String, etc can be sliced to get part of data from them.
      Index -> similar to array index refers to position of data.
      Slice -> use to reterive data within particular index.

Example
>>>     s = “LUG MANIPAL”
>>>     s[0]
’L’
>>>     s[2]
’G’
>>>     s[0:3]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   18 / 44
Index and Slices
      List, Tuple, String, etc can be sliced to get part of data from them.
      Index -> similar to array index refers to position of data.
      Slice -> use to reterive data within particular index.

Example
>>> s = “LUG MANIPAL”
>>> s[0]
’L’
>>> s[2]
’G’
>>> s[0:3]
’LUG’     from 0 till 3, not including 3!!
>>> s[:3]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   18 / 44
Index and Slices
      List, Tuple, String, etc can be sliced to get part of data from them.
      Index -> similar to array index refers to position of data.
      Slice -> use to reterive data within particular index.

Example
>>> s = “LUG MANIPAL”
>>> s[0]
’L’
>>> s[2]
’G’
>>> s[0:3]
’LUG’     from 0 till 3, not including 3!!
>>> s[:3]
’LUG’     from start till 3, not including 3!!
>>> s[4:]

Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   18 / 44
Index and Slices
      List, Tuple, String, etc can be sliced to get part of data from them.
      Index -> similar to array index refers to position of data.
      Slice -> use to reterive data within particular index.

Example
>>> s = “LUG MANIPAL”
>>> s[0]
’L’
>>> s[2]
’G’
>>> s[0:3]
’LUG’     from 0 till 3, not including 3!!
>>> s[:3]
’LUG’     from start till 3, not including 3!!
>>> s[4:]
’MANIPAL’      from 4 till end
Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   18 / 44
Index and Slices contd.


Example
>>> s = “LUG MANIPAL”
>>> s[:11:2]




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   19 / 44
Index and Slices contd.


Example
>>> s = “LUG MANIPAL”
>>> s[:11:2]
’LGMNPL’     from start till 11, every 2nd element
>>> s[:11:3]




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   19 / 44
Index and Slices contd.


Example
>>> s = “LUG MANIPAL”
>>> s[:11:2]
’LGMNPL’      from start till 11, every 2nd element
>>> s[:11:3]
’L NA’    from start till 11, every 3rd element
>>> s[-1]




Ankur Shrivastava (LUG Manipal)   Beginning Python    January 29, 2010   19 / 44
Index and Slices contd.


Example
>>> s = “LUG MANIPAL”
>>> s[:11:2]
’LGMNPL’       from start till 11, every 2nd element
>>> s[:11:3]
’L NA’     from start till 11, every 3rd element
>>> s[-1]
’L’    last element
>>> s[-7:]




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   19 / 44
Index and Slices contd.


Example
>>> s = “LUG MANIPAL”
>>> s[:11:2]
’LGMNPL’       from start till 11, every 2nd element
>>> s[:11:3]
’L NA’     from start till 11, every 3rd element
>>> s[-1]
’L’    last element
>>> s[-7:]
’MANIPAL’
>>> s[:-8]




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   19 / 44
Index and Slices contd.


Example
>>> s = “LUG MANIPAL”
>>> s[:11:2]
’LGMNPL’       from start till 11, every 2nd element
>>> s[:11:3]
’L NA’     from start till 11, every 3rd element
>>> s[-1]
’L’    last element
>>> s[-7:]
’MANIPAL’
>>> s[:-8]
’LUG’



Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   19 / 44
Variables
      There no prior type declaration required for variables.
      A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
      Int, String, Complex, or any other object ).




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   20 / 44
Variables
      There no prior type declaration required for variables.
      A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
      Int, String, Complex, or any other object ).
      Variables are references(?) to allocated memory(?).




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   20 / 44
Variables
      There no prior type declaration required for variables.
      A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
      Int, String, Complex, or any other object ).
      Variables are references(?) to allocated memory(?).
      References are always shared(?).




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   20 / 44
Variables
      There no prior type declaration required for variables.
      A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
      Int, String, Complex, or any other object ).
      Variables are references(?) to allocated memory(?).
      References are always shared(?).
      use functions list(old list) and dict(old dict) to obtain copy.




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   20 / 44
Variables
     There no prior type declaration required for variables.
     A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
     Int, String, Complex, or any other object ).
     Variables are references(?) to allocated memory(?).
     References are always shared(?).
     use functions list(old list) and dict(old dict) to obtain copy.
Note Be carefull with references they can lead to nasty things!!!




 Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   20 / 44
Variables
     There no prior type declaration required for variables.
     A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
     Int, String, Complex, or any other object ).
     Variables are references(?) to allocated memory(?).
     References are always shared(?).
     use functions list(old list) and dict(old dict) to obtain copy.
Note Be carefull with references they can lead to nasty things!!!

 NOTE
 >>> l = [1, 2, 3, 4]
 >>> d = {’key’:l}
 >>> d[’key’]




 Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   20 / 44
Variables
     There no prior type declaration required for variables.
     A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
     Int, String, Complex, or any other object ).
     Variables are references(?) to allocated memory(?).
     References are always shared(?).
     use functions list(old list) and dict(old dict) to obtain copy.
Note Be carefull with references they can lead to nasty things!!!

 NOTE
 >>> l = [1, 2, 3, 4]
 >>> d = {’key’:l}
 >>> d[’key’]
 [1, 2, 3, 4]




 Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   20 / 44
Variables
     There no prior type declaration required for variables.
     A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
     Int, String, Complex, or any other object ).
     Variables are references(?) to allocated memory(?).
     References are always shared(?).
     use functions list(old list) and dict(old dict) to obtain copy.
Note Be carefull with references they can lead to nasty things!!!

 NOTE
 >>> l = [1, 2, 3, 4]
 >>> d = {’key’:l}
 >>> d[’key’]
 [1, 2, 3, 4]
 >>> l[0] = 0
 >>> d[’key’]


 Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   20 / 44
Variables
     There no prior type declaration required for variables.
     A variable can reffer to any Data Type ( like Tuple, List, Dictionary,
     Int, String, Complex, or any other object ).
     Variables are references(?) to allocated memory(?).
     References are always shared(?).
     use functions list(old list) and dict(old dict) to obtain copy.
Note Be carefull with references they can lead to nasty things!!!

 NOTE
 >>> l = [1, 2, 3, 4]
 >>> d = {’key’:l}
 >>> d[’key’]
 [1, 2, 3, 4]
 >>> l[0] = 0
 >>> d[’key’]
 [0, 2, 3, 4]
 Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   20 / 44
Helpful Functions
      help(<obj>) provides help/documentaion for the object using
      pydoc.help.




Ankur Shrivastava (LUG Manipal)   Beginning Python      January 29, 2010   21 / 44
Helpful Functions
      help(<obj>) provides help/documentaion for the object using
      pydoc.help.
      dir(<obj>) lists the attributes/methods avaliable for that object.
      attributes/methods starting with / are internal attributes/methods
      and should not be used unless you know what you are doing.




Ankur Shrivastava (LUG Manipal)   Beginning Python      January 29, 2010   21 / 44
Helpful Functions
      help(<obj>) provides help/documentaion for the object using
      pydoc.help.
      dir(<obj>) lists the attributes/methods avaliable for that object.
      attributes/methods starting with / are internal attributes/methods
      and should not be used unless you know what you are doing.
      dir() returns names in current scope




Ankur Shrivastava (LUG Manipal)   Beginning Python      January 29, 2010   21 / 44
Helpful Functions
      help(<obj>) provides help/documentaion for the object using
      pydoc.help.
      dir(<obj>) lists the attributes/methods avaliable for that object.
      attributes/methods starting with / are internal attributes/methods
      and should not be used unless you know what you are doing.
      dir() returns names in current scope

Example
>>> l = [1, 2, 3]
>>> dir(l)
[’ add ’, ’ class ’, ’ contains ’, ’ delattr ’, ’ delitem ’, ’ delslice ’,
’ doc ’, ’ eq ’, ’ format ’, ’ ge ’, ’ getattribute ’, ’ getitem ’,
’ getslice ’, ’ gt ’, ’ hash ’, ’ iadd ’, ’ imul ’, ’ init ’, ’ iter ’, ’ le ’,
’ len ’, ’ lt ’, ’ mul ’, ’ ne ’, ’ new ’, ’ reduce ’, ’ reduce ex ’,
’ repr ’, ’ reversed ’, ’ rmul ’, ’ setattr ’, ’ setitem ’, ’ setslice ’,
’ sizeof ’, ’ str ’, ’ subclasshook ’, ’append’, ’count’, ’extend’, ’index’,
’insert’, ’pop’, ’remove’, ’reverse’, ’sort’]
Ankur Shrivastava (LUG Manipal)   Beginning Python             January 29, 2010   21 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   22 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.
      l.extend(< List >) − > adds all element in < list > to ’l’.




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   22 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.
      l.extend(< List >) − > adds all element in < list > to ’l’.
      l.insert(< pos >, < val >) − > Inserts < val > at position < pos >.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   22 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.
      l.extend(< List >) − > adds all element in < list > to ’l’.
      l.insert(< pos >, < val >) − > Inserts < val > at position < pos >.
      l.remove(< val >) − > removes first element matching < val >,
      raises ValueError if no such value exists.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   22 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.
      l.extend(< List >) − > adds all element in < list > to ’l’.
      l.insert(< pos >, < val >) − > Inserts < val > at position < pos >.
      l.remove(< val >) − > removes first element matching < val >,
      raises ValueError if no such value exists.
      l.index(< val >) − > returns index of first occurence of < val >,
      raises ValueError if no such value exists.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   22 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.
      l.extend(< List >) − > adds all element in < list > to ’l’.
      l.insert(< pos >, < val >) − > Inserts < val > at position < pos >.
      l.remove(< val >) − > removes first element matching < val >,
      raises ValueError if no such value exists.
      l.index(< val >) − > returns index of first occurence of < val >,
      raises ValueError if no such value exists.
      l.pop(< index >) − > removes element at < index >, if no index is
      specified last element is returned.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   22 / 44
List Operations

      l.append(< val >) − > adds < val > at the end of list.
      l.extend(< List >) − > adds all element in < list > to ’l’.
      l.insert(< pos >, < val >) − > Inserts < val > at position < pos >.
      l.remove(< val >) − > removes first element matching < val >,
      raises ValueError if no such value exists.
      l.index(< val >) − > returns index of first occurence of < val >,
      raises ValueError if no such value exists.
      l.pop(< index >) − > removes element at < index >, if no index is
      specified last element is returned.

Example
>>> l = [1, 2, 3, 4, 5, 6, 7]
>>> l.append(8)
>>> l
[1, 2, 3, 4, 5, 6, 7, 8]
Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   22 / 44
Dictionary Operations
      d.has key(< val >) − > returns true if key by < val > exists, else
      returns false.
      d.items() − > returns list of 2 value tuple, with first element key and
      second value.
      d.keys() − > returns list of all keys in dictionary.
      d.values() − > returns list of all values in dictionary.
      d.iteritems() − > returns an iteratable object of dictionay, giving a
      tuple of (key, value) on every iteration.

Example
>>> d = { ’a’:1 , ’abc’:878 }
>>> for i,j in d.iteritems():
...    print i, j
...
a1
abc 878
Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   23 / 44
Control Flow




Ankur Shrivastava (LUG Manipal)      Beginning Python   January 29, 2010   24 / 44
Input and Output
Input
    to take input (string) from user we use function raw input().
    function input() evaluates the input as python expression.
    we use functions int(), long(), float(), and str() to convert the
    input to desired type.




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   25 / 44
Input and Output
Input
    to take input (string) from user we use function raw input().
    function input() evaluates the input as python expression.
    we use functions int(), long(), float(), and str() to convert the
    input to desired type.
Output
    print is a keyword for giving output to a console or a file.
    print can take multiple arguments saperated by comma (, )
    if you dont want a newline add comma (, ) at the end.




Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   25 / 44
Input and Output
Input
    to take input (string) from user we use function raw input().
    function input() evaluates the input as python expression.
    we use functions int(), long(), float(), and str() to convert the
    input to desired type.
Output
    print is a keyword for giving output to a console or a file.
    print can take multiple arguments saperated by comma (, )
    if you dont want a newline add comma (, ) at the end.
Example
>>> val = raw input(“Enter a number: ”)
Enter a number: 123
>>> val = int(val) + 1
>>> print “Number is”, val
Number is 124
Ankur Shrivastava (LUG Manipal)   Beginning Python     January 29, 2010   25 / 44
if
    if is a conditional keyword, for a simple “if then else” clause in english.
    Header lines(?) are always concluded with a “:” followed by indented
    block of statements.
    optionally if can be followed by an “else if” which is known as “elif”
    in Python.
    expressions can be logically connected by using “or”/“and”.
Tip Just remember we need to put “:” where every we used “{}” in other
    languages, and statements following ’if’ should always be indented.




 Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   26 / 44
if
    if is a conditional keyword, for a simple “if then else” clause in english.
    Header lines(?) are always concluded with a “:” followed by indented
    block of statements.
    optionally if can be followed by an “else if” which is known as “elif”
    in Python.
    expressions can be logically connected by using “or”/“and”.
Tip Just remember we need to put “:” where every we used “{}” in other
    languages, and statements following ’if’ should always be indented.

Example
if a == 1:
     print “value of a is 1”
elif a == 2:
     print “value of a is 2”
else:
     print “value of a is not 1 or 2”
 Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   26 / 44
while

      while is used for repeated execution of a block of code till a
      condiction holds true.
      in Python while has an optional else clause which executes when the
      condiction evaluates to false.
      following values are considered flase -> None, False, any numeric type
      equal to zero, any empty sequence (), [],‘’ or any empty mapping {}.

Example
limit = 5
val = 0
while val < limit :
     print val,
     val +=1
Output :

Ankur Shrivastava (LUG Manipal)   Beginning Python           January 29, 2010   27 / 44
while

      while is used for repeated execution of a block of code till a
      condiction holds true.
      in Python while has an optional else clause which executes when the
      condiction evaluates to false.
      following values are considered flase -> None, False, any numeric type
      equal to zero, any empty sequence (), [],‘’ or any empty mapping {}.

Example
limit = 5
val = 0
while val < limit :
     print val,
     val +=1
Output :
01234
Ankur Shrivastava (LUG Manipal)   Beginning Python           January 29, 2010   27 / 44
for


       for is a sequence iterator(?).




 Ankur Shrivastava (LUG Manipal)    Beginning Python   January 29, 2010   28 / 44
for


       for is a sequence iterator(?).
       for works on strings, lists, tuples, etc.
       use range/xrange to generate lists
       range(0,4) − > [0, 1, 2, 3]
       range(0,6,2) − > [0, 2, 4]
       xrange works as a iterator and does not generate a list (?)




 Ankur Shrivastava (LUG Manipal)     Beginning Python        January 29, 2010   28 / 44
for


       for is a sequence iterator(?).
       for works on strings, lists, tuples, etc.
       use range/xrange to generate lists
       range(0,4) − > [0, 1, 2, 3]
       range(0,6,2) − > [0, 2, 4]
       xrange works as a iterator and does not generate a list (?)

Example
for item in range(1, 5) :
     print item,
Output:



 Ankur Shrivastava (LUG Manipal)     Beginning Python        January 29, 2010   28 / 44
for


       for is a sequence iterator(?).
       for works on strings, lists, tuples, etc.
       use range/xrange to generate lists
       range(0,4) − > [0, 1, 2, 3]
       range(0,6,2) − > [0, 2, 4]
       xrange works as a iterator and does not generate a list (?)

Example
for item in range(1, 5) :
     print item,
Output:
1234


 Ankur Shrivastava (LUG Manipal)     Beginning Python        January 29, 2010   28 / 44
break / continue
break
    used for loop termination
    if nested, terminates the inner loop
continue
    terminates the current iteration and starts the next
    it does not terminate the loop




Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   29 / 44
break / continue
break
    used for loop termination
    if nested, terminates the inner loop
continue
    terminates the current iteration and starts the next
    it does not terminate the loop

Example
for i in range(1,10) :
     if i == 6 :
          break
     if i == 3 :
          continue
     print i,
Output:

Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   29 / 44
break / continue
break
    used for loop termination
    if nested, terminates the inner loop
continue
    terminates the current iteration and starts the next
    it does not terminate the loop

Example
for i in range(1,10) :
     if i == 6 :
          break
     if i == 3 :
          continue
     print i,
Output:
1245
Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   29 / 44
List Comprehensions

      Normal use of “for” loop is to iterate and build a new list
      List comprehensions simplifies the above task
      Syntax − >
      [ <expression> for <target> in <iterable> <condiction> ]
      there can be multiples statements.

Example
>>> [ x*2 for x in range(1,5) ]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   30 / 44
List Comprehensions

      Normal use of “for” loop is to iterate and build a new list
      List comprehensions simplifies the above task
      Syntax − >
      [ <expression> for <target> in <iterable> <condiction> ]
      there can be multiples statements.

Example
>>> [ x*2 for x in range(1,5) ]
[2, 4, 6, 8]
>>> [ x for x in range(0,10) if x%2 == 0 and x > 2]




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   30 / 44
List Comprehensions

      Normal use of “for” loop is to iterate and build a new list
      List comprehensions simplifies the above task
      Syntax − >
      [ <expression> for <target> in <iterable> <condiction> ]
      there can be multiples statements.

Example
>>> [ x*2 for x in range(1,5) ]
[2, 4, 6, 8]
>>> [ x for x in range(0,10) if x%2 == 0 and x > 2]
[4, 6, 8]
>>> [ x+y for x in range(1,4) for y in range(1,4)]



Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   30 / 44
List Comprehensions

      Normal use of “for” loop is to iterate and build a new list
      List comprehensions simplifies the above task
      Syntax − >
      [ <expression> for <target> in <iterable> <condiction> ]
      there can be multiples statements.

Example
>>> [ x*2 for x in range(1,5) ]
[2, 4, 6, 8]
>>> [ x for x in range(0,10) if x%2 == 0 and x > 2]
[4, 6, 8]
>>> [ x+y for x in range(1,4) for y in range(1,4)]
[2, 3, 4, 3, 4, 5, 4, 5, 6]


Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   30 / 44
Functions




Ankur Shrivastava (LUG Manipal)    Beginning Python   January 29, 2010   31 / 44
What are Functions?
      A function is a group of statements that executes on request.
      In Python functions are also objects.
      function return type is not required.
      if function does not return any value, default value of None is
      returned.
      a function can take another function name as argument and return a
      function name (as in functional programming languages).
      a function is defined using the keyoword def followed by function
      name and parameters




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   32 / 44
What are Functions?
      A function is a group of statements that executes on request.
      In Python functions are also objects.
      function return type is not required.
      if function does not return any value, default value of None is
      returned.
      a function can take another function name as argument and return a
      function name (as in functional programming languages).
      a function is defined using the keyoword def followed by function
      name and parameters
Example
>>> def abc(arg):
···   print arg
···
>>> abc(“Hello”)
Hello
Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   32 / 44
Parameters
      Default Value is the value assigned to function argument in function
      defination.
      Types of Parameters
       Mandatory Parameters with no default values.
          Optional Parameters with default values.
      At function call values for all mandatory parameters are required.
      There is no function overloading in python.




Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   33 / 44
Parameters
      Default Value is the value assigned to function argument in function
      defination.
      Types of Parameters
       Mandatory Parameters with no default values.
          Optional Parameters with default values.
      At function call values for all mandatory parameters are required.
      There is no function overloading in python.

Example
def abc (arg1,arg2=10): # arg2 has default value of 10
    print arg1, arg2
abc(1)
abc(2,3)
Output :



Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   33 / 44
Parameters
      Default Value is the value assigned to function argument in function
      defination.
      Types of Parameters
       Mandatory Parameters with no default values.
          Optional Parameters with default values.
      At function call values for all mandatory parameters are required.
      There is no function overloading in python.

Example
def abc (arg1,arg2=10): # arg2 has default value of 10
    print arg1, arg2
abc(1)
abc(2,3)
Output :
1 10

Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   33 / 44
Parameters
      Default Value is the value assigned to function argument in function
      defination.
      Types of Parameters
       Mandatory Parameters with no default values.
          Optional Parameters with default values.
      At function call values for all mandatory parameters are required.
      There is no function overloading in python.

Example
def abc (arg1,arg2=10): # arg2 has default value of 10
    print arg1, arg2
abc(1)
abc(2,3)
Output :
1 10
23
Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   33 / 44
Modules




Ankur Shrivastava (LUG Manipal)    Beginning Python   January 29, 2010   34 / 44
What are Modules?

      Modules group code and data for reuse.
      Modules or a part of modules can be used in other code using import
      or from statements.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   35 / 44
What are Modules?

      Modules group code and data for reuse.
      Modules or a part of modules can be used in other code using import
      or from statements.
import
      Syntax − >
      import module [ as othername ]
      import imports whole of specified module in the namespace
      module/othername.




Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   35 / 44
What are Modules?

      Modules group code and data for reuse.
      Modules or a part of modules can be used in other code using import
      or from statements.
import
      Syntax − >
      import module [ as othername ]
      import imports whole of specified module in the namespace
      module/othername.
from
      Syntax − >
      from module import something [ as somethingelse ]
      using from import something inside the current namespace as
      something/somethingelse.

Ankur Shrivastava (LUG Manipal)   Beginning Python        January 29, 2010   35 / 44
How to make Module?



      Any python file (.py ) can work as a module.
      If the file is written to execute when invoked, it is executed when
      imported.
      To allow a file to executed when invoked and avoid when imported we
      compare variable “ name ”
      Python file executing as main code has variable “ name ” set to
      “ main ”
      Python file executing as module has variable “ name ” set to the
      module name




Ankur Shrivastava (LUG Manipal)   Beginning Python          January 29, 2010   36 / 44
Lets create a file example.py, which we will use to describe modules
example.py
# some functions
def div(a,b):
     print a/b
# code that will execute in every case
print “Hi”
# code that will execute only if file invoked
if name == “ main ”:
     mul(2,2)
     print “not as module”
else:
     print “as module”

Try import and from on example.py
and also try executing the file.

Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   37 / 44
File I/O




Ankur Shrivastava (LUG Manipal)    Beginning Python   January 29, 2010   38 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are




 Ankur Shrivastava (LUG Manipal)   Beginning Python       January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.




 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.




 Ankur Shrivastava (LUG Manipal)        Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.
              ’a’ opens a file in write only mode, if file exists new data in added at
              the end, else a new file is created.




 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.
              ’a’ opens a file in write only mode, if file exists new data in added at
              the end, else a new file is created.
              ’r+’ file is opened in read and write mode, but file must exist.




 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.
              ’a’ opens a file in write only mode, if file exists new data in added at
              the end, else a new file is created.
              ’r+’ file is opened in read and write mode, but file must exist.
              ’w+’ file is opened in read and write mode, file is truncated if exists,
              else a new file is created.




 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.
              ’a’ opens a file in write only mode, if file exists new data in added at
              the end, else a new file is created.
              ’r+’ file is opened in read and write mode, but file must exist.
              ’w+’ file is opened in read and write mode, file is truncated if exists,
              else a new file is created.
              ’a+’ file is opened in read and write mode, if file exists new data in
              added at the end, else a new file is created.




 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.
              ’a’ opens a file in write only mode, if file exists new data in added at
              the end, else a new file is created.
              ’r+’ file is opened in read and write mode, but file must exist.
              ’w+’ file is opened in read and write mode, file is truncated if exists,
              else a new file is created.
              ’a+’ file is opened in read and write mode, if file exists new data in
              added at the end, else a new file is created.
              append ’b’ to the mode to open file in binary mode.




 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File
       file is a built-in type in Python.
       Allows access to files in an Operating System independent manner.
       Different modes to access a file are
              ’r’ opens an already existing file in read only mode.
              ’w’ opens a file in write only mode, if file exists it is truncated else a
              new file in created.
              ’a’ opens a file in write only mode, if file exists new data in added at
              the end, else a new file is created.
              ’r+’ file is opened in read and write mode, but file must exist.
              ’w+’ file is opened in read and write mode, file is truncated if exists,
              else a new file is created.
              ’a+’ file is opened in read and write mode, if file exists new data in
              added at the end, else a new file is created.
              append ’b’ to the mode to open file in binary mode.
       modes are passed to function open which is used to open a file
       Synatx − >
       <file obj> = open(<file name>,<mode>,bufsize=-1)
 Ankur Shrivastava (LUG Manipal)       Beginning Python              January 29, 2010   39 / 44
File Object Methods


Let us assume we have
f = open(’file’,’r+’)




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   40 / 44
File Object Methods


Let us assume we have
f = open(’file’,’r+’)
      f.read([size]) reads size bytes from file and returns, if size is not
      specified or if size < 0 then size reads whole file.




Ankur Shrivastava (LUG Manipal)    Beginning Python            January 29, 2010   40 / 44
File Object Methods


Let us assume we have
f = open(’file’,’r+’)
      f.read([size]) reads size bytes from file and returns, if size is not
      specified or if size < 0 then size reads whole file.
      f.readline() reads one line from file (till n) and returns the line
      (including n)




Ankur Shrivastava (LUG Manipal)    Beginning Python            January 29, 2010   40 / 44
File Object Methods


Let us assume we have
f = open(’file’,’r+’)
      f.read([size]) reads size bytes from file and returns, if size is not
      specified or if size < 0 then size reads whole file.
      f.readline() reads one line from file (till n) and returns the line
      (including n)
      f.readlines() reads all lines in file and returns a list of all lines.




Ankur Shrivastava (LUG Manipal)     Beginning Python             January 29, 2010   40 / 44
File Object Methods


Let us assume we have
f = open(’file’,’r+’)
      f.read([size]) reads size bytes from file and returns, if size is not
      specified or if size < 0 then size reads whole file.
      f.readline() reads one line from file (till n) and returns the line
      (including n)
      f.readlines() reads all lines in file and returns a list of all lines.
      f.write(data) writes data to file.




Ankur Shrivastava (LUG Manipal)     Beginning Python             January 29, 2010   40 / 44
File Object Methods


Let us assume we have
f = open(’file’,’r+’)
      f.read([size]) reads size bytes from file and returns, if size is not
      specified or if size < 0 then size reads whole file.
      f.readline() reads one line from file (till n) and returns the line
      (including n)
      f.readlines() reads all lines in file and returns a list of all lines.
      f.write(data) writes data to file.
      f.close() closes the file.




Ankur Shrivastava (LUG Manipal)     Beginning Python             January 29, 2010   40 / 44
And we are done..




                                  Thank You!!!




Ankur Shrivastava (LUG Manipal)      Beginning Python   January 29, 2010   41 / 44
And we are done..




                                  Questions?




Ankur Shrivastava (LUG Manipal)     Beginning Python   January 29, 2010   42 / 44
Contact Information




          Ankur Shrivastava
          ankur@ankurs.com
         http://ankurs.com                     Linux User’s Group Manipal
                                                http://lugmanipal.org
                                            http://forums.lugmanipal.org




Ankur Shrivastava (LUG Manipal)   Beginning Python         January 29, 2010   43 / 44
Copying




 Creative Commons Attribution-Noncommercial-No Derivative Works 2.5
                            India License
    http://creativecommons.org/licenses/by-nc-nd/2.5/in/




Ankur Shrivastava (LUG Manipal)   Beginning Python   January 29, 2010   44 / 44

Weitere ähnliche Inhalte

Was ist angesagt?

Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPTShivam Gupta
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3Youhei Sakurai
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd roundYouhei Sakurai
 
GDG Helwan Introduction to python
GDG Helwan Introduction to pythonGDG Helwan Introduction to python
GDG Helwan Introduction to pythonMohamed Hegazy
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the StyleJuan-Manuel Gimeno
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019Samir Mohanty
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAMaulik Borsaniya
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1Kirti Verma
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-pythonAakashdata
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python ProgrammingMorteza Zakeri
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An IntroductionSwarit Wadhe
 
Getting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeGetting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeLihang Li
 

Was ist angesagt? (19)

Python Tutorial for Beginner
Python Tutorial for BeginnerPython Tutorial for Beginner
Python Tutorial for Beginner
 
Basics of python
Basics of pythonBasics of python
Basics of python
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
 
Introduction to python 3
Introduction to python 3Introduction to python 3
Introduction to python 3
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Introduction to python 3 2nd round
Introduction to python 3   2nd roundIntroduction to python 3   2nd round
Introduction to python 3 2nd round
 
GDG Helwan Introduction to python
GDG Helwan Introduction to pythonGDG Helwan Introduction to python
GDG Helwan Introduction to python
 
Python: the Project, the Language and the Style
Python: the Project, the Language and the StylePython: the Project, the Language and the Style
Python: the Project, the Language and the Style
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYAChapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
Chapter 1 - INTRODUCTION TO PYTHON -MAULIK BORSANIYA
 
Python tutorial
Python tutorialPython tutorial
Python tutorial
 
Python final presentation kirti ppt1
Python final presentation kirti ppt1Python final presentation kirti ppt1
Python final presentation kirti ppt1
 
Beginning Python Programming
Beginning Python ProgrammingBeginning Python Programming
Beginning Python Programming
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to-python
Introduction to-pythonIntroduction to-python
Introduction to-python
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
 
Python - An Introduction
Python - An IntroductionPython - An Introduction
Python - An Introduction
 
Getting started with Linux and Python by Caffe
Getting started with Linux and Python by CaffeGetting started with Linux and Python by Caffe
Getting started with Linux and Python by Caffe
 

Andere mochten auch

Doing magic with python metaclasses
Doing magic with python metaclassesDoing magic with python metaclasses
Doing magic with python metaclassesAgiliq Solutions
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programmingkanteshraj
 
CRYSTAL STRUCTURE AND X – RAYS DIFFRACTION
CRYSTAL STRUCTURE AND X – RAYS DIFFRACTIONCRYSTAL STRUCTURE AND X – RAYS DIFFRACTION
CRYSTAL STRUCTURE AND X – RAYS DIFFRACTIONA K Mishra
 
crystal structure and x ray diffraction
crystal structure and x ray diffractioncrystal structure and x ray diffraction
crystal structure and x ray diffractionMd Kaleem
 
Lo1.2 types of computer system error
Lo1.2 types of computer system errorLo1.2 types of computer system error
Lo1.2 types of computer system errorFrya Lora
 
Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...
Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...
Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...A K Mishra
 

Andere mochten auch (9)

Beginning Python
Beginning PythonBeginning Python
Beginning Python
 
Doing magic with python metaclasses
Doing magic with python metaclassesDoing magic with python metaclasses
Doing magic with python metaclasses
 
Talk Code
Talk CodeTalk Code
Talk Code
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programming
 
Python slide.1
Python slide.1Python slide.1
Python slide.1
 
CRYSTAL STRUCTURE AND X – RAYS DIFFRACTION
CRYSTAL STRUCTURE AND X – RAYS DIFFRACTIONCRYSTAL STRUCTURE AND X – RAYS DIFFRACTION
CRYSTAL STRUCTURE AND X – RAYS DIFFRACTION
 
crystal structure and x ray diffraction
crystal structure and x ray diffractioncrystal structure and x ray diffraction
crystal structure and x ray diffraction
 
Lo1.2 types of computer system error
Lo1.2 types of computer system errorLo1.2 types of computer system error
Lo1.2 types of computer system error
 
Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...
Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...
Dielectric and Magnetic Properties of materials,Polarizability,Dielectic loss...
 

Ähnlich wie Beginning Python

Distributed Computing
Distributed ComputingDistributed Computing
Distributed ComputingVarun Thacker
 
What makes Python So Awesome
What makes Python So AwesomeWhat makes Python So Awesome
What makes Python So AwesomeVikash Agrawal
 
SoC Python Discussion Group
SoC Python Discussion GroupSoC Python Discussion Group
SoC Python Discussion Groupkrishna_dubba
 
What is Launchpad? Version 1
What is Launchpad? Version 1What is Launchpad? Version 1
What is Launchpad? Version 1Pyae Sone
 
Real Python 🐍👨_💻-1.pdf
Real Python 🐍👨_💻-1.pdfReal Python 🐍👨_💻-1.pdf
Real Python 🐍👨_💻-1.pdfvishal laddha
 
introduction to ubuntu
introduction to ubuntuintroduction to ubuntu
introduction to ubuntuasifnawaz144wb
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonNikhil Kapoor
 
Hello, Python
Hello, PythonHello, Python
Hello, Pythonhardwyrd
 
python classes in thane
python classes in thanepython classes in thane
python classes in thanefaizrashid1995
 
Open Source Softwares
Open Source SoftwaresOpen Source Softwares
Open Source SoftwaresYara Khalifa
 
Introduction to jupyter pandas and matplotlib
Introduction to jupyter pandas and matplotlibIntroduction to jupyter pandas and matplotlib
Introduction to jupyter pandas and matplotlibtlsghalbi
 
"Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber...
"Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber..."Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber...
"Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber...eLiberatica
 

Ähnlich wie Beginning Python (20)

Distributed Computing
Distributed ComputingDistributed Computing
Distributed Computing
 
What makes Python So Awesome
What makes Python So AwesomeWhat makes Python So Awesome
What makes Python So Awesome
 
SoC Python Discussion Group
SoC Python Discussion GroupSoC Python Discussion Group
SoC Python Discussion Group
 
Python lecture 01
Python lecture 01Python lecture 01
Python lecture 01
 
What is Launchpad? Version 1
What is Launchpad? Version 1What is Launchpad? Version 1
What is Launchpad? Version 1
 
Python Course
Python CoursePython Course
Python Course
 
Online Lecture Design
Online Lecture DesignOnline Lecture Design
Online Lecture Design
 
Real Python 🐍👨_💻-1.pdf
Real Python 🐍👨_💻-1.pdfReal Python 🐍👨_💻-1.pdf
Real Python 🐍👨_💻-1.pdf
 
introduction to ubuntu
introduction to ubuntuintroduction to ubuntu
introduction to ubuntu
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Ubuntu Community
Ubuntu CommunityUbuntu Community
Ubuntu Community
 
Python
PythonPython
Python
 
Hello, Python
Hello, PythonHello, Python
Hello, Python
 
python classes in thane
python classes in thanepython classes in thane
python classes in thane
 
Open Source Softwares
Open Source SoftwaresOpen Source Softwares
Open Source Softwares
 
Introduction to jupyter pandas and matplotlib
Introduction to jupyter pandas and matplotlibIntroduction to jupyter pandas and matplotlib
Introduction to jupyter pandas and matplotlib
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
python-ppt.ppt
python-ppt.pptpython-ppt.ppt
python-ppt.ppt
 
Ubuntu Quick Guide
Ubuntu Quick GuideUbuntu Quick Guide
Ubuntu Quick Guide
 
"Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber...
"Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber..."Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber...
"Understanding Open Source and Ubuntu Part 1 of 2" by Kurt von Finck @ eLiber...
 

Kürzlich hochgeladen

Postal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utilisePostal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utiliseccsubcollector
 
CALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female serviceanilsa9823
 
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girlsPooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual serviceanilsa9823
 
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝soniya singh
 
办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭o8wvnojp
 
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...CIOWomenMagazine
 
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...ur8mqw8e
 
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot AndCall Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot AndPooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual serviceanilsa9823
 
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改atducpo
 
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...anilsa9823
 
call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..nishakur201
 
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service DhuleDhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhulesrsj9000
 
Cheap Rate ➥8448380779 ▻Call Girls In Mg Road Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Mg Road GurgaonCheap Rate ➥8448380779 ▻Call Girls In Mg Road Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Mg Road GurgaonDelhi Call girls
 
文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改
文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改
文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改atducpo
 
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdfBreath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdfJess Walker
 
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdfREFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdfssusere8ea60
 
The Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushThe Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushShivain97
 

Kürzlich hochgeladen (20)

Postal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utilisePostal Ballot procedure for employees to utilise
Postal Ballot procedure for employees to utilise
 
CALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Adil Nagar Lucknow best Female service
 
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
9892124323, Call Girls in mumbai, Vashi Call Girls , Kurla Call girls
 
CALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Rajajipuram Lucknow best sexual service
 
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
Call Girls in Kalyan Vihar Delhi 💯 Call Us 🔝8264348440🔝
 
办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭办理西悉尼大学毕业证成绩单、制作假文凭
办理西悉尼大学毕业证成绩单、制作假文凭
 
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
Understanding Relationship Anarchy: A Guide to Liberating Love | CIO Women Ma...
 
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
《塔夫斯大学毕业证成绩单购买》做Tufts文凭毕业证成绩单/伪造美国假文凭假毕业证书图片Q微信741003700《塔夫斯大学毕业证购买》《Tufts毕业文...
 
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot AndCall Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
Call Girls In Andheri East Call US Pooja📞 9892124323 Book Hot And
 
CALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Mahanagar Lucknow best sexual service
 
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
办理国外毕业证学位证《原版美国montana文凭》蒙大拿州立大学毕业证制作成绩单修改
 
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
Lucknow 💋 High Class Call Girls Lucknow 10k @ I'm VIP Independent Escorts Gir...
 
call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..call girls in candolim beach 9870370636] NORTH GOA ..
call girls in candolim beach 9870370636] NORTH GOA ..
 
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service DhuleDhule Call Girls #9907093804 Contact Number Escorts Service Dhule
Dhule Call Girls #9907093804 Contact Number Escorts Service Dhule
 
Cheap Rate ➥8448380779 ▻Call Girls In Mg Road Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Mg Road GurgaonCheap Rate ➥8448380779 ▻Call Girls In Mg Road Gurgaon
Cheap Rate ➥8448380779 ▻Call Girls In Mg Road Gurgaon
 
文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改
文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改
文凭办理《原版美国USU学位证书》犹他州立大学毕业证制作成绩单修改
 
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdfBreath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
Breath, Brain & Beyond_A Holistic Approach to Peak Performance.pdf
 
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Tingre Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdfREFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
REFLECTIONS Newsletter Jan-Jul 2024.pdf.pdf
 
The Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by MindbrushThe Selfspace Journal Preview by Mindbrush
The Selfspace Journal Preview by Mindbrush
 

Beginning Python

  • 1. Beginning Python Ankur Shrivastava Linux User’s Group Manipal January 29, 2010 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 1 / 44
  • 2. Who are we? Linux User’s Group Manipal Life, Universe and FOSS!! Believers of Knowledge Sharing Most technologically focused “group” in University LUG Manipal is a non profit “Group” alive only on voluntary work!! http://lugmanipal.org Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 2 / 44
  • 3. Points To Remember!!! If you have problem(s) don’t hesitate to ask Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 4. Points To Remember!!! If you have problem(s) don’t hesitate to ask Slides are based on Documentation so discussions are really important, slides are for later reference!! Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 5. Points To Remember!!! If you have problem(s) don’t hesitate to ask Slides are based on Documentation so discussions are really important, slides are for later reference!! Please dont consider sessions as Class (i hate classes) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 6. Points To Remember!!! If you have problem(s) don’t hesitate to ask Slides are based on Documentation so discussions are really important, slides are for later reference!! Please dont consider sessions as Class (i hate classes) Speaker is just like any person sitting next to you Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 7. Points To Remember!!! If you have problem(s) don’t hesitate to ask Slides are based on Documentation so discussions are really important, slides are for later reference!! Please dont consider sessions as Class (i hate classes) Speaker is just like any person sitting next to you Documentation is really important Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 8. Points To Remember!!! If you have problem(s) don’t hesitate to ask Slides are based on Documentation so discussions are really important, slides are for later reference!! Please dont consider sessions as Class (i hate classes) Speaker is just like any person sitting next to you Documentation is really important Google is your friend Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 9. Points To Remember!!! If you have problem(s) don’t hesitate to ask Slides are based on Documentation so discussions are really important, slides are for later reference!! Please dont consider sessions as Class (i hate classes) Speaker is just like any person sitting next to you Documentation is really important Google is your friend If you have questions after this workshop mail me or come to LUG Manipal’s forums http://forums.lugmanipal.org Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 3 / 44
  • 10. What is Python? Python is a general purpose, object oriented, high level, interpreted language Developed in early 90’s by Guido Van Rossum Its Simple, Portable, Open Source and Powerfull. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 4 / 44
  • 11. What we will learn? History, Features and basic detail Language Basics Control Flow Functions Modules File I/O Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 5 / 44
  • 12. What we require? Python interpreter Gnu/Linux − > Already installed in all distro’s Mac − > Already Installed, if not download http://python.org Windows − > Install Python from Python folder provided to you or download from http://python.org Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 6 / 44
  • 13. What we require? Python interpreter Gnu/Linux − > Already installed in all distro’s Mac − > Already Installed, if not download http://python.org Windows − > Install Python from Python folder provided to you or download from http://python.org Text Editor Gnu/Linux − > Vim/Emacs/Gedit/Kate/Geany any editor will do Mac − > Vim/TextMate or any other Unix like text editor Windows − > Notpad++, provided in Notepadpp folder or download http://notepad-plus.sourceforge.net Don’t use Notepad (MS) for editing code, always use Notepad++ Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 6 / 44
  • 14. What we require? Python interpreter Gnu/Linux − > Already installed in all distro’s Mac − > Already Installed, if not download http://python.org Windows − > Install Python from Python folder provided to you or download from http://python.org Text Editor Gnu/Linux − > Vim/Emacs/Gedit/Kate/Geany any editor will do Mac − > Vim/TextMate or any other Unix like text editor Windows − > Notpad++, provided in Notepadpp folder or download http://notepad-plus.sourceforge.net Don’t use Notepad (MS) for editing code, always use Notepad++ Documentation for Python present in Docs folder, web http://python.org/doc/ Set editor to expand tab to 4 spaces. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 6 / 44
  • 15. Where is it used? Used extensively in web => Django, TurboGears, Plone, etc communicating with Databases => MySQL, PostgreSQL, Oracle, etc Desktop GUI => GTK+, QT, Tk, etc Scientific Computing => Scipy, Scientific Python, etc Network Programming with frameworks/libraries like Twisted, etc Software Development => SCons, Buildbot, Roundup, etc Games and 3D graphics => pyGame, PyKyra, etc Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 7 / 44
  • 16. Difference from C/C++/Java No pointers ( similar to Java ) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 8 / 44
  • 17. Difference from C/C++/Java No pointers ( similar to Java ) No prior compilation to Bytecode(?), directly interpreted Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 8 / 44
  • 18. Difference from C/C++/Java No pointers ( similar to Java ) No prior compilation to Bytecode(?), directly interpreted Includes garbage collector(?) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 8 / 44
  • 19. Difference from C/C++/Java No pointers ( similar to Java ) No prior compilation to Bytecode(?), directly interpreted Includes garbage collector(?) Can be used in Procedure(?)/Object Oriented(?) approach/style Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 8 / 44
  • 20. Difference from C/C++/Java No pointers ( similar to Java ) No prior compilation to Bytecode(?), directly interpreted Includes garbage collector(?) Can be used in Procedure(?)/Object Oriented(?) approach/style English like syntax Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 8 / 44
  • 21. Difference from C/C++/Java No pointers ( similar to Java ) No prior compilation to Bytecode(?), directly interpreted Includes garbage collector(?) Can be used in Procedure(?)/Object Oriented(?) approach/style English like syntax Very good for scripting Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 8 / 44
  • 22. Versions of Python What do you mean by versions, Python is a language ? Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 9 / 44
  • 23. Versions of Python What do you mean by versions, Python is a language ? Ans) Python as a language keeps on evolving and new features are being added to the language, here by versions we refer to the python interpreter version, new features are added to python interpreter in every release. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 9 / 44
  • 24. Versions of Python What do you mean by versions, Python is a language ? Ans) Python as a language keeps on evolving and new features are being added to the language, here by versions we refer to the python interpreter version, new features are added to python interpreter in every release. important versions are Python 2.6/2.7 and 3.0/3.1 we will focus on Python 2.6/2.7 and not Python 3.0/3.1 Python 3.0/3.1 is the future of Python and has non compatible changes from Python 2.X, currently there is less support of Python 3.X and it will take a few years before it matches with that of Python 2.X Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 9 / 44
  • 25. Interactive session What is interactive session ? Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 10 / 44
  • 26. Interactive session What is interactive session ? Allows you to test your idea/logic/code and play arround with it, works as a shell, you can try out almost anything but whatever you type is note saved. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 10 / 44
  • 27. Interactive session What is interactive session ? Allows you to test your idea/logic/code and play arround with it, works as a shell, you can try out almost anything but whatever you type is note saved. How to start an interactive session ? Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 10 / 44
  • 28. Interactive session What is interactive session ? Allows you to test your idea/logic/code and play arround with it, works as a shell, you can try out almost anything but whatever you type is note saved. How to start an interactive session ? On Linux open terminal and type python On Windows, open Python in program files. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 10 / 44
  • 29. Interactive session What is interactive session ? Allows you to test your idea/logic/code and play arround with it, works as a shell, you can try out almost anything but whatever you type is note saved. How to start an interactive session ? On Linux open terminal and type python On Windows, open Python in program files. to exit an interactive session type quit() or press Ctrl + D on Unix like machine press Ctrl + Z on Windows machine Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 10 / 44
  • 30. Language Basics Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 11 / 44
  • 31. Indentation In Python indentation is very important. There are no end/begin delimiteres like { } Grouping of statements are done on basis of their indentation. Statements at same indentation are grouped together in a single block. Its recommended to use 4 spaces instead of tabs. # marks start of comment (single line) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 12 / 44
  • 32. Indentation In Python indentation is very important. There are no end/begin delimiteres like { } Grouping of statements are done on basis of their indentation. Statements at same indentation are grouped together in a single block. Its recommended to use 4 spaces instead of tabs. # marks start of comment (single line) sample code a = 10 if a/10 == 1: print ‘‘i think’’ # notice 4 spaces before this print print ‘‘the value was’’ # and this print print ‘‘10’’ # and this print Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 12 / 44
  • 33. Numbers Integer numbers => decimal -> 1, 44, -44, 2309 octal -> 01, 022, 077 hexadecimal -> 0x1, 0x23, 0x3f long -> 121212L, 2323232938238293829382938293283293825L Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 13 / 44
  • 34. Numbers Integer numbers => decimal -> 1, 44, -44, 2309 octal -> 01, 022, 077 hexadecimal -> 0x1, 0x23, 0x3f long -> 121212L, 2323232938238293829382938293283293825L Floating point => 0.0, 0.32, 2.23e2 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 13 / 44
  • 35. Numbers Integer numbers => decimal -> 1, 44, -44, 2309 octal -> 01, 022, 077 hexadecimal -> 0x1, 0x23, 0x3f long -> 121212L, 2323232938238293829382938293283293825L Floating point => 0.0, 0.32, 2.23e2 Complex numbers => 10+10j, 1+2j, 3-4j where j = −11/2 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 13 / 44
  • 36. String There is no character data type in python Strings can be quoted in single (’,“) or triple (”’,“““) quotes Special characters can be inserted by using the escape character Some commonly used escape sequesces => for a in string ’ for ’ in a string ” for “ in a string n for a newline r for cariage return t for tab Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 14 / 44
  • 37. String There is no character data type in python Strings can be quoted in single (’,“) or triple (”’,“““) quotes Special characters can be inserted by using the escape character Some commonly used escape sequesces => for a in string ’ for ’ in a string ” for “ in a string n for a newline r for cariage return t for tab Example >>>s = ’Line contaning ’ and in itself’ >>>print s Line contaning ’ and in itself Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 14 / 44
  • 38. Tuple Tuple is an immutable(?) ordered sequence of items(?) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 15 / 44
  • 39. Tuple Tuple is an immutable(?) ordered sequence of items(?) Tuples can be considered as constant array There can have nesting of tuples one inside other Elements in a Tuple does not have to be of same type Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) Elements can be accessed in way similar to an array Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 15 / 44
  • 40. Tuple Tuple is an immutable(?) ordered sequence of items(?) Tuples can be considered as constant array There can have nesting of tuples one inside other Elements in a Tuple does not have to be of same type Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) Elements can be accessed in way similar to an array Example >>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) >>> t[0] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 15 / 44
  • 41. Tuple Tuple is an immutable(?) ordered sequence of items(?) Tuples can be considered as constant array There can have nesting of tuples one inside other Elements in a Tuple does not have to be of same type Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) Elements can be accessed in way similar to an array Example >>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) >>> t[0] 1 >>> t[4] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 15 / 44
  • 42. Tuple Tuple is an immutable(?) ordered sequence of items(?) Tuples can be considered as constant array There can have nesting of tuples one inside other Elements in a Tuple does not have to be of same type Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) Elements can be accessed in way similar to an array Example >>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) >>> t[0] 1 >>> t[4] ’abc’ >>> t[6] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 15 / 44
  • 43. Tuple Tuple is an immutable(?) ordered sequence of items(?) Tuples can be considered as constant array There can have nesting of tuples one inside other Elements in a Tuple does not have to be of same type Assignment -> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) Elements can be accessed in way similar to an array Example >>> t = (1,2,3,4,‘‘abc’’,2.34,(10,11)) >>> t[0] 1 >>> t[4] ’abc’ >>> t[6] (10,11) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 15 / 44
  • 44. List List is a mutable ordered sequence of items Items in a list can be added or removed There can have nesting of lists one inside other Elements in a List does not have to be of same type Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] Data access and assignment similar to an array Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 16 / 44
  • 45. List List is a mutable ordered sequence of items Items in a list can be added or removed There can have nesting of lists one inside other Elements in a List does not have to be of same type Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] Data access and assignment similar to an array Example >>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] >>> l[0] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 16 / 44
  • 46. List List is a mutable ordered sequence of items Items in a list can be added or removed There can have nesting of lists one inside other Elements in a List does not have to be of same type Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] Data access and assignment similar to an array Example >>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] >>> l[0] 1 >>> l[6] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 16 / 44
  • 47. List List is a mutable ordered sequence of items Items in a list can be added or removed There can have nesting of lists one inside other Elements in a List does not have to be of same type Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] Data access and assignment similar to an array Example >>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] >>> l[0] 1 >>> l[6] [10,11] >>> l[6][0] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 16 / 44
  • 48. List List is a mutable ordered sequence of items Items in a list can be added or removed There can have nesting of lists one inside other Elements in a List does not have to be of same type Assignment -> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] Data access and assignment similar to an array Example >>> l = [1,2,3,4,‘‘abc’’,2.34,[10,11]] >>> l[0] 1 >>> l[6] [10,11] >>> l[6][0] 10 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 16 / 44
  • 49. Dictionaries Dictionaries are containers which store items in key/value pairs(?). Dictionaries are mutable but does not have any defined sequence. Key can be any integer or string and Value can be any item. As in Dictionaries values can be accessed by using the key. Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } Value can be accessed using the key and keys are unique. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 17 / 44
  • 50. Dictionaries Dictionaries are containers which store items in key/value pairs(?). Dictionaries are mutable but does not have any defined sequence. Key can be any integer or string and Value can be any item. As in Dictionaries values can be accessed by using the key. Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } Value can be accessed using the key and keys are unique. Example >>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } >>> d[’key’] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 17 / 44
  • 51. Dictionaries Dictionaries are containers which store items in key/value pairs(?). Dictionaries are mutable but does not have any defined sequence. Key can be any integer or string and Value can be any item. As in Dictionaries values can be accessed by using the key. Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } Value can be accessed using the key and keys are unique. Example >>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } >>> d[’key’] ’value’ >>> d[1] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 17 / 44
  • 52. Dictionaries Dictionaries are containers which store items in key/value pairs(?). Dictionaries are mutable but does not have any defined sequence. Key can be any integer or string and Value can be any item. As in Dictionaries values can be accessed by using the key. Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } Value can be accessed using the key and keys are unique. Example >>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } >>> d[’key’] ’value’ >>> d[1] ’value’ >>> d[’abc’] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 17 / 44
  • 53. Dictionaries Dictionaries are containers which store items in key/value pairs(?). Dictionaries are mutable but does not have any defined sequence. Key can be any integer or string and Value can be any item. As in Dictionaries values can be accessed by using the key. Assignment -> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } Value can be accessed using the key and keys are unique. Example >>> d = { ’key’:’value’, 1:’value’, ’abc’:[1,2,3,4] } >>> d[’key’] ’value’ >>> d[1] ’value’ >>> d[’abc’] [1, 2, 3, 4] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 17 / 44
  • 54. Index and Slices List, Tuple, String, etc can be sliced to get part of data from them. Index -> similar to array index refers to position of data. Slice -> use to reterive data within particular index. Example >>> s = “LUG MANIPAL” >>> s[0] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 18 / 44
  • 55. Index and Slices List, Tuple, String, etc can be sliced to get part of data from them. Index -> similar to array index refers to position of data. Slice -> use to reterive data within particular index. Example >>> s = “LUG MANIPAL” >>> s[0] ’L’ >>> s[2] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 18 / 44
  • 56. Index and Slices List, Tuple, String, etc can be sliced to get part of data from them. Index -> similar to array index refers to position of data. Slice -> use to reterive data within particular index. Example >>> s = “LUG MANIPAL” >>> s[0] ’L’ >>> s[2] ’G’ >>> s[0:3] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 18 / 44
  • 57. Index and Slices List, Tuple, String, etc can be sliced to get part of data from them. Index -> similar to array index refers to position of data. Slice -> use to reterive data within particular index. Example >>> s = “LUG MANIPAL” >>> s[0] ’L’ >>> s[2] ’G’ >>> s[0:3] ’LUG’ from 0 till 3, not including 3!! >>> s[:3] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 18 / 44
  • 58. Index and Slices List, Tuple, String, etc can be sliced to get part of data from them. Index -> similar to array index refers to position of data. Slice -> use to reterive data within particular index. Example >>> s = “LUG MANIPAL” >>> s[0] ’L’ >>> s[2] ’G’ >>> s[0:3] ’LUG’ from 0 till 3, not including 3!! >>> s[:3] ’LUG’ from start till 3, not including 3!! >>> s[4:] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 18 / 44
  • 59. Index and Slices List, Tuple, String, etc can be sliced to get part of data from them. Index -> similar to array index refers to position of data. Slice -> use to reterive data within particular index. Example >>> s = “LUG MANIPAL” >>> s[0] ’L’ >>> s[2] ’G’ >>> s[0:3] ’LUG’ from 0 till 3, not including 3!! >>> s[:3] ’LUG’ from start till 3, not including 3!! >>> s[4:] ’MANIPAL’ from 4 till end Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 18 / 44
  • 60. Index and Slices contd. Example >>> s = “LUG MANIPAL” >>> s[:11:2] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 19 / 44
  • 61. Index and Slices contd. Example >>> s = “LUG MANIPAL” >>> s[:11:2] ’LGMNPL’ from start till 11, every 2nd element >>> s[:11:3] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 19 / 44
  • 62. Index and Slices contd. Example >>> s = “LUG MANIPAL” >>> s[:11:2] ’LGMNPL’ from start till 11, every 2nd element >>> s[:11:3] ’L NA’ from start till 11, every 3rd element >>> s[-1] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 19 / 44
  • 63. Index and Slices contd. Example >>> s = “LUG MANIPAL” >>> s[:11:2] ’LGMNPL’ from start till 11, every 2nd element >>> s[:11:3] ’L NA’ from start till 11, every 3rd element >>> s[-1] ’L’ last element >>> s[-7:] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 19 / 44
  • 64. Index and Slices contd. Example >>> s = “LUG MANIPAL” >>> s[:11:2] ’LGMNPL’ from start till 11, every 2nd element >>> s[:11:3] ’L NA’ from start till 11, every 3rd element >>> s[-1] ’L’ last element >>> s[-7:] ’MANIPAL’ >>> s[:-8] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 19 / 44
  • 65. Index and Slices contd. Example >>> s = “LUG MANIPAL” >>> s[:11:2] ’LGMNPL’ from start till 11, every 2nd element >>> s[:11:3] ’L NA’ from start till 11, every 3rd element >>> s[-1] ’L’ last element >>> s[-7:] ’MANIPAL’ >>> s[:-8] ’LUG’ Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 19 / 44
  • 66. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 67. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 68. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 69. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). use functions list(old list) and dict(old dict) to obtain copy. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 70. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). use functions list(old list) and dict(old dict) to obtain copy. Note Be carefull with references they can lead to nasty things!!! Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 71. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). use functions list(old list) and dict(old dict) to obtain copy. Note Be carefull with references they can lead to nasty things!!! NOTE >>> l = [1, 2, 3, 4] >>> d = {’key’:l} >>> d[’key’] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 72. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). use functions list(old list) and dict(old dict) to obtain copy. Note Be carefull with references they can lead to nasty things!!! NOTE >>> l = [1, 2, 3, 4] >>> d = {’key’:l} >>> d[’key’] [1, 2, 3, 4] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 73. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). use functions list(old list) and dict(old dict) to obtain copy. Note Be carefull with references they can lead to nasty things!!! NOTE >>> l = [1, 2, 3, 4] >>> d = {’key’:l} >>> d[’key’] [1, 2, 3, 4] >>> l[0] = 0 >>> d[’key’] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 74. Variables There no prior type declaration required for variables. A variable can reffer to any Data Type ( like Tuple, List, Dictionary, Int, String, Complex, or any other object ). Variables are references(?) to allocated memory(?). References are always shared(?). use functions list(old list) and dict(old dict) to obtain copy. Note Be carefull with references they can lead to nasty things!!! NOTE >>> l = [1, 2, 3, 4] >>> d = {’key’:l} >>> d[’key’] [1, 2, 3, 4] >>> l[0] = 0 >>> d[’key’] [0, 2, 3, 4] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 20 / 44
  • 75. Helpful Functions help(<obj>) provides help/documentaion for the object using pydoc.help. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 21 / 44
  • 76. Helpful Functions help(<obj>) provides help/documentaion for the object using pydoc.help. dir(<obj>) lists the attributes/methods avaliable for that object. attributes/methods starting with / are internal attributes/methods and should not be used unless you know what you are doing. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 21 / 44
  • 77. Helpful Functions help(<obj>) provides help/documentaion for the object using pydoc.help. dir(<obj>) lists the attributes/methods avaliable for that object. attributes/methods starting with / are internal attributes/methods and should not be used unless you know what you are doing. dir() returns names in current scope Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 21 / 44
  • 78. Helpful Functions help(<obj>) provides help/documentaion for the object using pydoc.help. dir(<obj>) lists the attributes/methods avaliable for that object. attributes/methods starting with / are internal attributes/methods and should not be used unless you know what you are doing. dir() returns names in current scope Example >>> l = [1, 2, 3] >>> dir(l) [’ add ’, ’ class ’, ’ contains ’, ’ delattr ’, ’ delitem ’, ’ delslice ’, ’ doc ’, ’ eq ’, ’ format ’, ’ ge ’, ’ getattribute ’, ’ getitem ’, ’ getslice ’, ’ gt ’, ’ hash ’, ’ iadd ’, ’ imul ’, ’ init ’, ’ iter ’, ’ le ’, ’ len ’, ’ lt ’, ’ mul ’, ’ ne ’, ’ new ’, ’ reduce ’, ’ reduce ex ’, ’ repr ’, ’ reversed ’, ’ rmul ’, ’ setattr ’, ’ setitem ’, ’ setslice ’, ’ sizeof ’, ’ str ’, ’ subclasshook ’, ’append’, ’count’, ’extend’, ’index’, ’insert’, ’pop’, ’remove’, ’reverse’, ’sort’] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 21 / 44
  • 79. List Operations l.append(< val >) − > adds < val > at the end of list. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 80. List Operations l.append(< val >) − > adds < val > at the end of list. l.extend(< List >) − > adds all element in < list > to ’l’. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 81. List Operations l.append(< val >) − > adds < val > at the end of list. l.extend(< List >) − > adds all element in < list > to ’l’. l.insert(< pos >, < val >) − > Inserts < val > at position < pos >. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 82. List Operations l.append(< val >) − > adds < val > at the end of list. l.extend(< List >) − > adds all element in < list > to ’l’. l.insert(< pos >, < val >) − > Inserts < val > at position < pos >. l.remove(< val >) − > removes first element matching < val >, raises ValueError if no such value exists. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 83. List Operations l.append(< val >) − > adds < val > at the end of list. l.extend(< List >) − > adds all element in < list > to ’l’. l.insert(< pos >, < val >) − > Inserts < val > at position < pos >. l.remove(< val >) − > removes first element matching < val >, raises ValueError if no such value exists. l.index(< val >) − > returns index of first occurence of < val >, raises ValueError if no such value exists. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 84. List Operations l.append(< val >) − > adds < val > at the end of list. l.extend(< List >) − > adds all element in < list > to ’l’. l.insert(< pos >, < val >) − > Inserts < val > at position < pos >. l.remove(< val >) − > removes first element matching < val >, raises ValueError if no such value exists. l.index(< val >) − > returns index of first occurence of < val >, raises ValueError if no such value exists. l.pop(< index >) − > removes element at < index >, if no index is specified last element is returned. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 85. List Operations l.append(< val >) − > adds < val > at the end of list. l.extend(< List >) − > adds all element in < list > to ’l’. l.insert(< pos >, < val >) − > Inserts < val > at position < pos >. l.remove(< val >) − > removes first element matching < val >, raises ValueError if no such value exists. l.index(< val >) − > returns index of first occurence of < val >, raises ValueError if no such value exists. l.pop(< index >) − > removes element at < index >, if no index is specified last element is returned. Example >>> l = [1, 2, 3, 4, 5, 6, 7] >>> l.append(8) >>> l [1, 2, 3, 4, 5, 6, 7, 8] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 22 / 44
  • 86. Dictionary Operations d.has key(< val >) − > returns true if key by < val > exists, else returns false. d.items() − > returns list of 2 value tuple, with first element key and second value. d.keys() − > returns list of all keys in dictionary. d.values() − > returns list of all values in dictionary. d.iteritems() − > returns an iteratable object of dictionay, giving a tuple of (key, value) on every iteration. Example >>> d = { ’a’:1 , ’abc’:878 } >>> for i,j in d.iteritems(): ... print i, j ... a1 abc 878 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 23 / 44
  • 87. Control Flow Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 24 / 44
  • 88. Input and Output Input to take input (string) from user we use function raw input(). function input() evaluates the input as python expression. we use functions int(), long(), float(), and str() to convert the input to desired type. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 25 / 44
  • 89. Input and Output Input to take input (string) from user we use function raw input(). function input() evaluates the input as python expression. we use functions int(), long(), float(), and str() to convert the input to desired type. Output print is a keyword for giving output to a console or a file. print can take multiple arguments saperated by comma (, ) if you dont want a newline add comma (, ) at the end. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 25 / 44
  • 90. Input and Output Input to take input (string) from user we use function raw input(). function input() evaluates the input as python expression. we use functions int(), long(), float(), and str() to convert the input to desired type. Output print is a keyword for giving output to a console or a file. print can take multiple arguments saperated by comma (, ) if you dont want a newline add comma (, ) at the end. Example >>> val = raw input(“Enter a number: ”) Enter a number: 123 >>> val = int(val) + 1 >>> print “Number is”, val Number is 124 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 25 / 44
  • 91. if if is a conditional keyword, for a simple “if then else” clause in english. Header lines(?) are always concluded with a “:” followed by indented block of statements. optionally if can be followed by an “else if” which is known as “elif” in Python. expressions can be logically connected by using “or”/“and”. Tip Just remember we need to put “:” where every we used “{}” in other languages, and statements following ’if’ should always be indented. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 26 / 44
  • 92. if if is a conditional keyword, for a simple “if then else” clause in english. Header lines(?) are always concluded with a “:” followed by indented block of statements. optionally if can be followed by an “else if” which is known as “elif” in Python. expressions can be logically connected by using “or”/“and”. Tip Just remember we need to put “:” where every we used “{}” in other languages, and statements following ’if’ should always be indented. Example if a == 1: print “value of a is 1” elif a == 2: print “value of a is 2” else: print “value of a is not 1 or 2” Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 26 / 44
  • 93. while while is used for repeated execution of a block of code till a condiction holds true. in Python while has an optional else clause which executes when the condiction evaluates to false. following values are considered flase -> None, False, any numeric type equal to zero, any empty sequence (), [],‘’ or any empty mapping {}. Example limit = 5 val = 0 while val < limit : print val, val +=1 Output : Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 27 / 44
  • 94. while while is used for repeated execution of a block of code till a condiction holds true. in Python while has an optional else clause which executes when the condiction evaluates to false. following values are considered flase -> None, False, any numeric type equal to zero, any empty sequence (), [],‘’ or any empty mapping {}. Example limit = 5 val = 0 while val < limit : print val, val +=1 Output : 01234 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 27 / 44
  • 95. for for is a sequence iterator(?). Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 28 / 44
  • 96. for for is a sequence iterator(?). for works on strings, lists, tuples, etc. use range/xrange to generate lists range(0,4) − > [0, 1, 2, 3] range(0,6,2) − > [0, 2, 4] xrange works as a iterator and does not generate a list (?) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 28 / 44
  • 97. for for is a sequence iterator(?). for works on strings, lists, tuples, etc. use range/xrange to generate lists range(0,4) − > [0, 1, 2, 3] range(0,6,2) − > [0, 2, 4] xrange works as a iterator and does not generate a list (?) Example for item in range(1, 5) : print item, Output: Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 28 / 44
  • 98. for for is a sequence iterator(?). for works on strings, lists, tuples, etc. use range/xrange to generate lists range(0,4) − > [0, 1, 2, 3] range(0,6,2) − > [0, 2, 4] xrange works as a iterator and does not generate a list (?) Example for item in range(1, 5) : print item, Output: 1234 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 28 / 44
  • 99. break / continue break used for loop termination if nested, terminates the inner loop continue terminates the current iteration and starts the next it does not terminate the loop Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 29 / 44
  • 100. break / continue break used for loop termination if nested, terminates the inner loop continue terminates the current iteration and starts the next it does not terminate the loop Example for i in range(1,10) : if i == 6 : break if i == 3 : continue print i, Output: Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 29 / 44
  • 101. break / continue break used for loop termination if nested, terminates the inner loop continue terminates the current iteration and starts the next it does not terminate the loop Example for i in range(1,10) : if i == 6 : break if i == 3 : continue print i, Output: 1245 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 29 / 44
  • 102. List Comprehensions Normal use of “for” loop is to iterate and build a new list List comprehensions simplifies the above task Syntax − > [ <expression> for <target> in <iterable> <condiction> ] there can be multiples statements. Example >>> [ x*2 for x in range(1,5) ] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 30 / 44
  • 103. List Comprehensions Normal use of “for” loop is to iterate and build a new list List comprehensions simplifies the above task Syntax − > [ <expression> for <target> in <iterable> <condiction> ] there can be multiples statements. Example >>> [ x*2 for x in range(1,5) ] [2, 4, 6, 8] >>> [ x for x in range(0,10) if x%2 == 0 and x > 2] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 30 / 44
  • 104. List Comprehensions Normal use of “for” loop is to iterate and build a new list List comprehensions simplifies the above task Syntax − > [ <expression> for <target> in <iterable> <condiction> ] there can be multiples statements. Example >>> [ x*2 for x in range(1,5) ] [2, 4, 6, 8] >>> [ x for x in range(0,10) if x%2 == 0 and x > 2] [4, 6, 8] >>> [ x+y for x in range(1,4) for y in range(1,4)] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 30 / 44
  • 105. List Comprehensions Normal use of “for” loop is to iterate and build a new list List comprehensions simplifies the above task Syntax − > [ <expression> for <target> in <iterable> <condiction> ] there can be multiples statements. Example >>> [ x*2 for x in range(1,5) ] [2, 4, 6, 8] >>> [ x for x in range(0,10) if x%2 == 0 and x > 2] [4, 6, 8] >>> [ x+y for x in range(1,4) for y in range(1,4)] [2, 3, 4, 3, 4, 5, 4, 5, 6] Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 30 / 44
  • 106. Functions Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 31 / 44
  • 107. What are Functions? A function is a group of statements that executes on request. In Python functions are also objects. function return type is not required. if function does not return any value, default value of None is returned. a function can take another function name as argument and return a function name (as in functional programming languages). a function is defined using the keyoword def followed by function name and parameters Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 32 / 44
  • 108. What are Functions? A function is a group of statements that executes on request. In Python functions are also objects. function return type is not required. if function does not return any value, default value of None is returned. a function can take another function name as argument and return a function name (as in functional programming languages). a function is defined using the keyoword def followed by function name and parameters Example >>> def abc(arg): ··· print arg ··· >>> abc(“Hello”) Hello Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 32 / 44
  • 109. Parameters Default Value is the value assigned to function argument in function defination. Types of Parameters Mandatory Parameters with no default values. Optional Parameters with default values. At function call values for all mandatory parameters are required. There is no function overloading in python. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 33 / 44
  • 110. Parameters Default Value is the value assigned to function argument in function defination. Types of Parameters Mandatory Parameters with no default values. Optional Parameters with default values. At function call values for all mandatory parameters are required. There is no function overloading in python. Example def abc (arg1,arg2=10): # arg2 has default value of 10 print arg1, arg2 abc(1) abc(2,3) Output : Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 33 / 44
  • 111. Parameters Default Value is the value assigned to function argument in function defination. Types of Parameters Mandatory Parameters with no default values. Optional Parameters with default values. At function call values for all mandatory parameters are required. There is no function overloading in python. Example def abc (arg1,arg2=10): # arg2 has default value of 10 print arg1, arg2 abc(1) abc(2,3) Output : 1 10 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 33 / 44
  • 112. Parameters Default Value is the value assigned to function argument in function defination. Types of Parameters Mandatory Parameters with no default values. Optional Parameters with default values. At function call values for all mandatory parameters are required. There is no function overloading in python. Example def abc (arg1,arg2=10): # arg2 has default value of 10 print arg1, arg2 abc(1) abc(2,3) Output : 1 10 23 Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 33 / 44
  • 113. Modules Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 34 / 44
  • 114. What are Modules? Modules group code and data for reuse. Modules or a part of modules can be used in other code using import or from statements. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 35 / 44
  • 115. What are Modules? Modules group code and data for reuse. Modules or a part of modules can be used in other code using import or from statements. import Syntax − > import module [ as othername ] import imports whole of specified module in the namespace module/othername. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 35 / 44
  • 116. What are Modules? Modules group code and data for reuse. Modules or a part of modules can be used in other code using import or from statements. import Syntax − > import module [ as othername ] import imports whole of specified module in the namespace module/othername. from Syntax − > from module import something [ as somethingelse ] using from import something inside the current namespace as something/somethingelse. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 35 / 44
  • 117. How to make Module? Any python file (.py ) can work as a module. If the file is written to execute when invoked, it is executed when imported. To allow a file to executed when invoked and avoid when imported we compare variable “ name ” Python file executing as main code has variable “ name ” set to “ main ” Python file executing as module has variable “ name ” set to the module name Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 36 / 44
  • 118. Lets create a file example.py, which we will use to describe modules example.py # some functions def div(a,b): print a/b # code that will execute in every case print “Hi” # code that will execute only if file invoked if name == “ main ”: mul(2,2) print “not as module” else: print “as module” Try import and from on example.py and also try executing the file. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 37 / 44
  • 119. File I/O Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 38 / 44
  • 120. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 121. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 122. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 123. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. ’a’ opens a file in write only mode, if file exists new data in added at the end, else a new file is created. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 124. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. ’a’ opens a file in write only mode, if file exists new data in added at the end, else a new file is created. ’r+’ file is opened in read and write mode, but file must exist. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 125. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. ’a’ opens a file in write only mode, if file exists new data in added at the end, else a new file is created. ’r+’ file is opened in read and write mode, but file must exist. ’w+’ file is opened in read and write mode, file is truncated if exists, else a new file is created. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 126. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. ’a’ opens a file in write only mode, if file exists new data in added at the end, else a new file is created. ’r+’ file is opened in read and write mode, but file must exist. ’w+’ file is opened in read and write mode, file is truncated if exists, else a new file is created. ’a+’ file is opened in read and write mode, if file exists new data in added at the end, else a new file is created. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 127. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. ’a’ opens a file in write only mode, if file exists new data in added at the end, else a new file is created. ’r+’ file is opened in read and write mode, but file must exist. ’w+’ file is opened in read and write mode, file is truncated if exists, else a new file is created. ’a+’ file is opened in read and write mode, if file exists new data in added at the end, else a new file is created. append ’b’ to the mode to open file in binary mode. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 128. File file is a built-in type in Python. Allows access to files in an Operating System independent manner. Different modes to access a file are ’r’ opens an already existing file in read only mode. ’w’ opens a file in write only mode, if file exists it is truncated else a new file in created. ’a’ opens a file in write only mode, if file exists new data in added at the end, else a new file is created. ’r+’ file is opened in read and write mode, but file must exist. ’w+’ file is opened in read and write mode, file is truncated if exists, else a new file is created. ’a+’ file is opened in read and write mode, if file exists new data in added at the end, else a new file is created. append ’b’ to the mode to open file in binary mode. modes are passed to function open which is used to open a file Synatx − > <file obj> = open(<file name>,<mode>,bufsize=-1) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 39 / 44
  • 129. File Object Methods Let us assume we have f = open(’file’,’r+’) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 40 / 44
  • 130. File Object Methods Let us assume we have f = open(’file’,’r+’) f.read([size]) reads size bytes from file and returns, if size is not specified or if size < 0 then size reads whole file. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 40 / 44
  • 131. File Object Methods Let us assume we have f = open(’file’,’r+’) f.read([size]) reads size bytes from file and returns, if size is not specified or if size < 0 then size reads whole file. f.readline() reads one line from file (till n) and returns the line (including n) Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 40 / 44
  • 132. File Object Methods Let us assume we have f = open(’file’,’r+’) f.read([size]) reads size bytes from file and returns, if size is not specified or if size < 0 then size reads whole file. f.readline() reads one line from file (till n) and returns the line (including n) f.readlines() reads all lines in file and returns a list of all lines. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 40 / 44
  • 133. File Object Methods Let us assume we have f = open(’file’,’r+’) f.read([size]) reads size bytes from file and returns, if size is not specified or if size < 0 then size reads whole file. f.readline() reads one line from file (till n) and returns the line (including n) f.readlines() reads all lines in file and returns a list of all lines. f.write(data) writes data to file. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 40 / 44
  • 134. File Object Methods Let us assume we have f = open(’file’,’r+’) f.read([size]) reads size bytes from file and returns, if size is not specified or if size < 0 then size reads whole file. f.readline() reads one line from file (till n) and returns the line (including n) f.readlines() reads all lines in file and returns a list of all lines. f.write(data) writes data to file. f.close() closes the file. Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 40 / 44
  • 135. And we are done.. Thank You!!! Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 41 / 44
  • 136. And we are done.. Questions? Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 42 / 44
  • 137. Contact Information Ankur Shrivastava ankur@ankurs.com http://ankurs.com Linux User’s Group Manipal http://lugmanipal.org http://forums.lugmanipal.org Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 43 / 44
  • 138. Copying Creative Commons Attribution-Noncommercial-No Derivative Works 2.5 India License http://creativecommons.org/licenses/by-nc-nd/2.5/in/ Ankur Shrivastava (LUG Manipal) Beginning Python January 29, 2010 44 / 44