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
© Pipal Academy LLP
def mean(nums):
return sum(nums)/len(nums)
scores = [20, 30, 35.7, 40, 50]
mean(scores) # when we call this function ... the argument scores->nums inside the function
35.14
problems
What will this print?
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
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
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
name = "arcesium"
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!
def xadder(y):
return x+y # x is not there! so it will taken from global for reading only
x
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [10], in <cell line: 1>() ----> 1 x NameError: name 'x' is not defined
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
x = 10
xadder(4)# it has used x from global namespace..
14
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
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
64
def add(x, y):
print(x+y) # prints but does not return...
print(add(2, 3))
5 None
del x
x = 10
def foo():
x = x + 10 # trying to reffer global and create local at the same time... not possible!
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
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
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
y = 50
def foo():
print(y)
#y = 10
foo()
50
x = 10
def foo():
#y = x + 10
y = 20
x = y # will be allowed but x is local
foo()
print(x)
10
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
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
sentence = "Here is data for testing"
type(sentence) # what is the type of this object which senetence is referring to!
str
sentence[0] # sentence (str) object has data which can be accessed with indexing/slicing
'H'
sentence.count("a") # this function like construct works with data stored inside the object
2
sentence.count("e")
3
poem = """Twinkle twinkle little star
How I wonder what you are?
"""
poem.count("\n")
2
sentence.startswith("Here")
True
sentence.startswith("What")
False
sentence.isupper()
False
"HELLO".isupper()
True
"test".islower()
True
sentence.islower()
False
sentence.upper() # this is returned result..original data is as it is
'HERE IS DATA FOR TESTING'
sentence
'Here is data for testing'
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
sentence.lower()
'here is data for testing'
sentence.title()
'Here Is Data For Testing'
sentence.replace("testing", "playing")
'Here is data for playing'
text = "blah blah ..this is another"
text.replace("blah", "hello") # replace every occurence
'hello hello ..this is another'
nums = [1, 2, 3, 54]
nums[3] = 4 # changed!
nums
[1, 2, 3, 4]
print(cube(square(5))) # nested function call! inner most part will be executed first
15625
text_data = "(7638726.0)"
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)'
text_data.replace("(","")
'7638726.0)'
text_data.replace("(","").replace(")","") # method chanining ... ->->-> executes from left to right
'7638726.0'
f = float( text_data.replace("(","").replace(")","") )
f
7638726.0
text_data
'(7638726.0)'
first = text_data.replace("(","")
first
'7638726.0)'
first.replace(")","")
'7638726.0'
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'>
text_data.replace("(","").replace(")","")
'7638726.0'
first = text_data.replace("(","")
second = first.replace(")","")
sentence
'Here is data for testing'
sentence.replace("is", "was").upper()
'HERE WAS DATA FOR TESTING'
sentence.replace("data", "some text, some text").count("text")
2
sentence.replace("data", "some text, some text").replace("testing", "playing")
'Here is some text, some text for playing'
sentence
'Here is data for testing'
text_data.replace("(","").replace(")","")
'7638726.0'
float(text_data.replace("(","").replace(")",""))
7638726.0
first_replace = text_data.replace("(","")
second_replace= first_replace.replace(")","")
float(second_replace)
7638726.0
"Hello"
'Hello'
"Hello".count("l")
2
print(cube(square(4)))
4096
String methods that create something other than a string!
sentence.split(" ") # list of words!
['Here', 'is', 'data', 'for', 'testing']
poem
'Twinkle twinkle little star\nHow I wonder what you are?\n'
print(poem)
Twinkle twinkle little star How I wonder what you are?
poem.split("\n")
['Twinkle twinkle little star', 'How I wonder what you are?', '']
poem.split(" ")
['Twinkle', 'twinkle', 'little', 'star\nHow', 'I', 'wonder', 'what', 'you', 'are?\n']
poem.split() # all white spaces (is not jst space, it is also tab also new line) as splitter
['Twinkle', 'twinkle', 'little', 'star', 'How', 'I', 'wonder', 'what', 'you', 'are?']
x = [1, 1, 1]
print(x)
[1, 1, 1]
words = sentence.split()
words
['Here', 'is', 'data', 'for', 'testing']
" ".join(words)
'Here is data for testing'
"_".join(words)
'Here_is_data_for_testing'
folders = ["","home","vikrant","training","2022","arcesium"]
path = "/".join(folders)
path
'/home/vikrant/training/2022/arcesium'
"\n" # newline
'\n'
"\t"
'\t'
"\\"
'\\'
len("\n")
1
len("\\")
1
windowspath_sep = "\\"
foldersw = ["c:","program files","python","bin"]
windowspath_sep.join(foldersw)
'c:\\program files\\python\\bin'
print(windowspath_sep.join(foldersw))
c:\program files\python\bin
python_executable_path = 'c:\\program files\\python\\bin\\python.exe'
python_executable_path.split(windowspath_sep)
['c:', 'program files', 'python', 'bin', 'python.exe']
python_executable_path.split(windowspath_sep)[-1]
'python.exe'
list methods
empty = []
empty.append(1) # there is no print! that means this method appends , but does not return
empty
[1]
empty.append(2)
empty
[1, 2]
ones = [1, 1, 1, 1]
ones.append(-1)
ones
[1, 1, 1, 1, -1]
empty
[1, 2]
empty.append(3)
empty
[1, 2, 3]
ones.extend([-1,-1,-1])
ones
[1, 1, 1, 1, -1, -1, -1, -1]
ones.count(1)
4
ones.count(-1)
4
copyones = ones[:] # with slicing
copyones
[1, 1, 1, 1, -1, -1, -1, -1]
anothercopy = ones.copy()
anothercopy
[1, 1, 1, 1, -1, -1, -1, -1]
xlist = [1, 1, 1, 1]
ylist = xlist # this does not copy..it just makes another name to same data!
copyxlist = xlist.copy()
xlist.append(2)
xlist
[1, 1, 1, 1, 2]
ylist
[1, 1, 1, 1, 2]
copyxlist
[1, 1, 1, 1]
x = 10
y = x
x = 20
ones
[1, 1, 1, 1, -1, -1, -1, -1]
ones.remove(1)
ones # remove first occurence
[1, 1, 1, -1, -1, -1, -1]
ones.clear() # clear everything
ones
[]
help(ones.clear)
Help on built-in function clear:
clear() method of builtins.list instance
Remove all items from list.
nums = [1, 2, 3, 4]
nums.pop() # this mehod changes the data as well as retuns result
# remove last item and return it
4
nums
[1, 2, 3]