Python Virtual Training For Arcesium - Module I - Day 3

Dec 07-11, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch3/module1-day3.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. Create a notebook with name module1-day3.ipynb for today's session

In [ ]:
 
In [ ]:
 

Quick recap - methods from string

In [1]:
text = "some text with some contents"
In [2]:
type(text)
Out[2]:
str
In [3]:
text.startswith("some")
Out[3]:
True
In [4]:
text.endswith("s")
Out[4]:
True
In [5]:
text.isupper()
Out[5]:
False
In [6]:
text.isalnum()
Out[6]:
False
In [7]:
text.istitle()
Out[7]:
False
In [8]:
text.capitalize()
Out[8]:
'Some text with some contents'
In [9]:
text.upper()
Out[9]:
'SOME TEXT WITH SOME CONTENTS'
In [10]:
upper_text = text.upper()
In [11]:
print(upper_text)
SOME TEXT WITH SOME CONTENTS
In [12]:
text.lower()
Out[12]:
'some text with some contents'
In [13]:
text.title()
Out[13]:
'Some Text With Some Contents'
In [27]:
text.rjust(50) # right justify with width 50, pads space chars to left side so that text moves to right
Out[27]:
'                      some text with some contents'
In [15]:
text.ljust(50)
Out[15]:
'some text with some contents                      '
In [16]:
rtext = text.rjust(50)
In [17]:
len(rtext)
Out[17]:
50
In [18]:
rtext[:10] # first 10 items from the string
Out[18]:
'          '
In [19]:
space = ' ' # space char
In [20]:
print(rtext)
                      some text with some contents
In [22]:
rtext
Out[22]:
'                      some text with some contents'
In [23]:
len(text)
Out[23]:
28
In [25]:
rtext[:50-28] # only space chars
Out[25]:
'                      '
In [26]:
rtext[:50-28+1]
Out[26]:
'                      s'
In [28]:
ltext = text.ljust(50)
In [29]:
ltext
Out[29]:
'some text with some contents                      '
In [30]:
text.center(50)
Out[30]:
'           some text with some contents           '
In [32]:
text.center(10)# if width is less than the len of str then nothing happens
Out[32]:
'some text with some contents'
In [33]:
text.split() # splits the string into words based on spaces
Out[33]:
['some', 'text', 'with', 'some', 'contents']
In [34]:
words = text.split()
In [35]:
" ".join(words)
Out[35]:
'some text with some contents'
In [36]:
"_".join(words)
Out[36]:
'some_text_with_some_contents'
In [39]:
folders = ["", "home", "vikrant" , "training","2020", "arcesium_finop_batch3"]
In [40]:
"/".join(folders)
Out[40]:
'/home/vikrant/training/2020/arcesium_finop_batch3'

Problems:

  • A sentence has hyphen between every two word.
text = "Yet-another-sentence-with-nothing-in-it"

How can you transform it such that there will be space beween two words.

  • A path separator for windows os is
sep = "\\" escapce char
Thers is list of folders from C:
folders = ["C:", "Program Files", "python3.9"]

can you make a string for complete path to python installation folder? "c:\Program Files\python3.9"

  • On unix system a path of file is given
path = "/home/vikrant/training/module-day1.ipynb"

can you find out only filename?

  • Can you find out extension of a file given in variable filename

filename = "hello.xlsx"

solutions

In [42]:
text = "Yet-another-sentence-with-nothing-in-it"
In [43]:
text.split() # without any argument, then it splits on spaces
Out[43]:
['Yet-another-sentence-with-nothing-in-it']
In [44]:
text.split("-") # if argument is given , then string is split into words based on arg
Out[44]:
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
In [45]:
words = text.split("-")
In [46]:
words
Out[46]:
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
In [47]:
" ".join(words)
Out[47]:
'Yet another sentence with nothing in it'
In [48]:
space = " "
In [49]:
space
Out[49]:
' '
In [50]:
words
Out[50]:
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
In [51]:
space.join(words)
Out[51]:
'Yet another sentence with nothing in it'
In [52]:
space.join(["1", "2", "3", "4"])
Out[52]:
'1 2 3 4'
In [53]:
type(words)
Out[53]:
list
In [54]:
numbers = [1, 2, 3, 4, 5]
In [55]:
mixed = [{"x":1}, {1, 2, 3}, [1, 2, 3, 4], "hello"]
In [56]:
mixed
Out[56]:
[{'x': 1}, {1, 2, 3}, [1, 2, 3, 4], 'hello']
In [57]:
" ".join([1, 2, 3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-57-97add66affa3> in <module>
----> 1 " ".join([1, 2, 3])

TypeError: sequence item 0: expected str instance, int found
In [59]:
" ".join(["text", "string"]) # will work only on list of strings/text
Out[59]:
'text string'
In [60]:
" ".join(['1', '2', '3'])
Out[60]:
'1 2 3'
In [61]:
['1,2,3'] # looks like a list, list of str, how many string?
Out[61]:
['1,2,3']
In [62]:
" ".join(['1,2,3'])
Out[62]:
'1,2,3'
In [63]:
"_".join(text) #
Out[63]:
'Y_e_t_-_a_n_o_t_h_e_r_-_s_e_n_t_e_n_c_e_-_w_i_t_h_-_n_o_t_h_i_n_g_-_i_n_-_i_t'
In [64]:
numbers = [1, 2, 3, 4]
In [65]:
text = "abrakadabra"
In [66]:
"_".join(("hey","whats","this","?"))
Out[66]:
'hey_whats_this_?'
In [67]:
"_".join((1, 2, 34))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-67-bacf98c46fa1> in <module>
----> 1 "_".join((1, 2, 34))

TypeError: sequence item 0: expected str instance, int found

Observation:.join(arg), here arg can be any collection that contains strings or chars

In [68]:
c = "a"
In [69]:
"Hello this is another text".replace(" ",",")
Out[69]:
'Hello,this,is,another,text'
In [70]:
"Hello this is another text".replace(" ","-")
Out[70]:
'Hello-this-is-another-text'
In [71]:
text
Out[71]:
'abrakadabra'
In [72]:
text = "Yet-another-sentence-with-nothing-in-it"
In [73]:
text.replace("-"," ")
Out[73]:
'Yet another sentence with nothing in it'
In [76]:
winsep = "\\" # this actually one char
In [75]:
print(winsep)
\
In [77]:
newline = "\n" # this single char
In [78]:
len(newline)
Out[78]:
1
In [79]:
len(winsep)
Out[79]:
1
In [80]:
"""
line1
line2
line3
"""
Out[80]:
'\nline1\nline2\nline3\n'
In [81]:
len(winsep)
Out[81]:
1
In [82]:
folders = ["C:", "Program Files", "python3.9"]
In [84]:
winsep.join(folders) # what you see on next line is repr (representative)
Out[84]:
'C:\\Program Files\\python3.9'
In [86]:
print(winsep.join(folders))
C:\Program Files\python3.9
In [87]:
multi = """a
b
c
d"""
In [89]:
multi # repr of multi
Out[89]:
'a\nb\nc\nd'
In [90]:
print(multi)
a
b
c
d
In [91]:
tabbed = "one\ttwo\tthree\tend"
In [93]:
tabbed # repr
Out[93]:
'one\ttwo\tthree\tend'
In [94]:
print(tabbed)
one	two	three	end
In [95]:
path = "/home/vikrant/training/module-day1.ipynb"
In [97]:
tokens = path.split("/")
In [98]:
tokens
Out[98]:
['', 'home', 'vikrant', 'training', 'module-day1.ipynb']
In [100]:
tokens[len(tokens)-1]
Out[100]:
'module-day1.ipynb'
In [102]:
tokens[-1] # last
Out[102]:
'module-day1.ipynb'
In [103]:
filename = "hello.xlsx"
In [105]:
pre, ext = filename.split(".")
In [106]:
print(pre, ext)
hello xlsx
In [107]:
download = "xyz.tar.gz"
In [110]:
pre, post = download.split(".") # right hand side has resulted in three items, while we are trying to store it in two!
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-110-a3e592c4b3e7> in <module>
----> 1 pre, post = download.split(".") # right hand side has resulted in three items, while we are trying to store it in two!

ValueError: too many values to unpack (expected 2)
In [111]:
x, y = 1, 2 
In [112]:
1, 2
Out[112]:
(1, 2)
In [113]:
x, y = (1, 2)
In [114]:
print(x, y)
1 2
In [115]:
a, b = [1, 2]
In [116]:
print(a, b)
1 2
In [117]:
a, b = [1, 2, 3]
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-117-c702cf699c19> in <module>
----> 1 a, b = [1, 2, 3]

ValueError: too many values to unpack (expected 2)
In [118]:
tokens = download.split(".")
In [119]:
tokens
Out[119]:
['xyz', 'tar', 'gz']
In [120]:
pre, ext = tokens
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-120-d9d4df25e16a> in <module>
----> 1 pre, ext = tokens

ValueError: too many values to unpack (expected 2)
In [123]:
download.split(".", maxsplit=1)
Out[123]:
['xyz', 'tar.gz']
In [124]:
"   hello this is a another text with some spaces at start"
Out[124]:
'   hello this is a another text with some spaces at start'
In [125]:
text = "   hello this is a another text with some spaces at start"
In [126]:
text.split()
Out[126]:
['hello',
 'this',
 'is',
 'a',
 'another',
 'text',
 'with',
 'some',
 'spaces',
 'at',
 'start']
In [127]:
multi
Out[127]:
'a\nb\nc\nd'
In [129]:
multi.split() # split, splits on eny white spaces... ' ', a tab, a new line
Out[129]:
['a', 'b', 'c', 'd']
In [130]:
"heloo        this  has multi spaces".split()
Out[130]:
['heloo', 'this', 'has', 'multi', 'spaces']
In [133]:
header = " Name,age,email,address\n"
In [135]:
header.split(",")
Out[135]:
[' Name', 'age', 'email', 'address\n']
In [136]:
columnnames = header.split(",")
In [137]:
columnnames[0]
Out[137]:
' Name'
In [138]:
columnnames[-1]
Out[138]:
'address\n'
In [145]:
choped = header.strip() #remove trailing spcaes , only from start and end!
In [141]:
choped
Out[141]:
'Name,age,email,address'
In [142]:
choped.split(",")
Out[142]:
['Name', 'age', 'email', 'address']
In [143]:
header
Out[143]:
' Name,age,email,address\n'
In [144]:
choped
Out[144]:
'Name,age,email,address'
In [147]:
"address\n".split("\n")
Out[147]:
['address', '']
In [148]:
header.strip()
Out[148]:
'Name,age,email,address'
In [151]:
header.split(",") #this returns a new list
Out[151]:
[' Name', 'age', 'email', 'address\n']
In [154]:
header # original string is same, it has not changed
Out[154]:
' Name,age,email,address\n'
In [156]:
header.strip().split(",")
Out[156]:
['Name', 'age', 'email', 'address']
In [158]:
c  = header.strip()
In [159]:
c
Out[159]:
'Name,age,email,address'
In [160]:
c.split(",")
Out[160]:
['Name', 'age', 'email', 'address']
In [161]:
header.strip().split()
Out[161]:
['Name,age,email,address']

Method chaining

header = " Name,age,email,address\n"
header.strip().split(",")[-1]
------>----->----------->----->----- mehtods will get executed in this order
`
In [162]:
header
Out[162]:
' Name,age,email,address\n'
In [163]:
header.split(",")
Out[163]:
[' Name', 'age', 'email', 'address\n']
In [165]:
person = {"Name":'Alice',
        "age":29,
        "email":"alice@wonder.land",
        "address":"Rabbit Hole"}
In [168]:
item_from_file = header.split(",")[0]
In [169]:
person[item_from_file]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-169-c6ab33472414> in <module>
----> 1 person[item_from_file]

KeyError: ' Name'
In [170]:
item_from_file
Out[170]:
' Name'
In [174]:
person[' Name'] # because of additional space, we can not retrive data from dict
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-174-a0bbc2ea300b> in <module>
----> 1 person[' Name'] # because of additional space, we can not retrive data from dict

KeyError: ' Name'
In [172]:
person['Name']
Out[172]:
'Alice'
In [173]:
person['name']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-173-0430809b25ad> in <module>
----> 1 person['name']

KeyError: 'name'
In [175]:
person[item_from_file.strip()]
Out[175]:
'Alice'
In [176]:
item_from_file
Out[176]:
' Name'
In [177]:
item_from_file.strip()
Out[177]:
'Name'
In [178]:
poem = """
this is frist line of poem
last line of poem
"""
In [179]:
print(poem)
this is frist line of poem
last line of poem

In [180]:
print(poem)
this is frist line of poem
last line of poem

In [181]:
poem
Out[181]:
'\nthis is frist line of poem\nlast line of poem\n'
In [182]:
f = open("/home/vikrant/Downloads/JH How Children Learn.txt")
firstline = f.readline() 
In [183]:
firstline
Out[183]:
'The best learning of children occurs before they go to school. \n'
In [184]:
f.close()
In [185]:
itemname = input("Enter name of item that you want to read from dictionary:")
In [186]:
itemname
Out[186]:
'Name '
In [187]:
fullname = input("Enter your fullname (first name and second name)")
In [188]:
fullname = input("Enter your fullname (first name and second name)")
In [189]:
fullname.strip()
Out[189]:
'vikran patil'

Methods from Lists

In [191]:
nums = [1, 2, 3,4, 5, -1]
In [193]:
nums.index(-1) # location of -1 in nums
Out[193]:
5
In [194]:
nums.index(0) # ??
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-194-7ea439dad2d9> in <module>
----> 1 nums.index(0) # ??

ValueError: 0 is not in list
In [195]:
nums.index(5)
Out[195]:
4
In [197]:
nums.count(-1) # how many times -1 comes?
Out[197]:
1
In [198]:
nums.count(0)
Out[198]:
0
In [199]:
nums = [1, 1, 2, 2, 3, 3, 5, 5, 5, 5, 5, 5, 5]
In [200]:
nums.count(5)
Out[200]:
7
In [201]:
nums.count(1)
Out[201]:
2
In [209]:
empty = []
In [210]:
empty
Out[210]:
[]
In [211]:
empty.append(1) # it adds 1 at end of empty
In [212]:
empty
Out[212]:
[1]
In [213]:
empty.append(-1) # append adds at end
In [214]:
empty
Out[214]:
[1, -1]
In [215]:
text.replace(" ",",")
Out[215]:
',,,hello,this,is,a,another,text,with,some,spaces,at,start'
In [218]:
empty.append(0) # this method does append but does not return a value
In [220]:
empty # this has 2 zeros because we executed line number 218 twice
Out[220]:
[1, -1, 0, 0]
In [221]:
x = text.split()
In [222]:
x
Out[222]:
['hello',
 'this',
 'is',
 'a',
 'another',
 'text',
 'with',
 'some',
 'spaces',
 'at',
 'start']
In [228]:
y = empty.append(1) # this will not save anything in y
In [225]:
print(y)
None
In [226]:
y
In [227]:
empty
Out[227]:
[1, -1, 0, 0, 1]
In [229]:
y = empty
In [230]:
y
Out[230]:
[1, -1, 0, 0, 1, 1]
In [231]:
y = [1, 2, 3]
In [232]:
y = empty.append(5)
In [233]:
y
In [234]:
empty.insert(0, 23)
In [235]:
empty
Out[235]:
[23, 1, -1, 0, 0, 1, 1, 5]
In [236]:
empty.insert(3, 22)
In [237]:
empty
Out[237]:
[23, 1, -1, 22, 0, 0, 1, 1, 5]
In [239]:
empty.remove(23)
In [240]:
empty
Out[240]:
[1, -1, 22, 0, 0, 1, 1, 5]
In [241]:
empty.remove(1)
In [242]:
empty
Out[242]:
[-1, 22, 0, 0, 1, 1, 5]
In [243]:
empty.remove(1)
In [244]:
empty
Out[244]:
[-1, 22, 0, 0, 1, 5]
In [245]:
empty.pop() # removes last item and returns it
Out[245]:
5
In [246]:
empty
Out[246]:
[-1, 22, 0, 0, 1]
In [247]:
x = empty.pop()
In [248]:
x
Out[248]:
1
In [249]:
empty
Out[249]:
[-1, 22, 0, 0]
In [250]:
empty.pop(2)
Out[250]:
0
In [251]:
empty
Out[251]:
[-1, 22, 0]
In [254]:
empty.clear() # delete every item
In [255]:
empty
Out[255]:
[]
In [256]:
nums
Out[256]:
[1, 1, 2, 2, 3, 3, 5, 5, 5, 5, 5, 5, 5]
In [257]:
nums.reverse()
In [258]:
nums
Out[258]:
[5, 5, 5, 5, 5, 5, 5, 3, 3, 2, 2, 1, 1]

Creating custom functions

In [260]:
def square(x):
    s = x*x
    return s
In [261]:
square
Out[261]:
<function __main__.square(x)>
In [262]:
square(5)
Out[262]:
25
In [263]:
def square(x)
    s = x*x
    return s
  File "<ipython-input-263-459b539ed1d4>", line 1
    def square(x)
                 ^
SyntaxError: invalid syntax
In [264]:
def square(x):
    s = x*x
    return s
In [265]:
def square(x):
s = x*x
return s
  File "<ipython-input-265-0210685aca91>", line 2
    s = x*x
    ^
IndentationError: expected an indented block
In [266]:
def square(x):
    s = x*x
    return s
In [268]:
def square(x):
    s = x*x

return s
  File "<ipython-input-268-34e939e5f78a>", line 4
    return s
    ^
SyntaxError: 'return' outside function
In [273]:
def square(x):
    s = x*x
    print(s)
    # this function has no return statement
In [270]:
square(5)
25
In [271]:
sqr5 = square(5) # to get the result in variable , the function has to return
25
In [272]:
print(sqr5)
None
In [274]:
def square(x):
    s = x*x
    return s
In [275]:
print(square(5))
25
In [280]:
def twice(x):
    print(2*x) # it is returning None!!
In [277]:
twice(5)
10
In [278]:
twice(10)
20
In [279]:
twice(twice(5)) # first inner fucntion call will be  executed
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-279-25ba0e1add61> in <module>
----> 1 twice(twice(5)) # first inner fucntion call will be  executed

<ipython-input-276-8db4314a5c52> in twice(x)
      1 def twice(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [281]:
def twice(x):
    return 2*x
In [282]:
twice(twice(5))
Out[282]:
20
In [283]:
twice(twice(twice(5)))
Out[283]:
40
In [284]:
square(5)
Out[284]:
25
In [289]:
def square(x):
    return x*x

def double(x):
    return 2*x
In [290]:
sq5 = square(5)
In [291]:
double(sq5)
Out[291]:
50
In [292]:
double(square(5))
Out[292]:
50
In [293]:
double(square(6))
Out[293]:
72
In [294]:
def twice(x):
    print(2*x) # this is not returning anything.. it will return None
In [295]:
2*None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-295-ebf0962da868> in <module>
----> 1 2*None

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [296]:
twice(None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-296-011f23172eca> in <module>
----> 1 twice(None)

<ipython-input-294-8db4314a5c52> in twice(x)
      1 def twice(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [297]:
s1 = twice(5)# None
twice(s1)
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-297-6a9f4b479ef4> in <module>
      1 s1 = twice(5)# None
----> 2 twice(s1)

<ipython-input-294-8db4314a5c52> in twice(x)
      1 def twice(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [298]:
twice(twice(5))
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-298-bb3a0f0c8472> in <module>
----> 1 twice(twice(5))

<ipython-input-294-8db4314a5c52> in twice(x)
      1 def twice(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [299]:
def twice(x):
    return 2*x
In [300]:
twice(twice(5))
Out[300]:
20

Problems

  1. Net asset value, or NAV, is equal to a fund's or company's total assets less its liabilities. NAV is usually computed per share value for MF,ETF or closed ended fund. Write a function to compute NAV. Compute NAV for total assets of 25,00,00,000, liabilities of 30,00,000 and 1000 shares.
         >>> NAV(assets,liabilities,shares)
  2. In financial terms a negative balance is represented with round barackets around the number instead of - sign. Write a function numeric_value which returns actual numeric value. For example a value "(1234)" should get -1234 as numeric value. while "1234.5" will still get value as 1234.5.:
     >>> numeric_value("(35.5)")
     -35.5
     >>> numeric_value("32.5")
     32.5
  3. Compount interest is calculated using formula P (1 + r/n)nt For 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 gets compounded, and t denotes the number of years. Write a function compounded_total which takes P, n, r, and t as arguments of a function and returns total value after t years.
  4. See the results of this and think about it, we will discuss it tomorrow
x = 10
def foo():
    x = x+1

foo()
print(x)
In [ ]: