Python Virtual Training For Arcesium - Module I - Day 2

Aug 10-14, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch1_module1/day2.html

© Pipal Academy LLP

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

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

make use of notebook module1-day2.ipynb for today's session.

String methods

In [1]:
sentence = "These Are Few Wise Words"

Mehtods to perform some checks on a string

In [2]:
sentence.startswith("These")
Out[2]:
True
In [3]:
sentence.startswith("This")
Out[3]:
False
In [4]:
sentence.endswith("nums")
Out[4]:
False
In [5]:
sentence.endswith("Words")
Out[5]:
True
In [6]:
sentence.isupper()
Out[6]:
False
In [7]:
sum([1, 2, 3])
Out[7]:
6
In [8]:
startswith("There")
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-eef961d4ec93> in <module>
----> 1 startswith("There")

NameError: name 'startswith' is not defined
In [9]:
type(sentence)
Out[9]:
str
In [10]:
sentence.isupper()
Out[10]:
False
In [11]:
sentence.islower()
Out[11]:
False
In [12]:
sentence.title()
Out[12]:
'These Are Few Wise Words'
In [13]:
sentence.isalpha() ##check is it contains all alphabets only, no spaces
Out[13]:
False
In [14]:
"khdskjdshfds".isalpha()
Out[14]:
True
In [15]:
"hjsdjhs hjsdkjhsa".isalpha()
Out[15]:
False
In [16]:
sentence.isalnum() ## check if it's a alphanumeric string. alphabets and digits. no spaces
Out[16]:
False
In [17]:
"user1234".isalnum()
Out[17]:
True

Question In a dictionary if we save key values as strings then can we use these methods?

Yes

In [18]:
person = {"name":"Alice", "email":"alice@wonder.land"}
In [19]:
person['name'].isupper()
Out[19]:
False
In [20]:
person['name'].istitle()
Out[20]:
True
In [21]:
person['email'].endswith(".land")
Out[21]:
True
In [22]:
person = {"name":"Alice", "email":"alice@wonder.land", "age":13}
In [24]:
type(person['age'])
Out[24]:
int
In [25]:
person['age'].isupper()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-25-ad7a10b02b08> in <module>
----> 1 person['age'].isupper()

AttributeError: 'int' object has no attribute 'isupper'

In addition to checks , string also has methods transform. ALl these transform methods are returning new string, keeping the original as it is.

In [26]:
"hello".capitalize()
Out[26]:
'Hello'
In [27]:
sentence.upper()
Out[27]:
'THESE ARE FEW WISE WORDS'
In [28]:
sentence
Out[28]:
'These Are Few Wise Words'
In [29]:
sentence.lower()
Out[29]:
'these are few wise words'
In [30]:
"hello , how are you?".title()
Out[30]:
'Hello , How Are You?'
In [31]:
sentence.rjust(50)
Out[31]:
'                          These Are Few Wise Words'
In [32]:
len(sentence.rjust(50))
Out[32]:
50
In [33]:
sentence.ljust(50)
Out[33]:
'These Are Few Wise Words                          '
In [35]:
sentence.center(50)
Out[35]:
'             These Are Few Wise Words             '
In [36]:
sentence.replace(" ", "-")
Out[36]:
'These-Are-Few-Wise-Words'

Following tranform methods will be used very extensively

In [37]:
sentence.split() # splits the sentence in words, words are assumed to be seperated by white space
Out[37]:
['These', 'Are', 'Few', 'Wise', 'Words']
In [38]:
poem = """This is first line
this second line
this is thrid line"""
In [39]:
poem
Out[39]:
'This is first line\nthis second line\nthis is thrid line'
In [40]:
poem.split()
Out[40]:
['This',
 'is',
 'first',
 'line',
 'this',
 'second',
 'line',
 'this',
 'is',
 'thrid',
 'line']
In [41]:
lines = poem.split("\n")
In [42]:
lines
Out[42]:
['This is first line', 'this second line', 'this is thrid line']
In [43]:
sentence.split("\n")
Out[43]:
['These Are Few Wise Words']
In [44]:
poem.split()
Out[44]:
['This',
 'is',
 'first',
 'line',
 'this',
 'second',
 'line',
 'this',
 'is',
 'thrid',
 'line']
In [45]:
["word"]*5
Out[45]:
['word', 'word', 'word', 'word', 'word']
In [46]:
["word"]*10
Out[46]:
['word',
 'word',
 'word',
 'word',
 'word',
 'word',
 'word',
 'word',
 'word',
 'word']
In [47]:
"name_of_a_valid_python_variable".split()
Out[47]:
['name_of_a_valid_python_variable']
In [48]:
"name_of_a_valid_python_variable".split("_")
Out[48]:
['name', 'of', 'a', 'valid', 'python', 'variable']
In [49]:
sentence.split?
Signature: sentence.split(sep=None, maxsplit=-1)
Docstring:
Return a list of the words in the string, using sep as the delimiter string.

sep
  The delimiter according which to split the string.
  None (the default value) means split according to any whitespace,
  and discard empty strings from the result.
maxsplit
  Maximum number of splits to do.
  -1 (the default value) means no limit.
Type:      builtin_function_or_method
In [50]:
help(sentence.split)
Help on built-in function split:

split(sep=None, maxsplit=-1) method of builtins.str instance
    Return a list of the words in the string, using sep as the delimiter string.
    
    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.

In [51]:
help("".split)
Help on built-in function split:

split(sep=None, maxsplit=-1) method of builtins.str instance
    Return a list of the words in the string, using sep as the delimiter string.
    
    sep
      The delimiter according which to split the string.
      None (the default value) means split according to any whitespace,
      and discard empty strings from the result.
    maxsplit
      Maximum number of splits to do.
      -1 (the default value) means no limit.

In [53]:
# help(str) ypu can see help of all methods from str object using this statement

Opposite of split is join

In [54]:
words = ["one", "two", "three"]
In [55]:
" ".join(words)
Out[55]:
'one two three'
In [56]:
"-".join(words)
Out[56]:
'one-two-three'
In [57]:
words = sentence.split()
In [58]:
words
Out[58]:
['These', 'Are', 'Few', 'Wise', 'Words']
In [59]:
"_".join(words)
Out[59]:
'These_Are_Few_Wise_Words'

We will look at methods which will allow us to remove trailing spaces

In [61]:
"                    hello this is a log string with spaces at left".lstrip() # it will strip spaces on left hand side
Out[61]:
'hello this is a log string with spaces at left'
In [64]:
rspaces = sentence.ljust(50)
In [65]:
rspaces
Out[65]:
'These Are Few Wise Words                          '
In [66]:
rspaces.rstrip()
Out[66]:
'These Are Few Wise Words'
In [67]:
"    a string with trainling spaces on both side       ".strip()
Out[67]:
'a string with trainling spaces on both side'
In [68]:
multiline= """line one
line two
line three
"""
In [69]:
multiline
Out[69]:
'line one\nline two\nline three\n'
In [71]:
multiline.split("\n")
Out[71]:
['line one', 'line two', 'line three', '']
In [72]:
strippedpoem = multiline.strip()
In [73]:
strippedpoem.split("\n")
Out[73]:
['line one', 'line two', 'line three']

Method chanining

In [74]:
multiline.strip().split("\n")
Out[74]:
['line one', 'line two', 'line three']
In [76]:
multiline.strip().split("\n")[-1] # last line
Out[76]:
'line three'
multiline.strip().split("\n")[-1]
------------->------>---------->- works this way

problems

  1. On a website login , only alphanumeric usernames are allowed. a string is stored in a variable username. How will you check if username is as per rules?we tran
  2. A sentence has hyphen beween every two words.

     >>> sentence = "Yet-another-sentence-with-nothing-much-in-it"

    how can we transform it such that there will be spaces between two word.

  3. A seperator for windows operating system is sep = "\\". Folder names starting from C: drive till the folder containing an executable 'python.exe' are given in a list

     >>> folders = ["C:", "Program Files", "python3.8"]

    how will you make a string for complete path to python.exe

  4. A path to file is given on linux system. On a linux system path sepearator is "/"

     >>> path = "/home/vikrant/training/day2.html"

    How will you find only name of file from given path.

  5. Using string methods, can you find extension of a file if filename is stored if a variable `filename="hello.xlsx"

  6. Make a string which has double quote in it!

In [78]:
"\""
Out[78]:
'"'
In [79]:
"\"
  File "<ipython-input-79-a16852ba415a>", line 1
    "\"
       ^
SyntaxError: EOL while scanning string literal

Solution 1

In [80]:
username = "vikrant23243"
In [81]:
username.isalnum()
Out[81]:
True

solution 2

In [82]:
sentence = "Yet-another-sentence-with-nothing-much-in-it"
In [83]:
sentence.replace("-", " ")
Out[83]:
'Yet another sentence with nothing much in it'

solution 3

In [85]:
sep = "\\"
folders = ["C:", "Program Files", "python3.8"]
exe = "python.exe"
path = sep.join(folders) 
In [86]:
path
Out[86]:
'C:\\Program Files\\python3.8'
In [87]:
folders + [exe]
Out[87]:
['C:', 'Program Files', 'python3.8', 'python.exe']
In [88]:
path = sep.join(folders + [exe])
In [89]:
print(path)
C:\Program Files\python3.8\python.exe
In [90]:
path
Out[90]:
'C:\\Program Files\\python3.8\\python.exe'

solution 4

In [91]:
path = "/home/vikrant/training/day2.html"
In [92]:
path.split("/")
Out[92]:
['', 'home', 'vikrant', 'training', 'day2.html']
In [93]:
path.split("/")[-1]
Out[93]:
'day2.html'

solution 5

In [94]:
filename = "hello.xlsx"
In [95]:
filename.split(".")
Out[95]:
['hello', 'xlsx']
In [96]:
filename.split(".")[-1]
Out[96]:
'xlsx'

solution 6

In [97]:
stringwithdoublequote = '"'
In [98]:
print(stringwithdoublequote)
"
In [99]:
stringwithsinglequote = "'"
In [100]:
print(stringwithsinglequote)
'

Method from list

list has method to find item in it:

In [101]:
nums = [1, 2, 3, 4]
In [102]:
nums.index(3)
Out[102]:
2
In [103]:
nums.index(1)
Out[103]:
0
In [104]:
nums[0]
Out[104]:
1
In [105]:
words = ["one", "two", "three"]
In [106]:
words.index("two")
Out[106]:
1
In [107]:
words[1]
Out[107]:
'two'
In [108]:
nums = [1, 1, 1, 3, 3, 3, 4, 4,1 , 5, 5]
In [110]:
nums.count(1)
Out[110]:
4
In [111]:
nums.count(3)
Out[111]:
3
In [112]:
nums.count(4)
Out[112]:
2
There are methods to add new items to list
In [113]:
empty = []
In [118]:
empty.append(1) # adds item at end of list
In [115]:
empty
Out[115]:
[1]
In [116]:
empty.append(1)
In [117]:
empty
Out[117]:
[1, 1]
In [119]:
empty.insert(0, 23) # adds item in a list at given location  lst.insert(where?, what?)
In [120]:
empty
Out[120]:
[23, 1, 1, 1]
In [121]:
empty.extend([0, 0, 0]) ## add items at end from given list
In [122]:
empty
Out[122]:
[23, 1, 1, 1, 0, 0, 0]
List has methods to remove items from it
In [132]:
nums = [1, 2, 3]
In [133]:
nums.remove(2) # will remove first occurence of given item
In [134]:
nums
Out[134]:
[1, 3]
In [145]:
nums = [1, 1, 1, 3, 3, 3, 4, 4,1 , 5, 5]
In [146]:
nums.remove(1)
In [147]:
nums
Out[147]:
[1, 1, 3, 3, 3, 4, 4, 1, 5, 5]
In [148]:
nums.remove(5)
In [149]:
nums
Out[149]:
[1, 1, 3, 3, 3, 4, 4, 1, 5]
In [150]:
nums.pop() # will remove and return last item from a list
Out[150]:
5
In [151]:
nums
Out[151]:
[1, 1, 3, 3, 3, 4, 4, 1]
In [152]:
digits = [0, 1, 2, 3, 4, 5]
In [153]:
last_item = digits.pop()
In [154]:
last_item
Out[154]:
5
In [155]:
digits
Out[155]:
[0, 1, 2, 3, 4]
In [156]:
digits = [0, 1, 2, 3, 4, 5]
In [157]:
removed_item = digits.remove(5)
In [158]:
print(removed_item)
None
In [160]:
words = ["a","b","c","d","e"]
In [161]:
words.pop(2) # remove item at location 2 and return it
Out[161]:
'c'
In [162]:
words
Out[162]:
['a', 'b', 'd', 'e']
In [163]:
words.clear()
In [164]:
words
Out[164]:
[]

list also has some other method to manipulate list

In [165]:
randomnums = [ 12, 1, 3, 5,2, 43, 1, 42]
In [168]:
randomnums.sort() # sort the list in place
In [167]:
randomnums
Out[167]:
[1, 1, 2, 3, 5, 12, 42, 43]
In [169]:
randomnums.reverse() # it will reverse the list inplace
In [170]:
randomnums
Out[170]:
[43, 42, 12, 5, 3, 2, 1, 1]
In [172]:
randomnums.copy() ## returns a copy of list
Out[172]:
[43, 42, 12, 5, 3, 2, 1, 1]
In [173]:
randomnums[::]
Out[173]:
[43, 42, 12, 5, 3, 2, 1, 1]
In [177]:
x = randomnums.copy()
In [178]:
x.append(-11)
In [179]:
x
Out[179]:
[43, 42, 12, 5, 3, 2, 1, 1, -11]
In [180]:
randomnums
Out[180]:
[43, 42, 12, 5, 3, 2, 1, 1]
In [181]:
randomnums.sort(reverse=True) 
In [182]:
randomnums
Out[182]:
[43, 42, 12, 5, 3, 2, 1, 1]
In [183]:
randomnums.sort()
In [184]:
randomnums
Out[184]:
[1, 1, 2, 3, 5, 12, 42, 43]

Creating your own functions

As of now we used only statements. No programs. Putting few statements together for later and frequent use is doen through functions. Functions allow us to make us black box. What is a black box. A box which has input terminals, through which you give inputs. And there are output terminals through which receive output.

In [185]:
def square(x):
    y = x * x
    return y
         +-------+
    x--->| square|----->y
         |       |
         +-------+

The moment we execute this, in current namespace a name called square is created. code for this function is stored somewhere in memory. then name sqaure is connected to code location in memory.

In [187]:
square ## just examining ! 
Out[187]:
<function __main__.square(x)>
In [188]:
square(3)
Out[188]:
9
In [190]:
def sumofsquares(a, b): # defination start line, must start with def and end with :
    a2 = square(a) # next line has to indented at 4 space (by convention)
    b2 = square(b) # all lines in this code block should be at same indentation
    return a2 + b2 # finally return

sumofsquares(2, 3) # make note of changed indentation
Out[190]:
13
In [192]:
def sumofsquares(a, b): # defination start line, must start with def and end with :
    a2 = square(a) # next line has to indented at 4 space (by convention)
    b2 = square(b) # all lines in this code block should be at same indentation
    return a2 + b2 # finally return

    sumofsquares(2, 3)  # indentaion imakes this line inside the function
In [193]:
def donothing():
    pass # do nothing
In [198]:
def say_hello(name):
    print("Hello", name) # a function without return statement actually returns an object called None
In [195]:
say_hello("Python")
Hello Python
In [196]:
x = say_hello("Python")
Hello Python
In [197]:
print(x)
None
In [199]:
sqr5 = square(5)
In [200]:
print(sqr5)
25

A function with variable number of arguments

In [210]:
def mysum(*args):# this syntax allows us to pass variable number of arguments
    print(type(args))
In [202]:
mysum(12, 23, 23)
<class 'tuple'>
In [203]:
sum([1, 2, 3, 4])
Out[203]:
10
In [204]:
sum((2, 3, 4, 5))
Out[204]:
14
In [205]:
def mysum(*args):
    return sum(args)
In [223]:
def mysum(*nums): # here * is the syntax...rest is just variable name
    return sum(nums)
In [224]:
mysum(1, 2, 3)
Out[224]:
6
In [207]:
mysum(2, 3)
Out[207]:
5
In [208]:
mysum(1, 2, 3, 4, 5, 6)
Out[208]:
21

Calling Functions Vs Functions

In [211]:
def add(2, 3): # incorrect
    return 2 + 3
  File "<ipython-input-211-5c46505af097>", line 1
    def add(2, 3): # incorrect
            ^
SyntaxError: invalid syntax
In [212]:
def add("a", "b"): # incorrect
    return a + b
  File "<ipython-input-212-949e9b55f4a7>", line 1
    def add("a", "b"): # incorrect
            ^
SyntaxError: invalid syntax
In [213]:
def add("a", "b"): # incorrect
    return "a" + "b"
  File "<ipython-input-213-a55344606a3f>", line 1
    def add("a", "b"): # incorrect
            ^
SyntaxError: invalid syntax
In [214]:
def add(a, b):
    return a+b
In [215]:
add(2, 3)
Out[215]:
5
In [217]:
add(a, b)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-217-6816481791a0> in <module>
----> 1 add(a, b)

NameError: name 'a' is not defined
In [218]:
x = 5
y = 6
In [219]:
add(x, y)
Out[219]:
11
In [220]:
a = 34
b = 36
add(a, b)
Out[220]:
70
In [222]:
sumofsquares(add(2, 3), square(5))
sumofsquares(5, 25)
Out[222]:
650

problems

  1. Net asset value , NAV is equal to fund's or company's total asset less it's liabilities. NAV is usually calculated per share value for MF, ETF or closed ended fund. Write a function NAV. Compute NAV for total assets of 25,00,00,000 , liabilities 30,00,000 and 1000 shares.
  2. In financial terms a -ve number is represented py round brackets around the number instaed of -ve sign. Write a function numeric_value which returns actual numeric value. For example a value "(1234)" should return -1234 and "1234" should return 1234.
  3. Have a look at following python code what will it print? can you correct it?

     def twice(x)
         print(2*x)
    
     print(twice(twice(3))
In [ ]: