Python Virtual Training For Arcesium - Module I - Day 1

Dec 07-11, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch3/module1-day1.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4 | Day 5

We will be using jupyter hub from http://lab.pipal.in for this training.

esc + m -> covert the cell to markdown
esc +y  -> convert back the cell to code cell
shift + enter -> execute the cell

Header1

Header2

Header3

# Header1
## Header2
### Header3
In [1]:
2 + 3
Out[1]:
5

simply type text

Header1

Header2

Header1

Header2

Header3

Introduction to Python Programming

Consider the sentence and your response on it

- multiply three and four write down results in your paper notebook

In [2]:
42 + 0
Out[2]:
42

Working With python interpreter

if you run command python from windows cmd/unix terminal, mac terminal

Python 3.8.3 (default, Jul  2 2020, 16:21:59) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
In [3]:
3 + 4
Out[3]:
7

Numeric And Text Data

In [4]:
42 + 42 # text after # is comment 
Out[4]:
84
In [5]:
42 - 42
Out[5]:
0
In [6]:
42 * 2
Out[6]:
84
In [8]:
5 /2 # real number division
Out[8]:
2.5
In [9]:
5 // 2 # integer division
Out[9]:
2
In [10]:
2 ** 5 # raise to power
Out[10]:
32
In [11]:
5 % 2 # remainder when 5 divided by 2
Out[11]:
1

Real number/ float

In [12]:
1.1 + 1.1
Out[12]:
2.2
In [13]:
1.0 - 1.0
Out[13]:
0.0
In [14]:
1.0 * 2
Out[14]:
2.0
In [15]:
5.0 / 2
Out[15]:
2.5
In [16]:
5.0 // 2 
Out[16]:
2.0
In [17]:
2.0 ** 5 
Out[17]:
32.0

These symbols are called as operators. And these operators have some priorities when you face multiple operators in single statement.

In [18]:
2**5%5/2*7
Out[18]:
7.0

Priority table for operators

=============      ===========
operators          priorities
=============      ===========
**                 1
% // / *           2
+ -                3
=============      ===========
2**5%5/2*7
32%5/2*7
2/2*7
1.0*7
7.0
In [20]:
2**(5%5)/2*7 # with brackets you can change the priority
Out[20]:
3.5
In [23]:
3*2 # integer * integer => integer
Out[23]:
6
In [24]:
3*2.0 # integer * float => float
Out[24]:
6.0
In [25]:
4/2 # division results in float by default
Out[25]:
2.0
In [26]:
4//2 ## if you want integer then you must give explicitly integer division
Out[26]:
2
In [27]:
7 + 2 *3
Out[27]:
13
In [28]:
(7+2)*3
Out[28]:
27

Now we know wokring with numbers/numeric data , lets work with text data

In [29]:
"Hello this text data"
Out[29]:
'Hello this text data'
In [30]:
'Hello, this is also text data!'
Out[30]:
'Hello, this is also text data!'
In [31]:
"""line one
line two
line three
line four"""
Out[31]:
'line one\nline two\nline three\nline four'
In [32]:
2
Out[32]:
2
In [33]:
'''
one
two
three
four
'''
Out[33]:
'\none\ntwo\nthree\nfour\n'
In [34]:
"""
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
Out[34]:
"\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n"
In [35]:
"text\ntext1\ntext2"
Out[35]:
'text\ntext1\ntext2'
In [36]:
"Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"
  File "<ipython-input-36-3df91ab0e59e>", line 1
    "Beautiful is better than ugly.
                                   ^
SyntaxError: EOL while scanning string literal

Question: What will happen if I put multiline text in single(not tripple) quotes!

In [37]:
'''
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
'''
Out[37]:
"\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren't special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you're Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it's a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let's do more of those!\n"
In [38]:
"hello\ttest"
Out[38]:
'hello\ttest'
In [39]:
2 * 3
Out[39]:
6
In [40]:
"this is number 2, this is tab \t"
Out[40]:
'this is number 2, this is tab \t'

operators on text data (string)

In [42]:
"hello" + " world" # + operator results in concatenation of strings/text
Out[42]:
'hello world'
In [44]:
"*" * 5 # operator * results in repeating the string 5 times
Out[44]:
'*****'
In [45]:
"-"*10
Out[45]:
'----------'
In [46]:
3
Out[46]:
3
In [47]:
"3"
Out[47]:
'3'
In [48]:
"type any thing with any quote , single quote will come"
Out[48]:
'type any thing with any quote , single quote will come'
In [50]:
10.5*"5"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-1dac843b84c6> in <module>
----> 1 10.5*"5"

TypeError: can't multiply sequence by non-int of type 'float'
In [51]:
"hello"*5 
Out[51]:
'hellohellohellohellohello'
In [53]:
"hello"*"hello" #it won't allow multiplication with any random thing... only with integers it will allow multiplication
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-53-744c6cb46b68> in <module>
----> 1 "hello"*"hello" #it won't allow multiplication with any random thing... only with integers it will allow multiplication

TypeError: can't multiply sequence by non-int of type 'str'
In [54]:
"text"*3
Out[54]:
'texttexttext'
In [55]:
"text"*3.0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-55-97d7c01017a9> in <module>
----> 1 "text"*3.0

TypeError: can't multiply sequence by non-int of type 'float'
In [56]:
"text"*"hello"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-56-4f84203270ce> in <module>
----> 1 "text"*"hello"

TypeError: can't multiply sequence by non-int of type 'str'
In [57]:
"hello" + "world" # only text can be added in a text
Out[57]:
'helloworld'
In [58]:
"hello" + 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-58-295c36e74c04> in <module>
----> 1 "hello" + 3

TypeError: can only concatenate str (not "int") to str
In [59]:
"hello" + "3"
Out[59]:
'hello3'

Problems:

  • Use python to convert asset value of 39455.5 given in EUR to INR
  • Compound interest is caluclated using formula P(1+r/n)**(nt). In this this formula,P is the principal amount, r is the rate of interest per annum, n denotes the number of times in a year the interest is compounded. and t denotes the number of years of investment.Use python to compute totol amount for principle 26780, rate of interest 7%, interest is compounded quarterly and amount is invested for 5 years.
In [60]:
2 + 3
Out[60]:
5
In [61]:
39455.5 * 90.4 # here 90.4 is currency conversion rate
Out[61]:
3566777.2
In [62]:
# P(1+r/n)**(nt)
In [63]:
2(2+3)
<>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
<>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
<ipython-input-63-8b8375460855>:1: SyntaxWarning: 'int' object is not callable; perhaps you missed a comma?
  2(2+3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-63-8b8375460855> in <module>
----> 1 2(2+3)

TypeError: 'int' object is not callable
In [64]:
2*(2+3)
Out[64]:
10
In [65]:
# P(1+r/n)**(nt)
26780*(1+(7/100)/4)**(4*5)
Out[65]:
37887.76008234032

Variables and literals

In addition to arithmatic operators there is something called as = assignment operator

In [67]:
x = 10 # it has actually stored value 10 in something with name x, which can be used later
In [68]:
x + 2
Out[68]:
12
In [69]:
P = 26780
r = 7/100
n = 4
t = 5
In [70]:
P*(1+r/n)**(n*t)
Out[70]:
37887.76008234032
In [82]:
x = 155
y = 100 # to see this variable later I must execute this cell everytime I do a change
z = 500
In [72]:
x
Out[72]:
155
In [74]:
155 # this is called a litteral
Out[74]:
155
In [75]:
x + y
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-75-cd60f97aa77f> in <module>
----> 1 x + y

NameError: name 'y' is not defined
In [76]:
z
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-76-3a710d2a84f8> in <module>
----> 1 z

NameError: name 'z' is not defined
In [78]:
x 
Out[78]:
155
In [79]:
y
Out[79]:
100
In [80]:
z
Out[80]:
300
In [81]:
z
Out[81]:
300
In [85]:
z # before this line I made a change in a cell where z is defined... then I excuted that cell... then only I can see change here
Out[85]:
500
In [86]:
155 # is litteral
Out[86]:
155
In [87]:
x = 155 # is variable
In [88]:
x
Out[88]:
155

Now look at litteral in context of text data

In [89]:
vikrant = 10
In [90]:
"vikrant" # this is litteral
Out[90]:
'vikrant'
In [92]:
vikrant # this is variable
Out[92]:
10
In [93]:
s = "some value" # a variable is created through assugnement operator
In [95]:
2 = "hello" # you can't create a variable of any name that you wish
  File "<ipython-input-95-70b9256d9a2f>", line 1
    2 = "hello" # you can't create a variable of any name that you wish
    ^
SyntaxError: cannot assign to literal

What can be used as variable name?

  • The variable name can't start with number
  • it can be single word ( means no space allowed )
  • it can't have operators in it (*,+,-/%)
  • it can have alphabets[a-z][A-Z], digits[0-9] and underscore
In [96]:
a = 2
In [97]:
b = 3
In [99]:
a, b = 2, 3 # you can create as many variable as possible in single = operator
In [100]:
x,y,z = 0,0,0
In [101]:
r,g,b = 255,0,0

Problems: Have a look at following python statements.

x = 10
y = x
x = x + 10

What will be value of y after this?

In [102]:
x = 10
y = x
x = x+10
In [103]:
y
Out[103]:
10
In [104]:
x
Out[104]:
20

Problem:

x = 10
y = x
y = 25

what will be the value of x after this?

In [107]:
x = 10
y = x
y = 25
In [108]:
x
Out[108]:
10

lets do more with strings

In [109]:
s = "hello"
In [110]:
s
Out[110]:
'hello'
In [112]:
s[0] # square bracket and inside that some integer value
Out[112]:
'h'
In [113]:
s[4]
Out[113]:
'o'
In [114]:
s[1]
Out[114]:
'e'
In [116]:
s[0] # index starts at 0
Out[116]:
'h'
In [117]:
s[-1] # last
Out[117]:
'o'
In [119]:
s[-2] # second last
Out[119]:
'l'
In [120]:
s[4]
Out[120]:
'o'
In [122]:
s[5] # we have tried access beyond the string limit
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-122-b8371ecf24db> in <module>
----> 1 s[5] # we have tried access beyond the string limit

IndexError: string index out of range
In [123]:
p = "python"
   +---+---+---+---+---+---+
   | p | y | t | h | o | n |
   +---+---+---+---+---+---+
     0   1   2   3   4   5    --->
    -6  -5  -4  -3  -2  -1    <----

Collections

In [125]:
[1, 1, 1] # list .. which has stored 1 ,1 ,1 in it
Out[125]:
[1, 1, 1]
In [126]:
ones = [1, 1, 1, 1]
In [127]:
ones
Out[127]:
[1, 1, 1, 1]
In [128]:
numbers = [1, 2, 3, 4]
In [129]:
words = ["these", "are", "some", "words"]
In [132]:
words
Out[132]:
['these', 'are', 'some', 'words']
In [131]:
mixed = ["python", "solves", 42, 0]
In [133]:
name = "vikrant"
In [134]:
name
Out[134]:
'vikrant'
In [135]:
words
Out[135]:
['these', 'are', 'some', 'words']
In [136]:
numbers
Out[136]:
[1, 2, 3, 4]
In [138]:
print(words)
['these', 'are', 'some', 'words']
In [142]:
name ## reprentative repsonse of interpeter
Out[142]:
'vikrant'
In [144]:
print(name) # this is print
vikrant
In [146]:
name[0]
Out[146]:
'v'
In [147]:
print("hello")
hello
In [148]:
mixed 
Out[148]:
['python', 'solves', 42, 0]
In [149]:
nested = [[1, 2, 3], [2, 3, 4]]
In [150]:
words
Out[150]:
['these', 'are', 'some', 'words']
In [153]:
words[0] # zeroth word
Out[153]:
'these'
In [152]:
words[-1] # last word
Out[152]:
'words'
In [154]:
words[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-154-f6a2fb6dbef1> in <module>
----> 1 words[5]

IndexError: list index out of range
In [155]:
x = 10
In [156]:
words
Out[156]:
['these', 'are', 'some', 'words']
In [157]:
words[0] = "first"
In [158]:
words
Out[158]:
['first', 'are', 'some', 'words']
In [159]:
words[-1] = "last"
In [160]:
words
Out[160]:
['first', 'are', 'some', 'last']
In [161]:
name
Out[161]:
'vikrant'
In [162]:
name[0]
Out[162]:
'v'
In [165]:
name[0] = "V" # immutable object...once created can not be changed
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-165-bae53c36da2a> in <module>
----> 1 name[0] = "V" # immutable object...once created can not be changed

TypeError: 'str' object does not support item assignment
In [166]:
"hello " + name 
Out[166]:
'hello vikrant'
In [167]:
ones
Out[167]:
[1, 1, 1, 1]
In [169]:
ones * 2 # just like string it suports * and + operator
Out[169]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [170]:
ones2 = ones*2
In [171]:
ones2
Out[171]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [172]:
ones
Out[172]:
[1, 1, 1, 1]
In [173]:
fivestar = "*"*5
In [174]:
fivestar
Out[174]:
'*****'
In [175]:
zeros = [0, 0 , 0]
In [176]:
oneszeros = ones + zeros
In [180]:
oneszeros
Out[180]:
[1, 1, 1, 1, 0, 0, 0]
In [178]:
m = ones+ zeros
In [179]:
m
Out[179]:
[1, 1, 1, 1, 0, 0, 0]

Tuples

Siblings of list

In [188]:
color = (0, 0, 255) # tuple is created with ()/ list is created with []
In [189]:
color[0] # access of element from tuple is similar to list
Out[189]:
0
In [184]:
color[-1]
Out[184]:
255
In [185]:
color[2]
Out[185]:
255
In [186]:
color * 2
Out[186]:
(0, 0, 255, 0, 0, 255)
In [190]:
(1, 1, 1) + (0, 0, 0)
Out[190]:
(1, 1, 1, 0, 0, 0)
In [192]:
color
Out[192]:
(0, 0, 255)
In [194]:
color[2] = 0 # tuple is also immutable object , once created can not be modified
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-194-e8a66c712837> in <module>
----> 1 color[2] = 0 # tuple is also immutable object , once created can not be modified

TypeError: 'tuple' object does not support item assignment
In [195]:
color
Out[195]:
(0, 0, 255)
In [196]:
color[0]
Out[196]:
0
In [197]:
color[0] = 255
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-197-2b3a41c9613e> in <module>
----> 1 color[0] = 255

TypeError: 'tuple' object does not support item assignment
In [199]:
color = (255, 0, 0) # rbg
In [200]:
blue = (0, 0, 255)
In [201]:
red = (255, 0, 0)
In [203]:
color = blue
In [204]:
color
Out[204]:
(0, 0, 255)
In [205]:
color = red
In [206]:
color
Out[206]:
(255, 0, 0)
In [207]:
red[2]=10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-207-f4edf2e674e1> in <module>
----> 1 red[2]=10

TypeError: 'tuple' object does not support item assignment
In [208]:
purple = (255, 0, 15)
In [209]:
purple
Out[209]:
(255, 0, 15)
In [210]:
purple[2] = 50
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-210-132bd3d90e02> in <module>
----> 1 purple[2] = 50

TypeError: 'tuple' object does not support item assignment
In [211]:
purple = (255, 0, 50)
In [212]:
words[0]="zero"
In [213]:
words
Out[213]:
['zero', 'are', 'some', 'last']

Dictionaries

In [214]:
student = ['nishant','shivam','sachin']
In [215]:
student[0]
Out[215]:
'nishant'
In [216]:
student[2]
Out[216]:
'sachin'
In [217]:
emails = {"nishant":"nishant@xyz.com",
         "sachin":"sachin@xyz.com",
         "vikrant":"vikrant@xyz.com"} # curly brackets
In [218]:
emails
Out[218]:
{'nishant': 'nishant@xyz.com',
 'sachin': 'sachin@xyz.com',
 'vikrant': 'vikrant@xyz.com'}
In [219]:
ages = {"alice":13,
       "alex":5,
       "maya":23}
In [220]:
ages
Out[220]:
{'alice': 13, 'alex': 5, 'maya': 23}
In [223]:
emails['nishant'] # you give name/key instead of number
Out[223]:
'nishant@xyz.com'
In [224]:
ages['alice']
Out[224]:
13
In [225]:
ages['alice'] = 14
In [226]:
ages
Out[226]:
{'alice': 14, 'alex': 5, 'maya': 23}
In [227]:
stock = {"name":"IBM",
        "open":123,
        "close":125,
        "high":126,
        "low":120.4}
In [228]:
stock
Out[228]:
{'name': 'IBM', 'open': 123, 'close': 125, 'high': 126, 'low': 120.4}
In [229]:
stock['name']
Out[229]:
'IBM'
In [234]:
stock['close'] # you can access only by name/key not by position or index
Out[234]:
125
In [232]:
stock["close"]
Out[232]:
125
In [233]:
nums = {1:"one",
       2:"two"}

boolean

In [231]:
True
Out[231]:
True
In [235]:
False
Out[235]:
False
In [236]:
x == 10
Out[236]:
True
In [237]:
multiline = """
line one
line two
line three
"""
In [238]:
multiline
Out[238]:
'\nline one\nline two\nline three\n'
In [239]:
print(multiline)
line one
line two
line three

In [240]:
homework = {"poem":"""
my poem
line 1
line 2
line3
"""}
In [241]:
homework['poem']
Out[241]:
'\nmy poem\nline 1\nline 2\nline3\n'
In [242]:
stock1 = {"name":"IBM", "open":123}
In [243]:
stock1 = {"name":"IBM", 
          "open":123}
In [244]:
matrix = [
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3]
]
In [245]:
matrix
Out[245]:
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [246]:
mat = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
In [247]:
l = [23, 343 , "helllo"]
In [248]:
bignames = ["fkjdhsf dhfdkjs hfkjhdsfkjhds kjfhdskjfh dhf",
           "kjdshf kjdhfkjdshf lkdjflkjds lkdsjflkjdsf ",
           "dsjfgdshfg jdjgfdg dsjfgdshgf djgf gdjfghdsg f"]
In [250]:
bignames[0]
Out[250]:
'fkjdhsf dhfdkjs hfkjhdsfkjhds kjfhdskjfh dhf'
In [251]:
t = (
    "this is my first item from tuple",
    2,
    "This is last item from tuple"
)
In [253]:
t[0]
Out[253]:
'this is my first item from tuple'

Take home assignment

Those who do not have python installed on your system. go this site and download appropriate python executable installer and install it on your system.

https://www.python.org/downloads/windows/

In [ ]: