Environment setup: Python and Jupyter

Variables: Numbers, String, Tuple, List, Dictionary

Basic operators: Arithmetic and Boolean operators

Control flow: if/else, for, while, pass, break, continue

List: access, update, del, len(), + , in, for, slicing, append(), insert(), pop(), remove()

Dictionary: access, update, del, in

Function: function definition, pass by reference, keyword argument, default argument, lambda

map reduce filter

Module: from, import, reload(), package has init.py, init and str

I/O: raw_input(), input(), open(), close(), write(), read(), rename(), remove(), mkdir(), chdir(), rmdir()

Pass by value, Pass by reference

Date/time: local time and time zone, pytz module

Variables: Numbers, String, Tuple, List, Dictionary


In [3]:
x=1
print x


1

In [4]:
type(x)


Out[4]:
int

In [5]:
x="text"

In [6]:
x


Out[6]:
'text'

In [7]:
type(x)


Out[7]:
str

In [7]:
x.conjugate()


Out[7]:
1

In [9]:
type(1+2j)


Out[9]:
complex

In [10]:
z=1+2j
print z


(1+2j)

In [11]:
(1,2)


Out[11]:
(1, 2)

In [8]:
t=(1,2,"text")

In [9]:
t


Out[9]:
(1, 2, 'text')

In [10]:
type(t)


Out[10]:
tuple

In [11]:
def foo():
    return (1,2)
x,y=foo()

In [12]:
print x
print y


1
2

In [27]:
def swap(x,y):
    return (y,x)

x=1;y=2
print "{0:d} {1:d}".format(x,y)
x,y=swap(x,y)
print "{:f} {:f}".format(x,y)


1 2
2.000000 1.000000

In [29]:
dir(1)


Out[29]:
['__abs__',
 '__add__',
 '__and__',
 '__class__',
 '__cmp__',
 '__coerce__',
 '__delattr__',
 '__div__',
 '__divmod__',
 '__doc__',
 '__float__',
 '__floordiv__',
 '__format__',
 '__getattribute__',
 '__getnewargs__',
 '__hash__',
 '__hex__',
 '__index__',
 '__init__',
 '__int__',
 '__invert__',
 '__long__',
 '__lshift__',
 '__mod__',
 '__mul__',
 '__neg__',
 '__new__',
 '__nonzero__',
 '__oct__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdiv__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'bit_length',
 'conjugate',
 'denominator',
 'imag',
 'numerator',
 'real']

In [13]:
x="text"

In [14]:
dir(x)


Out[14]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__getslice__',
 '__gt__',
 '__hash__',
 '__init__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '_formatter_field_name_split',
 '_formatter_parser',
 'capitalize',
 'center',
 'count',
 'decode',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'index',
 'isalnum',
 'isalpha',
 'isdigit',
 'islower',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [15]:
x.upper()


Out[15]:
'TEXT'

In [16]:
x=[]

In [17]:
type(x)


Out[17]:
list

In [18]:
x.append("text")

In [19]:
x


Out[19]:
['text']

In [23]:
x.append(1)

In [24]:
x


Out[24]:
['text', 1]

In [25]:
x.pop()


Out[25]:
1

In [26]:
x


Out[26]:
['text']

In [27]:
x


Out[27]:
['text']

In [31]:
x.append([1,2,3])

In [32]:
x


Out[32]:
['text', 2, [1, 2, 3]]

In [33]:
print x[0]
print x[-2]


text
2

In [34]:
x.pop(-2)


Out[34]:
2

In [35]:
x


Out[35]:
['text', [1, 2, 3]]

In [56]:
%%timeit -n10
x=[]
for i in range(100000):
    x.append(2*i+1)


10 loops, best of 3: 41.9 ms per loop

In [55]:
%%timeit -n10
x=[]
for i in xrange(100000):
    x.append(2*i+1)


10 loops, best of 3: 39.1 ms per loop

In [47]:
range(10)


Out[47]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [59]:
y=[2*i+1 for i in xrange(10)]
print y


[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

In [36]:
type({})


Out[36]:
dict

In [37]:
x={"key":"value","foo":"bar"}
print x


{'foo': 'bar', 'key': 'value'}

In [40]:
x[key]


Out[40]:
'value'

In [39]:
key="key"
if key in x:
    print x[key]


value

In [68]:
y={ i:i*i for i in xrange(10)}

In [69]:
y


Out[69]:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

In [75]:
z=[v for (k,v) in y.iteritems()]
print z


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

if/else, for, while, pass, break, continue


In [80]:
p=[]
for i in xrange(2,100):
    isprime=1
    for j in p:
        if(i%j==0):
            isprime=0
            break
    if isprime:
        p.append(i)
        
print p


[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

In [82]:
for i in xrange(10):
    pass

In [4]:
i=10
while i>0:
    i=i-1
    print i


9
8
7
6
5
4
3
2
1
0

In [9]:
x=['text',"str",''' Hello World\\n ''']
print x


['text', 'str', ' Hello World\\n ']

List: access, update, del, len(), + , in, for, slicing, append(), insert(), pop(), remove()


In [44]:
x=['a','b','c']
#access
print x[0]
#update
x[0]='d'
print x
print "size of x%d is" %len(x)


a
['d', 'b', 'c']
size of x3 is

In [16]:
y=['x','y','z']
z=x+y
gamma=y+x
print z
print gamma


['d', 'b', 'c', 'x', 'y', 'z']
['x', 'y', 'z', 'd', 'b', 'c']

In [18]:
print 'a' in x


False

In [21]:
print y
y.remove('y')# remove by vavlue
print y


['x', 'y', 'z']
['x', 'z']

In [22]:
print y
y.pop(0)# remove by index
print y


['x', 'z']
['z']

In [23]:
y.insert(0,'x')
y.insert(1,'y')
print y


['x', 'y', 'z']

In [45]:
x=[i*i for i in xrange(10)]
print x


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [32]:
x[:3]


Out[32]:
[0, 1, 4]

In [33]:
x[-3:]


Out[33]:
[49, 64, 81]

In [36]:
x[-1:]


Out[36]:
[81]

In [38]:
x[3:-3]


Out[38]:
[9, 16, 25, 36]

In [40]:
x[1:6]


Out[40]:
[1, 4, 9, 16, 25]

In [54]:
x[::2]


Out[54]:
[0, 4, 16, 36, 64]

In [61]:
print x
x.reverse()
print x


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[81, 64, 49, 36, 25, 16, 9, 4, 1, 0]

In [62]:
print x
print x[::-1]
print x


[81, 64, 49, 36, 25, 16, 9, 4, 1, 0]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[81, 64, 49, 36, 25, 16, 9, 4, 1, 0]

Dictionary: access, update, del, in


In [63]:
x={}

In [65]:
x={'key':'value'}

In [67]:
x['foo']='bar'

In [68]:
x


Out[68]:
{'foo': 'bar', 'key': 'value'}

In [69]:
x['foo']='Hello'

In [70]:
x


Out[70]:
{'foo': 'Hello', 'key': 'value'}

In [71]:
x['m']=123

In [77]:
x['foo','key']


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-77-ce049a4a288b> in <module>()
----> 1 x['foo','key']

KeyError: ('foo', 'key')

In [76]:
keys=['foo','key']
[x[k] for k in keys]


Out[76]:
['Hello', 'value']

In [78]:
print x
del x
print x


{'foo': 'Hello', 'm': 123, 'key': 'value'}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-78-28797b7c5a91> in <module>()
      1 print x
      2 del x
----> 3 print x

NameError: name 'x' is not defined

Function: function definition, pass by reference, keyword argument, default argument, lambda

a built-in immutable type: str, int, long, bool, float, tuple


In [80]:
def foo(x):
    x=x+1
    y=2*x
    return y
print foo(3)


8

In [81]:
x=3
print foo(x)
print x


8
3

In [84]:
def bar(x=[]):
    x.append(7)
    print "in loop: {}".format(x)

x=[1,2,3]
print x
bar(x)
print x


[1, 2, 3]
in loop: [1, 2, 3, 7]
[1, 2, 3, 7]

In [85]:
def func(x=0,y=0,z=0):#defualt input argument
    return x*100+y*10+z

func(1,2)


Out[85]:
120

In [87]:
func(y=2,z=3,x=1)#keyword input argument


Out[87]:
123

In [88]:
f=func

In [89]:
f(y=2)


Out[89]:
20

In [93]:
distance=[13,500,1370]#meter
def meter2Kilometer(d):
    return d/1000.0;

In [94]:
meter2Kilometer(distance)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-94-0289b1544d80> in <module>()
----> 1 meter2Kilometer(distance)

<ipython-input-93-26f4f625c2ba> in meter2Kilometer(d)
      1 distance=[13,500,1370]#meter
      2 def meter2Kilometer(d):
----> 3     return d/1000.0;

TypeError: unsupported operand type(s) for /: 'list' and 'float'

In [95]:
[meter2Kilometer(d) for d in distance]


Out[95]:
[0.013, 0.5, 1.37]

In [98]:
d2 = map(meter2Kilometer,distance)
print d2


[0.013, 0.5, 1.37]

In [101]:
d3 = map(lambda x: x/1000.0,distance)
print d3


[0.013, 0.5, 1.37]

In [105]:
distance=[13,500,1370]#meter
time=[1,10,100]
d3 = map(lambda s,t: s/float(t)*3.6, distance,time )
print d3


[46.800000000000004, 180.0, 49.32]

In [108]:
d4=filter(lambda s: s<1000, distance)
print d4


[13, 500]

In [110]:
total_distance=reduce(lambda i,j : i+j, distance)
total_distance


Out[110]:
1883

In [129]:
import numpy as np
x=np.arange(101)
print x


[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100]

In [130]:
np.histogram(x,bins=[0,50,60,70,80,100])


Out[130]:
(array([50, 10, 10, 10, 21], dtype=int64),
 array([  0,  50,  60,  70,  80, 100]))

In [131]:
print np.sort(x)


[  0   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17
  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35
  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53
  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71
  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89
  90  91  92  93  94  95  96  97  98  99 100]

Module: class, from, import, reload(), package and init


In [138]:
class Obj:
    def __init__(self, _x, _y):
        self.x = _x
        self.y = _y
    
    def update(self, _x, _y):
        self.x += _x
        self.y += _y  
        
    def __str__(self):
        return "x:%d, y:%d"%(self.x,self.y)

In [141]:
a=Obj(5,7)#call __init__
print a#call __str__
a.update(1,2)#call update
print a


x:5, y:7
x:6, y:9

In [163]:
import sys
import os
path=os.getcwd()
path=os.path.join(path,'lib')
print path
sys.path.insert(0, path)
from Obj import Obj as ob


C:\Users\Wasit\Documents\GitHub\PythonDay\notebook\lib

In [166]:
b=ob(7,9)
print b
b.update(3,7)
print b


x:7, y:9
x:10, y:16

In [158]:
os.getcwd()


Out[158]:
'C:\\Users\\Wasit\\Documents\\GitHub\\PythonDay\\notebook'

In [179]:
from mylib import mymodule as mm

In [180]:
mm=reload(mm)

In [182]:
print mm.Obj2(8,9)


x:8, y:9

In [ ]: