Sep 20-24, 2021 Vikrant Patil
These notes are available online at https://notes.pipal.in/2021/arcesium_finop_batch2/
© Pipal Academy LLP
Day 1 | Day 2 | Day 3 | Day 4 | Day 5
We will be using jupyter hub from https://lab2.pipal.in for this training.
login to hub and create a notebook with name module1-day2
len([1, 2, 3, 4, 5])
5
len("hello")
5
d = {"one":1, "two":2}
len(d)
2
point = (0, 1, 2,3)
len(point)
4
max([3, 4, 5, 6])
6
min([3, 4, 5, 6])
3
sum([4, 3, 2, 1, 1])
11
x = input("Enter some value")
x # value taken as input is always text
'45'
int(x)
45
sorted([5, 6, 7, 2, 1, 4, 2, 4])
[1, 2, 2, 4, 4, 5, 6, 7]
numbers = [34, 4 , 5, 6, 3, 2]
sorted(numbers)
[2, 3, 4, 5, 6, 34]
numbers
[34, 4, 5, 6, 3, 2]
textdata = "this is some text data"
textdata.startswith("this")
True
textdata.endswith("data")
True
textdata.endswith("Data")
False
textdata.islower() # are all character in this text in lower case?
True
x = input("Enter integer:")
x.isdecimal()
False
x.isdigit()
False
x.isalpha()
True
x.isalnum() # if text has alphabets or numbers
True
"variablename1232".isalnum()
True
textdata
'this is some text data'
textdata.upper()
'THIS IS SOME TEXT DATA'
textdata
'this is some text data'
textdata.capitalize() # make first char upper case
'This is some text data'
help(textdata.upper)
Help on built-in function upper:
upper() method of builtins.str instance
Return a copy of the string converted to uppercase.
textdata.lower()
'this is some text data'
textdata.title()
'This Is Some Text Data'
textdata.center(50)
' this is some text data '
textdata.rjust(50)
' this is some text data'
textdata.ljust(50)
'this is some text data '
textdata.replace(" ", ",") # frequently used
'this,is,some,text,data'
textdata
'this is some text data'
text_with_commas = textdata.replace(" ", ",")
text_with_commas
'this,is,some,text,data'
textdata.split() # breaks the text data into smaller parts...break whereever there is empty space
['this', 'is', 'some', 'text', 'data']
"these,are,some,words,with,comma,in,between".split(",") # this will break data into smaller strings where ever there is comma
['these', 'are', 'some', 'words', 'with', 'comma', 'in', 'between']
paragraph = """this is data from
some imaginary novel
which I wil use for understanding
split method of strings from python
language"""
words = paragraph.split()
len(words)
20
paragraph
'this is data from\nsome imaginary novel\nwhich I wil use for understanding \nsplit method of strings from python\nlanguage'
lines = paragraph.split("\n")
lines
['this is data from', 'some imaginary novel', 'which I wil use for understanding ', 'split method of strings from python', 'language']
len(lines)
5
page = """this is data from
some imaginary novel
which I wil use for understanding
split method of strings from python
language
this is data from
some imaginary novel
which I wil use for understanding
split method of strings from python
language
this is data from
some imaginary novel
which I wil use for understanding
split method of strings from python
language
"""
page
'this is data from\nsome imaginary novel\nwhich I wil use for understanding \nsplit method of strings from python\nlanguage\n\nthis is data from\nsome imaginary novel\nwhich I wil use for understanding \nsplit method of strings from python\nlanguage\n\nthis is data from\nsome imaginary novel\nwhich I wil use for understanding \nsplit method of strings from python\nlanguage\n'
paras = page.split("\n\n")
len(paras)
3
words
['this', 'is', 'data', 'from', 'some', 'imaginary', 'novel', 'which', 'I', 'wil', 'use', 'for', 'understanding', 'split', 'method', 'of', 'strings', 'from', 'python', 'language']
" ".join(words)
'this is data from some imaginary novel which I wil use for understanding split method of strings from python language'
",".join(words)
'this,is,data,from,some,imaginary,novel,which,I,wil,use,for,understanding,split,method,of,strings,from,python,language'
"_".join(words)
'this_is_data_from_some_imaginary_novel_which_I_wil_use_for_understanding_split_method_of_strings_from_python_language'
"-".join(words)
'this-is-data-from-some-imaginary-novel-which-I-wil-use-for-understanding-split-method-of-strings-from-python-language'
"/".join(words)
'this/is/data/from/some/imaginary/novel/which/I/wil/use/for/understanding/split/method/of/strings/from/python/language'
"/".join(["","home","vikrant","trainings","2021"])
'/home/vikrant/trainings/2021'
"\n"
'\n'
"\\"
'\\'
textdata.split()[-1]
'data'
textdata
'this is some text data'
textdata.replace("this", "that").replace("is","was")
'that was some text data'
problems
There is a varaible name which is a senetence with words seperated by _. convert that name into normal text senetence i.e. words seperated by space
name = "yet_another_variable_name_which_is_very_long"
convert this to
yet another variable name which is very long
On a website login , username can only be alphnumeric. user enter username in a variable username. how will you check if the name enetered follows the website's rule for username.
A complete filepath is given for a file. Find out in which folder the file is.
filepath = "c:\\Program Files\\Python3.9.7\\bin\\python
filepath = "c:\\Documents\Welcome.docx"
filename = "hello.xlsx"
"_".join("hello")# this is because join takes every item from "hello" andjoin it with _
'h_e_l_l_o'
"_".join(["test","this"])
'test_this'
"@232".isalnum()
False
"2323".isalnum()
True
"asa".isalpha()
True
"a123".isalnum()
True
"a123".isalpha() # this will check only aphabets
False
"\t" # this is not two char \ and t ... but it is single char \t
'\t'
len('\t')
1
"c:\Program Files\Python3.9.7\bin\python"
'c:\\Program Files\\Python3.9.7\x08in\\python'
print("c:\Program Files\Python3.9.7\nin\python")
c:\Program Files\Python3.9.7 in\python
r"c:\Program Files\Python3.9.7\bin\python" # r before " says that take this as raw string
'c:\\Program Files\\Python3.9.7\\bin\\python'
name = "yet_another_variable_name_which_is_very_long"
name.replace("_", " ")
'yet another variable name which is very long'
username = input("Eneter user name:")
username.isalnum()
True
filepath = "c:\\Program Files\\Python3.9.7\\bin\\python"
filepath.split("\\")[-2]
'bin'
filename = "hello.xlsx"
filename.split(".")[-1]
'xlsx'
filename = "hello.tar.gz"
filename.split(".")[-1] # text only after last . is taken as extension
'gz'
words = words[:8] # take first 8 words
words
['this', 'is', 'data', 'from', 'some', 'imaginary', 'novel', 'which']
words.index("is") # where is the location of 'is'
1
ones = [1, 1, 1, 1]
ones.index(1) # return location of first occurence of the item is present muliple times
0
words.count("some")
1
ones.count(1)
4
empty = []
empty.append(0)
empty
[0]
empty.append(1)
empty
[0, 1]
empty.append(3)
empty
[0, 1, 3]
words
['this', 'is', 'data', 'from', 'some', 'imaginary', 'novel', 'which']
words.insert(1, "extra") # this method modifies the list but does not return
words
['this', 'extra', 'is', 'data', 'from', 'some', 'imaginary', 'novel', 'which']
ones.extend([4, 4, 4])
ones
[1, 1, 1, 1, 4, 4, 4]
empty
[0, 1, 3]
empty.remove(3)
empty
[0, 1]
words
['this', 'extra', 'is', 'data', 'from', 'some', 'imaginary', 'novel', 'which']
words.remove('extra')
words
['this', 'is', 'data', 'from', 'some', 'imaginary', 'novel', 'which']
words.pop() # removes last item and also returns
'which'
words
['this', 'is', 'data', 'from', 'some', 'imaginary', 'novel']
words.sort() # this modifies original list
words
['data', 'from', 'imaginary', 'is', 'novel', 'some', 'this']
numbers
[34, 4, 5, 6, 3, 2]
numbers.sort()
numbers
[2, 3, 4, 5, 6, 34]
numbers.reverse()
numbers
[34, 6, 5, 4, 3, 2]
def square(x):
return x*x
def find_extension(filename):
tokens = filename.split(".")
return tokens[-1]
def sumofsquares(a, b):
return square(a) + square(b)
square
<function __main__.square(x)>
square(5)
25
square(10)
100
find_extension("hello.xlsx")
'xlsx'
def find_foldername(path, sep):
tokens = path.split(sep)
return tokens[-2]
find_foldername("c:\\Program Files\\Python3.9\\bin\\python.exe", "\\")
'bin'
find_extension("/home/vikrant/trainings/2021/arcesium_finop_bath2/index.html", "/")
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-143-00b2311d4da6> in <module> ----> 1 find_extension("/home/vikrant/trainings/2021/arcesium_finop_bath2/index.html", "/") TypeError: find_extension() takes 1 positional argument but 2 were given
find_foldername("/home/vikrant/trainings/2021/arcesium_finop_bath2/index.html", "/")
'arcesium_finop_bath2'
find_foldername("/", "/home/vikrant/trainings/2021/arcesium_finop_bath2/index.html")
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-145-0ddeaebcc794> in <module> ----> 1 find_foldername("/", "/home/vikrant/trainings/2021/arcesium_finop_bath2/index.html") <ipython-input-141-460699e2293c> in find_foldername(path, sep) 1 def find_foldername(path, sep): 2 tokens = path.split(sep) ----> 3 return tokens[-2] IndexError: list index out of range
def find_foldername(path, sep):
tokens = path.split(sep)
return tokens[-2]
find_foldername(sep="/",path="/home/vikrant/trainings/2021/arcesium_finop_bath2/index.html")
'arcesium_finop_bath2'
def cylinder_volume(radius, height):
return 3.14*radius**2*height
cylinder_volume(radius=1, height=2)
6.28
cylinder_volume(height=2, radius=1)
6.28
cylinder_volume(1, 2)
6.28
cylinder_volume(2, 1)# confusion! will get wrong results
12.56
square(5)
25
x = square(5)
x
25
def print_square(a):
print(a*a)
print_square(5)
25
square(5)
25
m = square(5)
m
25
n = print_square(5)
25
print(n)
None
Any function that does not return a value by return statement , it returns None
def add(2, 3): # incorrect
return 2+3
def add("a", "b"): # incorrect
return a + b
File "<ipython-input-164-0010f66ae02c>", line 1 def add(2, 3): # incorrect ^ SyntaxError: invalid syntax
def add(a, b): # this is correct and is just defination
return a+b
add(2,3)
5
a = 5
b = 7
add(a, b) # a, b here are variables passed as argument
12
add(8, 10) # 8 and 10 here are literals
18
problems
Net asset value or NAV is equls to fund's or company's total assets less its liabilities. NAV is usually calcaulated per share value for MF,ETF or closed ended fund. Write a function NAV which computes NAV. Compute NAV for total assets of 25,00,00,000 , liabilities 30,00,000 and 1000 shares
In finiancial terms a negative balance is represented with round brackets around the number instead of - sign. Write a function numeric_value which returns actual numeric value. For example a value "(1234)" is passed as argument yu should get -1234.0 as a result. if "2345.5" is give as argument to function it should return 2345.5
Have a look at following python code, what will it print, can you correct it if it wrong!
def twice(x):
print(2*x)
twice(twice(twice(5)))
def functionname(paramater1, prameter2)
return paramater1+paramater1
File "<ipython-input-173-ad6a9b991906>", line 1 def functionname(paramater1, prameter2) ^ SyntaxError: invalid syntax
def functionname(paramater1, prameter2):
return paramater1+paramater1
File "<ipython-input-174-5345c3fafa0a>", line 2 return paramater1+paramater1 ^ IndentationError: expected an indented block
def functionname(paramater1, prameter2):
return paramater1+paramater1
"hello".replace("hel", "cel")
'cello'
"hello".replace("cel", "del")
'hello'
#numeric_value("(1234)")
#-1234.0
float("(1243)")
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-179-985ba27261d0> in <module> ----> 1 float("(1243)") ValueError: could not convert string to float: '(1243)'
def numeric_value(strnum):
corrected_num = strnum.replace("(", "-").replace(")","")
return float(corrected_num)
numeric_value("(34343)")
-34343.0
numeric_value("543543")
543543.0
"(test)".remove(")")
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-183-c96c8ee5bd88> in <module> ----> 1 "(test)".remove(")") AttributeError: 'str' object has no attribute 'remove'
"(test)".replace(")","")
'(test'
def numericvalue(accvalue):
accvalue.replace("(", "-") # replaced dat is not stored anywhere
accvalue.replace(")","")
return float(accvalue)
text = "testdata"
text.replace("test","this")
'thisdata'
text
'testdata'
x = text.replace("test","this")
x
'thisdata'
text = text.replace("test","this")
text
'thisdata'
def numericvalue(accvalue):
local_var = accvalue.replace("(", "-") # replaced dat is not stored anywhere
xyz = local_var.replace(")","")
return float(xyz)
numericvalue("(23232)")
-23232.0
def twice(x):
print(2*x)
twice(twice(twice(5)))