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

Jun 20-24, 2022 Vikrant Patil

All notes are available online at https://notes.pipal.in/2022/arcesium_finop_batch1/

Please accept the invitation that you have received in your email and login to

https://engage.pipal.in/

© Pipal Academy LLP

Problem set Day 2¶

In [1]:
def mean(nums):
    return sum(nums)/len(nums)
In [2]:
scores = [20, 30, 35.7, 40, 50]
In [3]:
mean(scores) # when we call this function ... the argument scores->nums inside the function
Out[3]:
35.14

problems

What will this print?

In [4]:
y = 10

def foo():
    # -> this where the function is starting
    # this is only local variable!
    y = 50 # defining variable locally .. means inside the function
    
foo()
print(y)
10
In [5]:
def hello():
    print(name) # name is not defined even locally

hello()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [5], in <cell line: 4>()
      1 def hello():
      2     print(name) # name is not defined even locally
----> 4 hello()

Input In [5], in hello()
      1 def hello():
----> 2     print(name)

NameError: name 'name' is not defined
In [6]:
name # name is not there in global namespace also
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [6], in <cell line: 1>()
----> 1 name

NameError: name 'name' is not defined
In [7]:
name = "arcesium"
In [8]:
hello() 
arcesium

If any variable is not found in local context (namespace) then it can be taken for reading only purpose from global namespce if it exists there!

In [9]:
def xadder(y):
    return x+y # x is not there! so it will taken from global for reading only
In [10]:
x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [10], in <cell line: 1>()
----> 1 x

NameError: name 'x' is not defined
In [11]:
xadder(5)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Input In [11], in <cell line: 1>()
----> 1 xadder(5)

Input In [9], in xadder(y)
      1 def xadder(y):
----> 2     return x+y

NameError: name 'x' is not defined
In [12]:
x = 10
xadder(4)# it has used x from global namespace..
Out[12]:
14
In [155]:
global_x = 10

def changex():
    print("Before assigning", global_x) # will this use it as 10 ?...thats what is defined in global namespace
    global_x = 30  # the moment I make use of assignment operator , variable is made local
    
    print("after storing locally ..let me compute square:" , global_x**2)
    print("cube", global_x**3)
    
    

changex() # function call is over after this statement.
print(global_x) # now this will refer to global again
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [155], in <cell line: 12>()
      7     print("after storing locally ..let me compute square:" , global_x**2)
      8     print("cube", global_x**3)
---> 12 changex() # function call is over after this statement.
     13 print(global_x)

Input In [155], in changex()
      3 def changex():
----> 4     print("Before assigning", global_x) # will this use it as 10 ?...thats what is defined in global namespace
      5     global_x = 30  # the moment I make use of assignment operator , variable is made local
      7     print("after storing locally ..let me compute square:" , global_x**2)

UnboundLocalError: local variable 'global_x' referenced before assignment
In [14]:
def square(x):
    return x*x

def cube(x):
    return x**3

cube(square(2)) # compute square(2) first..then whatever is result is paased as an argument to cube 
Out[14]:
64
In [15]:
def add(x, y):
    print(x+y) # prints but does not return... 
    
print(add(2, 3))
5
None
In [16]:
del x
In [17]:
x = 10
def foo():
    x = x + 10 # trying to reffer global and create local at the same time... not possible! 
In [18]:
foo()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [18], in <cell line: 1>()
----> 1 foo()

Input In [17], in foo()
      2 def foo():
----> 3     x = x + 10

UnboundLocalError: local variable 'x' referenced before assignment
In [19]:
x = 10
def foo():
    y = x + 10
    x = y # trying to reffer global and create local at the same time... not possible! 
    
foo()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [19], in <cell line: 6>()
      3     y = x + 10
      4     x = y # trying to reffer global and create local at the same time... not possible! 
----> 6 foo()

Input In [19], in foo()
      2 def foo():
----> 3     y = x + 10
      4     x = y

UnboundLocalError: local variable 'x' referenced before assignment
In [20]:
y = 50

def foo():
    print(y)
    y = 10
    
foo()
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Input In [20], in <cell line: 7>()
      4     print(y)
      5     y = 10
----> 7 foo()

Input In [20], in foo()
      3 def foo():
----> 4     print(y)
      5     y = 10

UnboundLocalError: local variable 'y' referenced before assignment
In [21]:
y = 50

def foo():
    print(y)
    #y = 10 
    
foo()
50
In [22]:
x = 10
def foo():
    #y = x + 10
    y = 20
    x = y # will be allowed but x is local 
    
foo()
print(x)
10
In [23]:
x = 10
def foo():
    #y = x + 10
    y = 20
    x = y # will be allowed but x is local 
    return x
    
print(foo())
print("x", x)
20
x 10
In [24]:
x = 10
def foo():
    #y = x + 10
    y = 20
    x = y # will be allowed but x is local 
    return x
    
x = foo()
print("x", x)
x 20

methods¶

In [25]:
sentence = "Here is data for testing"
In [26]:
type(sentence) # what is the type of this object which senetence is referring to!
Out[26]:
str
In [27]:
sentence[0] # sentence (str) object has data which can be accessed with indexing/slicing
Out[27]:
'H'
In [28]:
sentence.count("a") # this function like construct works with data stored inside the object
Out[28]:
2
In [29]:
sentence.count("e")
Out[29]:
3
In [30]:
poem = """Twinkle twinkle little star
How I wonder what you are?
"""
In [31]:
poem.count("\n")
Out[31]:
2
In [32]:
sentence.startswith("Here") 
Out[32]:
True
In [33]:
sentence.startswith("What")
Out[33]:
False
In [34]:
sentence.isupper()
Out[34]:
False
In [35]:
"HELLO".isupper()
Out[35]:
True
In [36]:
"test".islower()
Out[36]:
True
In [37]:
sentence.islower()
Out[37]:
False
In [38]:
sentence.upper() # this is returned result..original data is as it is
Out[38]:
'HERE IS DATA FOR TESTING'
In [39]:
sentence
Out[39]:
'Here is data for testing'
In [40]:
sentence[0] = "W"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [40], in <cell line: 1>()
----> 1 sentence[0] = "W"

TypeError: 'str' object does not support item assignment
In [41]:
sentence.lower()
Out[41]:
'here is data for testing'
In [42]:
sentence.title()
Out[42]:
'Here Is Data For Testing'
In [43]:
sentence.replace("testing", "playing")
Out[43]:
'Here is data for playing'
In [44]:
text = "blah blah ..this is another"
In [45]:
text.replace("blah", "hello") # replace every occurence
Out[45]:
'hello hello ..this is another'
In [46]:
nums = [1, 2, 3, 54]
In [47]:
nums[3] = 4 # changed!
In [48]:
nums
Out[48]:
[1, 2, 3, 4]
In [49]:
print(cube(square(5))) # nested function call! inner most part will be executed first
15625
In [50]:
text_data = "(7638726.0)"
In [51]:
float(text_data)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [51], in <cell line: 1>()
----> 1 float(text_data)

ValueError: could not convert string to float: '(7638726.0)'
In [52]:
text_data.replace("(","")
Out[52]:
'7638726.0)'
In [53]:
text_data.replace("(","").replace(")","") # method chanining ... ->->-> executes from left to right
Out[53]:
'7638726.0'
In [54]:
f = float(  text_data.replace("(","").replace(")","")   )
In [55]:
f
Out[55]:
7638726.0
In [56]:
text_data
Out[56]:
'(7638726.0)'
In [57]:
first = text_data.replace("(","")
In [58]:
first
Out[58]:
'7638726.0)'
In [59]:
first.replace(")","")
Out[59]:
'7638726.0'
In [62]:
first = text_data.replace("(","")
print(type(first))
second = first.replace(")","")
print(type(second))
f = float(second)
print(type(f))
<class 'str'>
<class 'str'>
<class 'float'>
In [64]:
text_data.replace("(","").replace(")","")
Out[64]:
'7638726.0'
In [65]:
first = text_data.replace("(","")
second = first.replace(")","")
In [66]:
sentence
Out[66]:
'Here is data for testing'
In [67]:
sentence.replace("is", "was").upper()
Out[67]:
'HERE WAS DATA FOR TESTING'
In [68]:
sentence.replace("data", "some text, some text").count("text")
Out[68]:
2
In [69]:
sentence.replace("data", "some text, some text").replace("testing", "playing")
Out[69]:
'Here is some text, some text for playing'
In [70]:
sentence
Out[70]:
'Here is data for testing'
In [71]:
text_data.replace("(","").replace(")","")
Out[71]:
'7638726.0'
In [72]:
float(text_data.replace("(","").replace(")",""))
Out[72]:
7638726.0
In [73]:
first_replace = text_data.replace("(","")
second_replace= first_replace.replace(")","")
float(second_replace)
Out[73]:
7638726.0
In [74]:
"Hello"
Out[74]:
'Hello'
In [75]:
"Hello".count("l")
Out[75]:
2
In [77]:
print(cube(square(4)))
4096

String methods that create something other than a string!

In [80]:
sentence.split(" ") # list of words!
Out[80]:
['Here', 'is', 'data', 'for', 'testing']
In [81]:
poem
Out[81]:
'Twinkle twinkle little star\nHow I wonder what you are?\n'
In [82]:
print(poem)
Twinkle twinkle little star
How I wonder what you are?

In [83]:
poem.split("\n")
Out[83]:
['Twinkle twinkle little star', 'How I wonder what you are?', '']
In [84]:
poem.split(" ")
Out[84]:
['Twinkle',
 'twinkle',
 'little',
 'star\nHow',
 'I',
 'wonder',
 'what',
 'you',
 'are?\n']
In [85]:
poem.split() # all white spaces (is not jst space, it is also tab also new line)  as splitter
Out[85]:
['Twinkle',
 'twinkle',
 'little',
 'star',
 'How',
 'I',
 'wonder',
 'what',
 'you',
 'are?']
In [86]:
x = [1, 1, 1]
In [87]:
print(x)
[1, 1, 1]
In [88]:
words = sentence.split()
In [89]:
words
Out[89]:
['Here', 'is', 'data', 'for', 'testing']
In [90]:
" ".join(words)
Out[90]:
'Here is data for testing'
In [91]:
"_".join(words)
Out[91]:
'Here_is_data_for_testing'
In [93]:
folders = ["","home","vikrant","training","2022","arcesium"]
In [94]:
path = "/".join(folders)
In [95]:
path
Out[95]:
'/home/vikrant/training/2022/arcesium'
In [97]:
"\n" # newline
Out[97]:
'\n'
In [98]:
"\t"
Out[98]:
'\t'
In [99]:
"\\"
Out[99]:
'\\'
In [100]:
len("\n")
Out[100]:
1
In [101]:
len("\\")
Out[101]:
1
In [102]:
windowspath_sep = "\\"
In [105]:
foldersw = ["c:","program files","python","bin"]
windowspath_sep.join(foldersw)
Out[105]:
'c:\\program files\\python\\bin'
In [107]:
print(windowspath_sep.join(foldersw))
c:\program files\python\bin
In [108]:
python_executable_path = 'c:\\program files\\python\\bin\\python.exe'
In [109]:
python_executable_path.split(windowspath_sep)
Out[109]:
['c:', 'program files', 'python', 'bin', 'python.exe']
In [110]:
python_executable_path.split(windowspath_sep)[-1]
Out[110]:
'python.exe'

list methods

In [114]:
empty  = []
In [115]:
empty.append(1) # there is no print! that means this method appends , but does not return
In [116]:
empty
Out[116]:
[1]
In [117]:
empty.append(2)
In [118]:
empty
Out[118]:
[1, 2]
In [119]:
ones = [1, 1, 1, 1]
In [120]:
ones.append(-1)
In [121]:
ones
Out[121]:
[1, 1, 1, 1, -1]
In [122]:
empty
Out[122]:
[1, 2]
In [123]:
empty.append(3)
In [124]:
empty
Out[124]:
[1, 2, 3]
In [125]:
ones.extend([-1,-1,-1])
In [126]:
ones
Out[126]:
[1, 1, 1, 1, -1, -1, -1, -1]
In [127]:
ones.count(1)
Out[127]:
4
In [128]:
ones.count(-1)
Out[128]:
4
In [129]:
copyones = ones[:] # with slicing
In [130]:
copyones
Out[130]:
[1, 1, 1, 1, -1, -1, -1, -1]
In [131]:
anothercopy = ones.copy()
In [132]:
anothercopy
Out[132]:
[1, 1, 1, 1, -1, -1, -1, -1]
In [138]:
xlist = [1, 1, 1, 1]
ylist = xlist # this does not copy..it just makes another name to same data!
copyxlist = xlist.copy()
In [134]:
xlist.append(2)
In [135]:
xlist
Out[135]:
[1, 1, 1, 1, 2]
In [136]:
ylist
Out[136]:
[1, 1, 1, 1, 2]
In [137]:
copyxlist
Out[137]:
[1, 1, 1, 1]
In [139]:
x = 10
y = x
x = 20
In [140]:
ones
Out[140]:
[1, 1, 1, 1, -1, -1, -1, -1]
In [141]:
ones.remove(1)
In [142]:
ones # remove first occurence
Out[142]:
[1, 1, 1, -1, -1, -1, -1]
In [146]:
ones.clear()  # clear everything
In [145]:
ones
Out[145]:
[]
In [147]:
help(ones.clear)
Help on built-in function clear:

clear() method of builtins.list instance
    Remove all items from list.

In [152]:
nums = [1, 2, 3, 4]
In [153]:
nums.pop() # this mehod changes the data as well as retuns result
           # remove last item and return it 
Out[153]:
4
In [154]:
nums
Out[154]:
[1, 2, 3]