Python Virtual Training For Arcesium - Module I - Day 3¶

Jan 16-20, 2023 Vikrant Patil

All notes are available online at https://notes.pipal.in/2023/arcesium_finop_jan/

Please login to https://engage.pipal.in/ and launch jupyter lab

For today create a notebook with name module1-day3

notebook names are case sensitive. Make sure you give correct name

© Pipal Academy LLP

Day-2 problem set¶

In [1]:
def simple_interest(principal, time, rate):# if name does not match with the problem defination then tests will fail
    return principal*time*rate

Common systax rules for python

  • There is no colon (to be used for selective places),semicolon (not to be used elsewhere also) required after every statement
  • only when have some block statement we need to end it with :
  • After every block statement, following lines should be indented by 4 spaces.
  • return does not need parenthesis
  • variables, functions and all statements are case sensitive
In [2]:
def mean(a, b, c, d, e): 
    return (a+b+c+d+e)/5 # this computes mean of only five numbers
    
In [3]:
def mean(numbers):
    return sum(numbers)/len(numbers)
    
In [4]:
mean([1, 2, 3, 4, 2, 3, 1, 3, 5, 6])
Out[4]:
3.0
In [5]:
nums = list(range(100))
In [6]:
mean(nums)
Out[6]:
49.5
In [7]:
input("Enter comma seperated numbers")
Out[7]:
'1, 2, 3, 4'
In [10]:
X= 5
In [12]:
x # small case
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[12], line 1
----> 1 x # small case

NameError: name 'x' is not defined
In [13]:
x = 5
In [14]:
x
Out[14]:
5

Methods¶

In [15]:
sentence = "There are some unwise words to experiment"
In [17]:
type(sentence) # str-> string->text data
Out[17]:
str
In [18]:
sentence.startswith("T")
Out[18]:
True
In [19]:
sentence.startswith("THERE") # case sensitive
Out[19]:
False
In [20]:
sentence.startswith("There")
Out[20]:
True
In [21]:
sentence.endswith("experiment")
Out[21]:
True
In [22]:
X = "X"
In [23]:
X.isupper()
Out[23]:
True
In [24]:
sentence.isupper()
Out[24]:
False
In [25]:
sentence.islower()
Out[25]:
False
In [26]:
sentence.isalnum()
Out[26]:
False
In [27]:
sentence
Out[27]:
'There are some unwise words to experiment'
In [28]:
"there".isalnum()
Out[28]:
True
In [29]:
"ther2323".isalnum()
Out[29]:
True
In [30]:
"2323".isalpha()
Out[30]:
False
In [31]:
int("one")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[31], line 1
----> 1 int("one")

ValueError: invalid literal for int() with base 10: 'one'
In [34]:
"one".isnumeric()
Out[34]:
False
In [35]:
"232323".isnumeric()
Out[35]:
True

Methods to modify data. modified but not original data, new data is created and that is returned

In [36]:
sentence
Out[36]:
'There are some unwise words to experiment'
In [38]:
sentence.upper()
Out[38]:
'THERE ARE SOME UNWISE WORDS TO EXPERIMENT'
In [39]:
"vikrant".capitalize()
Out[39]:
'Vikrant'
In [40]:
sentence
Out[40]:
'There are some unwise words to experiment'
In [41]:
sentence.upper()
Out[41]:
'THERE ARE SOME UNWISE WORDS TO EXPERIMENT'
In [42]:
sentence
Out[42]:
'There are some unwise words to experiment'
In [43]:
sentence.ljust(50)
Out[43]:
'There are some unwise words to experiment         '
In [44]:
sentence.rjust(80)
Out[44]:
'                                       There are some unwise words to experiment'
In [46]:
sentence.center(100) # additional input and worked on internal data
Out[46]:
'                             There are some unwise words to experiment                              '
In [47]:
sentence
Out[47]:
'There are some unwise words to experiment'
In [51]:
sentence.rjust(10) # 10 is less than length of the data stored inside
Out[51]:
'There are some unwise words to experiment'
In [49]:
len(sentence)
Out[49]:
41
In [50]:
sentence.rjust(45)
Out[50]:
'    There are some unwise words to experiment'
In [52]:
centered_sentence = sentence.center(100)
In [53]:
len(centered_sentence)
Out[53]:
100
In [54]:
centered_sentence
Out[54]:
'                             There are some unwise words to experiment                              '

mehods used widely during text processing

In [56]:
sentence[:3].upper()
Out[56]:
'THE'
In [57]:
sentence
Out[57]:
'There are some unwise words to experiment'
In [58]:
sentence.split() # this will seperate words by taking whitespace as word boundary
Out[58]:
['There', 'are', 'some', 'unwise', 'words', 'to', 'experiment']
In [59]:
words  = sentence.split()
In [60]:
words
Out[60]:
['There', 'are', 'some', 'unwise', 'words', 'to', 'experiment']
In [61]:
words[0].upper()
Out[61]:
'THERE'
In [62]:
def upper_first_three_words(sentence):
    words = sentence.split()
    return words[0].upper(), words[1].upper(), words[2].upper()
In [63]:
upper_first_three_words(sentence)
Out[63]:
('THERE', 'ARE', 'SOME')
In [64]:
upper_first_three_words("THis is another statement")
Out[64]:
('THIS', 'IS', 'ANOTHER')
In [65]:
"THIS IS ANOTHER"
Out[65]:
'THIS IS ANOTHER'
In [66]:
three_words = upper_first_three_words(sentence)
In [67]:
three_words
Out[67]:
('THERE', 'ARE', 'SOME')
In [69]:
" ".join(three_words) # given words I can stitch them together to form a sentence
Out[69]:
'THERE ARE SOME'
In [70]:
",".join(three_words)
Out[70]:
'THERE,ARE,SOME'
In [71]:
"\\".join(three_words)
Out[71]:
'THERE\\ARE\\SOME'
In [72]:
"\\".join(["c:", "program files", "python"])
Out[72]:
'c:\\program files\\python'
In [73]:
"".join(three_words)
Out[73]:
'THEREARESOME'
In [76]:
words_input = input("Eneter words seperated by comma")
In [77]:
words_input
Out[77]:
'one,two,three,four'
In [80]:
words_input.split(",") # you can also specify word boundary for spliting
Out[80]:
['one', 'two', 'three', 'four']
In [81]:
"   this has trailing whitespace at start".strip()
Out[81]:
'this has trailing whitespace at start'
In [83]:
"   this has trailing whitespace at start".split() # split can take one more continious white spaces as word boundary
Out[83]:
['this', 'has', 'trailing', 'whitespace', 'at', 'start']
In [84]:
"     dsfghds,sdsd,dsad, sadsa, sdsad    ".strip()
Out[84]:
'dsfghds,sdsd,dsad, sadsa, sdsad'
In [85]:
"     dsfghds,sdsd,dsad, sadsa, sdsad    ".lstrip()
Out[85]:
'dsfghds,sdsd,dsad, sadsa, sdsad    '
In [86]:
"     dsfghds,sdsd,dsad, sadsa, sdsad    ".rstrip()
Out[86]:
'     dsfghds,sdsd,dsad, sadsa, sdsad'

method chaining¶

In [88]:
"This is a statement".replace("This", "That").split()
Out[88]:
['That', 'is', 'a', 'statement']
In [90]:
"This is a statement".replace("This", "That").replace("is", "was")
Out[90]:
'That was a statement'
In [92]:
int("-12121".replace("-", "")) # just another simple way to make absolute!
Out[92]:
12121

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?
  2. A sentence has hyphen between every two words.How can you transorm it such that there will be space between every two words.
>>> sentence = "Yet-another-sentence-with-nothing-in-it"
  1. A path to file is given for a linux system. on a linux system path seperator is "/". How will you find only name of file from given path?
>>> path = "/home/vikrant/trainig/day1.html"
  1. Using string methods can you find extension of a file if filename is stored in a variable filename = "hello.xlsx"
In [102]:
def check_unsername(username):
    return username.isalnum()


def filename_unix(path):
    tokens = path.split("/")
    return tokens[-1]


def extension(filename):
    tokens = filename.split(".")
    return "." + tokens[-1]
    
In [103]:
extension("hello.py")
Out[103]:
'.py'
In [100]:
filename_unix("/home/vikrant/day.html")
Out[100]:
'day.html'

Lists methods¶

In [104]:
evens = range(2, 20, 2)
In [106]:
list(evens)
Out[106]:
[2, 4, 6, 8, 10, 12, 14, 16, 18]
In [107]:
list(range(10))
Out[107]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [108]:
list(range(1, 11))
Out[108]:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [109]:
nums = list(range(5))
In [110]:
nums
Out[110]:
[0, 1, 2, 3, 4]
In [111]:
nums.index(1)
Out[111]:
1
In [112]:
odds = list(range(1, 20, 2))
In [113]:
odds
Out[113]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [116]:
odds.index(5) # returns index of 5
Out[116]:
2
In [115]:
odds[2]
Out[115]:
5
In [117]:
odds.index(2)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[117], line 1
----> 1 odds.index(2)

ValueError: 2 is not in list
In [118]:
odds.count(2)
Out[118]:
0
In [133]:
odds.count(5) # returns count
Out[133]:
1
In [120]:
ones  = [1, 1, 1, 1, 1, 1]
In [121]:
ones.count(1)
Out[121]:
6
In [122]:
nums = [1, 1, 1, 1, 2, 2, 2, 3, 3]
In [123]:
nums.count(1)
Out[123]:
4
In [124]:
nums.count(3)
Out[124]:
2
In [125]:
empty = []
In [126]:
empty.append(1) # does not return anything , but appends given item at end
In [127]:
empty
Out[127]:
[1]
In [128]:
empty.append(3)
In [129]:
empty
Out[129]:
[1, 3]
In [130]:
empty.insert(0, 23) # does not return anything, but inserts item at given location
In [131]:
empty
Out[131]:
[23, 1, 3]
In [132]:
empty.remove(23) # does not return anything, but removes first occurence of given item
In [134]:
empty
Out[134]:
[1, 3]
In [135]:
nums
Out[135]:
[1, 1, 1, 1, 2, 2, 2, 3, 3]
In [136]:
nums.remove(1)
In [137]:
nums
Out[137]:
[1, 1, 1, 2, 2, 2, 3, 3]
In [138]:
nums.clear() # remove everything
In [139]:
nums
Out[139]:
[]
In [140]:
odds
Out[140]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [141]:
sorted(odds)
Out[141]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [142]:
nums = [4, 2, 2, 6, 3, 9, 3, 8, 4, 2]
In [143]:
nums
Out[143]:
[4, 2, 2, 6, 3, 9, 3, 8, 4, 2]
In [145]:
sorted(nums) # it will return new sorted list. original list remains as it is
Out[145]:
[2, 2, 2, 3, 3, 4, 4, 6, 8, 9]
In [146]:
nums
Out[146]:
[4, 2, 2, 6, 3, 9, 3, 8, 4, 2]
In [147]:
nums.sort() # this does not return anything. this will sort in place. original data order is lost
In [148]:
nums
Out[148]:
[2, 2, 2, 3, 3, 4, 4, 6, 8, 9]
In [149]:
nums.reverse() # does not return anything. but reverses the list in place
In [150]:
nums
Out[150]:
[9, 8, 6, 4, 4, 3, 3, 2, 2, 2]
In [151]:
nums.sort()
In [152]:
nums
Out[152]:
[2, 2, 2, 3, 3, 4, 4, 6, 8, 9]
In [153]:
nums.sort(reverse=True) # descending order, in place
In [154]:
nums
Out[154]:
[9, 8, 6, 4, 4, 3, 3, 2, 2, 2]
In [155]:
sorted(nums, reverse=True)
Out[155]:
[9, 8, 6, 4, 4, 3, 3, 2, 2, 2]
  • str methods will never change original data, str is immutable
  • list has many methods which changes the internal data
In [156]:
s = "hello"
In [157]:
s.upper()
Out[157]:
'HELLO'
In [158]:
s
Out[158]:
'hello'
In [159]:
s_upper = s.upper()
In [160]:
s_upper
Out[160]:
'HELLO'
In [161]:
s
Out[161]:
'hello'

quiz

What will be output

x = 10
def foo():
    x = 20

foo()
print(x)

output is 10

What happens if x is neither defined nor passed as an argument

x = 10

def foo():
    print(x)

foo()
In [163]:
x = 10

def foo():
    print(x) # because is not available local namespace, it will take it from global
    
foo()
10
In [164]:
x = 10

def foo():
    x = x + 1
    
foo()
print(x)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[164], line 6
      3 def foo():
      4     x = x + 1
----> 6 foo()
      7 print(x)

Cell In[164], line 4, in foo()
      3 def foo():
----> 4     x = x + 1

UnboundLocalError: local variable 'x' referenced before assignment
In [165]:
x = 10

def foo():
    x = 20 # local
    x = x + 1
    
    
foo()
print(x)
10
In [166]:
x = [1, 1, 1]

def appendzero(y):
    y.append(0) # a method which changes in place is called..so original will get modified
    
appendzero(x)
print(x)
[1, 1, 1, 0]
In [167]:
x = [1, 1, 1]

def appendzero(y):
    y = y + [0] # this is not append. also defining a local variable
    
appendzero(x)
print(x)
[1, 1, 1]
underlying execution mechanism for this is

y = y + [0] 
y = x + [0]
In [168]:
l = [1, 1, 1]
In [169]:
l + [0]
Out[169]:
[1, 1, 1, 0]
In [170]:
l
Out[170]:
[1, 1, 1]
In [171]:
x = [1, 1, 1]

def appendzero(y):
    return y.append(0) # a method which changes in place is called..so original will get modified
    
appendzero(x)
print(x)
[1, 1, 1, 0]
In [172]:
x = [1, 1, 1]

def appendzero(y):
    return y.append(0) # a method which changes in place is called..so original will get modified
    
print(appendzero(x))
print(x)
None
[1, 1, 1, 0]
In [173]:
nums
Out[173]:
[9, 8, 6, 4, 4, 3, 3, 2, 2, 2]
In [174]:
print(nums.index(8)) # this returns
1
In [175]:
print(nums.append(-1)) # this does not return
None
In [176]:
nums
Out[176]:
[9, 8, 6, 4, 4, 3, 3, 2, 2, 2, -1]
In [ ]: