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.
sentence = "These Are Few Wise Words"
Mehtods to perform some checks on a string
sentence.startswith("These")
sentence.startswith("This")
sentence.endswith("nums")
sentence.endswith("Words")
sentence.isupper()
sum([1, 2, 3])
startswith("There")
type(sentence)
sentence.isupper()
sentence.islower()
sentence.title()
sentence.isalpha() ##check is it contains all alphabets only, no spaces
"khdskjdshfds".isalpha()
"hjsdjhs hjsdkjhsa".isalpha()
sentence.isalnum() ## check if it's a alphanumeric string. alphabets and digits. no spaces
"user1234".isalnum()
Question In a dictionary if we save key values as strings then can we use these methods?
Yes
person = {"name":"Alice", "email":"alice@wonder.land"}
person['name'].isupper()
person['name'].istitle()
person['email'].endswith(".land")
person = {"name":"Alice", "email":"alice@wonder.land", "age":13}
type(person['age'])
person['age'].isupper()
In addition to checks , string also has methods transform. ALl these transform methods are returning new string, keeping the original as it is.
"hello".capitalize()
sentence.upper()
sentence
sentence.lower()
"hello , how are you?".title()
sentence.rjust(50)
len(sentence.rjust(50))
sentence.ljust(50)
sentence.center(50)
sentence.replace(" ", "-")
Following tranform methods will be used very extensively
sentence.split() # splits the sentence in words, words are assumed to be seperated by white space
poem = """This is first line
this second line
this is thrid line"""
poem
poem.split()
lines = poem.split("\n")
lines
sentence.split("\n")
poem.split()
["word"]*5
["word"]*10
"name_of_a_valid_python_variable".split()
"name_of_a_valid_python_variable".split("_")
sentence.split?
help(sentence.split)
help("".split)
# help(str) ypu can see help of all methods from str object using this statement
Opposite of split is join
words = ["one", "two", "three"]
" ".join(words)
"-".join(words)
words = sentence.split()
words
"_".join(words)
We will look at methods which will allow us to remove trailing spaces
" hello this is a log string with spaces at left".lstrip() # it will strip spaces on left hand side
rspaces = sentence.ljust(50)
rspaces
rspaces.rstrip()
" a string with trainling spaces on both side ".strip()
multiline= """line one
line two
line three
"""
multiline
multiline.split("\n")
strippedpoem = multiline.strip()
strippedpoem.split("\n")
Method chanining
multiline.strip().split("\n")
multiline.strip().split("\n")[-1] # last line
multiline.strip().split("\n")[-1]
------------->------>---------->- works this way
problems
username. How will you check if username is as per rules?we tranA 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.
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
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.
Using string methods, can you find extension of a file if filename is stored if a variable `filename="hello.xlsx"
Make a string which has double quote in it!
"\""
"\"
Solution 1
username = "vikrant23243"
username.isalnum()
solution 2
sentence = "Yet-another-sentence-with-nothing-much-in-it"
sentence.replace("-", " ")
solution 3
sep = "\\"
folders = ["C:", "Program Files", "python3.8"]
exe = "python.exe"
path = sep.join(folders)
path
folders + [exe]
path = sep.join(folders + [exe])
print(path)
path
solution 4
path = "/home/vikrant/training/day2.html"
path.split("/")
path.split("/")[-1]
solution 5
filename = "hello.xlsx"
filename.split(".")
filename.split(".")[-1]
solution 6
stringwithdoublequote = '"'
print(stringwithdoublequote)
stringwithsinglequote = "'"
print(stringwithsinglequote)
list has method to find item in it:
nums = [1, 2, 3, 4]
nums.index(3)
nums.index(1)
nums[0]
words = ["one", "two", "three"]
words.index("two")
words[1]
nums = [1, 1, 1, 3, 3, 3, 4, 4,1 , 5, 5]
nums.count(1)
nums.count(3)
nums.count(4)
empty = []
empty.append(1) # adds item at end of list
empty
empty.append(1)
empty
empty.insert(0, 23) # adds item in a list at given location lst.insert(where?, what?)
empty
empty.extend([0, 0, 0]) ## add items at end from given list
empty
nums = [1, 2, 3]
nums.remove(2) # will remove first occurence of given item
nums
nums = [1, 1, 1, 3, 3, 3, 4, 4,1 , 5, 5]
nums.remove(1)
nums
nums.remove(5)
nums
nums.pop() # will remove and return last item from a list
nums
digits = [0, 1, 2, 3, 4, 5]
last_item = digits.pop()
last_item
digits
digits = [0, 1, 2, 3, 4, 5]
removed_item = digits.remove(5)
print(removed_item)
words = ["a","b","c","d","e"]
words.pop(2) # remove item at location 2 and return it
words
words.clear()
words
list also has some other method to manipulate list
randomnums = [ 12, 1, 3, 5,2, 43, 1, 42]
randomnums.sort() # sort the list in place
randomnums
randomnums.reverse() # it will reverse the list inplace
randomnums
randomnums.copy() ## returns a copy of list
randomnums[::]
x = randomnums.copy()
x.append(-11)
x
randomnums
randomnums.sort(reverse=True)
randomnums
randomnums.sort()
randomnums
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.
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.
square ## just examining !
square(3)
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
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
def donothing():
pass # do nothing
def say_hello(name):
print("Hello", name) # a function without return statement actually returns an object called None
say_hello("Python")
x = say_hello("Python")
print(x)
sqr5 = square(5)
print(sqr5)
A function with variable number of arguments
def mysum(*args):# this syntax allows us to pass variable number of arguments
print(type(args))
mysum(12, 23, 23)
sum([1, 2, 3, 4])
sum((2, 3, 4, 5))
def mysum(*args):
return sum(args)
def mysum(*nums): # here * is the syntax...rest is just variable name
return sum(nums)
mysum(1, 2, 3)
mysum(2, 3)
mysum(1, 2, 3, 4, 5, 6)
def add(2, 3): # incorrect
return 2 + 3
def add("a", "b"): # incorrect
return a + b
def add("a", "b"): # incorrect
return "a" + "b"
def add(a, b):
return a+b
add(2, 3)
add(a, b)
x = 5
y = 6
add(x, y)
a = 34
b = 36
add(a, b)
sumofsquares(add(2, 3), square(5))
sumofsquares(5, 25)
problems
NAV. Compute NAV for total assets of 25,00,00,000 , liabilities 30,00,000 and 1000 shares.numeric_value which returns actual numeric value. For example a value "(1234)" should return -1234 and "1234" should return 1234.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))