Python Lunch & Learn

Session 1

Atul Saurav

Agenda:

  1. About python
  2. Getting Started
  3. Python Basics types
  4. Lists, Tuples, Sets
  5. Strings
  6. Dictionaries
  7. Control Flow
  8. Functions

Introduction

  • High Level Language available on multiple platform and pre installed in all POSIX based systems
  • Easy to learn and use - “Batteries Included”
  • Not a compiled language - not the fastest language around
  • It is not a 5GL language like VB etc
    • So you have to write code and drag and drop doesn't write code for you in backend
    • You are not limited by the limitation of code generation frontend
    • With great power comes great responsibility - Uncle Ben, Marvel Comics
  • Source code gets converted to bytecode at runtime and is executed by the interpreter
  • Python behind the scenes is C, thus there are ways to optimize and run python programs at speed comparable to C!
  • Python is FREE!

Getting Started - Installation

There are multiple options:

On windows:

  • Standard Python can be installed from Python.org
  • Enhanced Python can be installed from third parties
    • Continuum.io - Anaconda (Recommended)
    • Enthought Canopy

On Linux:

  • Standard python is preinstalled and can be invoked by typing python on shell prompt
  • Anaconda python is installed on /opt/anaconda2/bin and can be executed from there
  • Prepending /opt/anaconda2/bin to PATH environment variable will invoke anaconda python

Getting Started - Development Options

  • Python interactive Read Evaluate Print Loop (REPL)
  • No specific text editor needed - Any plain text editor works
  • IDLE, iPython, Jypyter, PyCharm, Eclipse, Spyder

Lexical Conventions and Syntax

  • Python is case sensitive
  • Leading spaces on a line matter
  • Blocks are identified by indents unlike languages like C/Java etc..
  • A block can either be space indented or tab, not both
  • Single line comments are start with #
  • Multi line comments are enclosed within ''' or """

Python Types:

Type of any object can be determined by type function

Python has several built-in types:

  • Simple
    • Boolean
    • String
    • Numeric - Int, Float
  • Compound
    • List
    • Tuple
    • Set
    • Dictionaries

Boolean Type:

  • Denoted by keyword bool and has 2 possible keywords True and False as values
  • 0, None, empty string all evaluate to False
  • Everything else evaluates to True
In [1]:
bool(True), bool(False)
Out[1]:
(True, False)
In [2]:
bool(''), bool('Python')
Out[2]:
(False, True)
In [3]:
bool(None), bool(30), bool(0)
Out[3]:
(False, True, False)
In [4]:
if 'Python':
    print "hello"
else:
    print "bye"
hello

String Type:

  • Denoted by keyword str and is similar to string types from most languages
  • any sequence of characters enclosed within single, double or triple quotes is a string
In [5]:
>>> 'abc', type('abc'), '''abc'''
Out[5]:
('abc', str, 'abc')
In [6]:
>>> "abc", type("abc"), """abc"""
Out[6]:
('abc', str, 'abc')
In [7]:
a = """ Hello
Ok
Done
"""
In [8]:
print (a)
 Hello
Ok
Done

In [9]:
a = 1
b = 2
In [10]:
a + b
Out[10]:
3
In [11]:
a / b
Out[11]:
0
In [12]:
from __future__ import division
In [13]:
a/b
Out[13]:
0.5
In [14]:
1/3 == 0.333333
Out[14]:
False
In [15]:
import decimal
In [16]:
a = decimal.Decimal(3)
In [17]:
a
Out[17]:
Decimal('3')
In [18]:
a = list()
In [19]:
b = [1,2,'atul',[4,5,6]]
In [20]:
b
Out[20]:
[1, 2, 'atul', [4, 5, 6]]
In [21]:
type(b)
Out[21]:
list
In [22]:
b[2]
Out[22]:
'atul'
In [23]:
b[2][2]
Out[23]:
'u'
In [24]:
x = [['sub1', 1], ['sub',2]]
In [25]:
x
Out[25]:
[['sub1', 1], ['sub', 2]]
In [26]:
[type(y[0]) for y in x]
Out[26]:
[str, str]
In [27]:
d = 5
In [28]:
e = 5
In [29]:
k = d
In [30]:
k = 6
In [31]:
k
Out[31]:
6
In [32]:
d
Out[32]:
5
In [33]:
l = k
In [34]:
l
Out[34]:
6
In [35]:
k = 7
l
Out[35]:
6
In [36]:
dir(x)
Out[36]:
['__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']
In [37]:
help(x)
Help on list object:

class list(object)
 |  list() -> new empty list
 |  list(iterable) -> new list initialized from iterable's items
 |  
 |  Methods defined here:
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __contains__(...)
 |      x.__contains__(y) <==> y in x
 |  
 |  __delitem__(...)
 |      x.__delitem__(y) <==> del x[y]
 |  
 |  __delslice__(...)
 |      x.__delslice__(i, j) <==> del x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __eq__(...)
 |      x.__eq__(y) <==> x==y
 |  
 |  __ge__(...)
 |      x.__ge__(y) <==> x>=y
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getitem__(...)
 |      x.__getitem__(y) <==> x[y]
 |  
 |  __getslice__(...)
 |      x.__getslice__(i, j) <==> x[i:j]
 |      
 |      Use of negative indices is not supported.
 |  
 |  __gt__(...)
 |      x.__gt__(y) <==> x>y
 |  
 |  __iadd__(...)
 |      x.__iadd__(y) <==> x+=y
 |  
 |  __imul__(...)
 |      x.__imul__(y) <==> x*=y
 |  
 |  __init__(...)
 |      x.__init__(...) initializes x; see help(type(x)) for signature
 |  
 |  __iter__(...)
 |      x.__iter__() <==> iter(x)
 |  
 |  __le__(...)
 |      x.__le__(y) <==> x<=y
 |  
 |  __len__(...)
 |      x.__len__() <==> len(x)
 |  
 |  __lt__(...)
 |      x.__lt__(y) <==> x<y
 |  
 |  __mul__(...)
 |      x.__mul__(n) <==> x*n
 |  
 |  __ne__(...)
 |      x.__ne__(y) <==> x!=y
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __reversed__(...)
 |      L.__reversed__() -- return a reverse iterator over the list
 |  
 |  __rmul__(...)
 |      x.__rmul__(n) <==> n*x
 |  
 |  __setitem__(...)
 |      x.__setitem__(i, y) <==> x[i]=y
 |  
 |  __setslice__(...)
 |      x.__setslice__(i, j, y) <==> x[i:j]=y
 |      
 |      Use  of negative indices is not supported.
 |  
 |  __sizeof__(...)
 |      L.__sizeof__() -- size of L in memory, in bytes
 |  
 |  append(...)
 |      L.append(object) -- append object to end
 |  
 |  count(...)
 |      L.count(value) -> integer -- return number of occurrences of value
 |  
 |  extend(...)
 |      L.extend(iterable) -- extend list by appending elements from the iterable
 |  
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value.
 |      Raises ValueError if the value is not present.
 |  
 |  insert(...)
 |      L.insert(index, object) -- insert object before index
 |  
 |  pop(...)
 |      L.pop([index]) -> item -- remove and return item at index (default last).
 |      Raises IndexError if list is empty or index is out of range.
 |  
 |  remove(...)
 |      L.remove(value) -- remove first occurrence of value.
 |      Raises ValueError if the value is not present.
 |  
 |  reverse(...)
 |      L.reverse() -- reverse *IN PLACE*
 |  
 |  sort(...)
 |      L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
 |      cmp(x, y) -> -1, 0, 1
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __hash__ = None
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T