Python Virtual Training For Arcesium - Module I - Day 2

Aug 17-21, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch2/module1-day2.html

© Pipal Academy LLP

Day 1 | Day 2 | Day 3 | Day 4 | Day 5

We will be using jupyter hub from http://lab2.pipal.in for this training. Use notebook with name module1-day2.ipynb for today's session.

In [ ]:
 

More built in functions

max, min, sum, len, int, str, float, type

In [1]:
print("Hello World!")
Hello World!
In [2]:
print("one", "two", "as", "many", "parameter")
one two as many parameter
In [3]:
print("one", "two", "as", "many", "parameter", sep="-")
one-two-as-many-parameter

opposite of printing output is getting some input from user

In [4]:
x = input("Enter value of x")
In [5]:
print(x)
35
In [6]:
type(x)
Out[6]:
str
In [7]:
x
Out[7]:
'35'

input is built in function which takes text input from user.

In [8]:
x = int(input("Enter integer value for x"))
In [9]:
x
Out[9]:
42
In [10]:
int(x)
Out[10]:
42
In [11]:
sorted([3, 2, 4, 1, 3, 4])
Out[11]:
[1, 2, 3, 3, 4, 4]
In [12]:
numbers = [76, 3, 5, 2, 4, 1,3, 5]
In [13]:
sorted(numbers)
Out[13]:
[1, 2, 3, 3, 4, 5, 5, 76]
In [14]:
sorted(numbers, reverse=True)
Out[14]:
[76, 5, 5, 4, 3, 3, 2, 1]
In [15]:
sorted?
Signature: sorted(iterable, /, *, key=None, reverse=False)
Docstring:
Return a new list containing all items from the iterable in ascending order.

A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
Type:      builtin_function_or_method

Methods

In [16]:
sum([1, 2, 3, 4])
Out[16]:
10
In [17]:
sentence = "These Are Some Wise Words"
In [18]:
sentence.startswith("This")
Out[18]:
False
In [19]:
sentence.startswith("These")
Out[19]:
True
In [20]:
startwith() # it can not be called like this
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-20-71ed7be131ae> in <module>
----> 1 startwith() # it can not be called like this

NameError: name 'startwith' is not defined

checking methods

In [22]:
sentence.endswith("words") # case sensitive
Out[22]:
False
In [23]:
sentence.endswith("Words")
Out[23]:
True
In [26]:
sentence.isupper() # all char upper case of not
Out[26]:
False
In [27]:
sentence.islower() # all chars lower case or not
Out[27]:
False
In [28]:
sentence.istitle() ## only first letter of every word is capital?
Out[28]:
True
In [30]:
sentence.isalpha() ## whether it has only alphabets. space is not counted in alphabets
Out[30]:
False
In [31]:
"ksajhdsadfds".isalpha()
Out[31]:
True
In [33]:
sentence.isalnum()# alphabets and numbers
Out[33]:
False
In [34]:
"user123".isalnum()
Out[34]:
True

Transformation

In [35]:
"hello".capitalize()
Out[35]:
'Hello'
In [36]:
sentence.upper()
Out[36]:
'THESE ARE SOME WISE WORDS'
In [37]:
sentence.lower()
Out[37]:
'these are some wise words'
In [38]:
"hello world".title()
Out[38]:
'Hello World'
In [39]:
sentence.rjust(50)
Out[39]:
'                         These Are Some Wise Words'
In [40]:
sentence.ljust(50)
Out[40]:
'These Are Some Wise Words                         '
In [41]:
sentence.center(50)
Out[41]:
'            These Are Some Wise Words             '
In [42]:
sentence.replace("Wise", "Foolish")
Out[42]:
'These Are Some Foolish Words'
In [43]:
sentence
Out[43]:
'These Are Some Wise Words'
In [44]:
sentence[0] = "h"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-44-1accc784baa4> in <module>
----> 1 sentence[0] = "h"

TypeError: 'str' object does not support item assignment

These transofrmation methods will be used widely

In [46]:
sentence.split() # without parameters, it splits on whitespace
Out[46]:
['These', 'Are', 'Some', 'Wise', 'Words']
In [47]:
multiline = """line1
line2
line3"""
In [48]:
multiline.split()
Out[48]:
['line1', 'line2', 'line3']
In [52]:
poem = """Twinkle twinkle little star
how I wonder 
what you are
"""
In [53]:
poem.split()
Out[53]:
['Twinkle',
 'twinkle',
 'little',
 'star',
 'how',
 'I',
 'wonder',
 'what',
 'you',
 'are']
In [54]:
poem
Out[54]:
'Twinkle twinkle little star\nhow I wonder \nwhat you are\n'
In [55]:
poem.split("\n")
Out[55]:
['Twinkle twinkle little star', 'how I wonder ', 'what you are', '']
In [56]:
sentence.split()
Out[56]:
['These', 'Are', 'Some', 'Wise', 'Words']
In [57]:
words = sentence.split()
In [58]:
words
Out[58]:
['These', 'Are', 'Some', 'Wise', 'Words']
In [59]:
"-".join(words)
Out[59]:
'These-Are-Some-Wise-Words'
In [60]:
"_".join(words)
Out[60]:
'These_Are_Some_Wise_Words'
In [61]:
",".join(words)
Out[61]:
'These,Are,Some,Wise,Words'
In [62]:
",".join([1, 2, 3, 45])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-62-7ab978ff2170> in <module>
----> 1 ",".join([1, 2, 3, 45])

TypeError: sequence item 0: expected str instance, int found
In [63]:
",".join(["1", "2", "3", "45"])
Out[63]:
'1,2,3,45'
In [64]:
poem = """Twinkle twinkle little star
how I wonder 
what you are
"""
In [67]:
sentence1 = "He said"
sentence2 = "'I am fine'"
In [68]:
print(sentence2)
'I am fine'
In [69]:
print(sentence1)
He said
In [70]:
",".join([sentence1, sentence2])
Out[70]:
"He said,'I am fine'"
In [71]:
print(",".join([sentence1, sentence2]))
He said,'I am fine'
In [72]:
multiline = """this is first
and sencond
and this one is last"""
In [73]:
multiline.split("\n")
Out[73]:
['this is first', 'and sencond', 'and this one is last']
In [75]:
lines = multiline.split("\n")
In [76]:
lines
Out[76]:
['this is first', 'and sencond', 'and this one is last']
In [77]:
print("\n".join(lines))
this is first
and sencond
and this one is last
In [78]:
print("\n".join([sentence1, sentence2]))
He said
'I am fine'
In [80]:
poem.split("\n")
Out[80]:
['Twinkle twinkle little star', 'how I wonder ', 'what you are', '']
In [81]:
poem
Out[81]:
'Twinkle twinkle little star\nhow I wonder \nwhat you are\n'
In [82]:
poem.rstrip()
Out[82]:
'Twinkle twinkle little star\nhow I wonder \nwhat you are'
In [83]:
poem.rstrip().split("\n")
Out[83]:
['Twinkle twinkle little star', 'how I wonder ', 'what you are']
In [84]:
"     hello this has trailing spaced on left".lstrip()
Out[84]:
'hello this has trailing spaced on left'
In [85]:
"     hello this has triling spces on both sides      ".rstrip()
Out[85]:
'     hello this has triling spces on both sides'
In [86]:
"     hello this has triling spces on both sides      ".strip()
Out[86]:
'hello this has triling spces on both sides'

Method chaining

sentence = "   helo method chianing!    "
sentence.strip().split()[-1]
---------->-------->------> methods will be executed in this order
In [90]:
sentence = "These Are Some Wise Words"
In [91]:
"Wise" in sentence
Out[91]:
True
In [92]:
"Wise" not in sentence
Out[92]:
False
In [93]:
sentence
Out[93]:
'These Are Some Wise Words'
In [94]:
sentence.replace?
Signature: sentence.replace(old, new, count=-1, /)
Docstring:
Return a copy with all occurrences of substring old replaced by new.

  count
    Maximum number of occurrences to replace.
    -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are
replaced.
Type:      builtin_function_or_method
In [97]:
# help(str) show documentaion for str
In [98]:
help(sentence.replace)
Help on built-in function replace:

replace(old, new, count=-1, /) method of builtins.str instance
    Return a copy with all occurrences of substring old replaced by new.
    
      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.
    
    If the optional argument count is given, only the first count occurrences are
    replaced.

Problems

  1. On a website , login name is legal only if it is alphanumeric. A string is stored in a variable username. How will you check if username is as per rules?
  2. sentence has hyphen bewteen every two words.
    >>> sentence = "Yet-another-sentence-with-nothing-in-it"
    How can you transform this sentence such that there will be space between ever two words.
  3. A path seperator for windows opearting system is
     >>> sep = "\\"
    Folder names starting from c: drive till the folder containing executable 'python.exe' are given in a list.
     >>> folders = ["C:", "Program Files", "python3.8"]
    How will you make complete string fro complete path of python.exe?
  4. A path to file is given on a linux system. On linux system path seperator is "/"
     >>> path = "/home/vikrant/training/day1.html"
    How will you find only name of file from given path?
  5. Using string methods can you find extension of a file if filename is stored in a variable filename = "hello.xlsx"

solution 1

In [99]:
username = "vikrant231"
In [100]:
username.isalnum()
Out[100]:
True
In [101]:
username = "vikrant patil"
In [102]:
username.isalnum()
Out[102]:
False
In [103]:
"2323".isalnum()
Out[103]:
True
In [104]:
"2323 3434".isalnum()
Out[104]:
False

solution 2

In [105]:
sentence = "Yet-another-sentence-with-nothing-in-it"
In [106]:
sentence.replace("-"," ")
Out[106]:
'Yet another sentence with nothing in it'
In [107]:
sentence.split("-")
Out[107]:
['Yet', 'another', 'sentence', 'with', 'nothing', 'in', 'it']
In [108]:
" ".join(sentence.split("-"))
Out[108]:
'Yet another sentence with nothing in it'

solution 3

In [109]:
folders = ["C:", "Program Files", "python3.8"]
In [110]:
exe = "python.exe"
In [111]:
path = "\\".join(folders + [exe])
In [112]:
path
Out[112]:
'C:\\Program Files\\python3.8\\python.exe'
In [113]:
folders
Out[113]:
['C:', 'Program Files', 'python3.8']
In [114]:
folders + exe
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-114-5ca956a43bca> in <module>
----> 1 folders + exe

TypeError: can only concatenate list (not "str") to list
In [115]:
folders + [exe]
Out[115]:
['C:', 'Program Files', 'python3.8', 'python.exe']
In [116]:
"\\".join(folders + [exe])
Out[116]:
'C:\\Program Files\\python3.8\\python.exe'

solution 4

In [117]:
path = "/home/vikrant/training/day1.html"
In [118]:
path.split("/")
Out[118]:
['', 'home', 'vikrant', 'training', 'day1.html']
In [119]:
path.split("/")[-1]
Out[119]:
'day1.html'

solution 5

In [120]:
filename = "hello.xlsx" # week1.day1.xlsx
In [121]:
filename.split(".")
Out[121]:
['hello', 'xlsx']
In [122]:
filename.split(".")[-1]
Out[122]:
'xlsx'

List methods

to find items

In [123]:
nums = [1, 2, 3, 4]
In [124]:
nums.index(3)
Out[124]:
2
In [125]:
nums.index(2)
Out[125]:
1
In [126]:
nums = [1, 1, 3, 2, 3, 4, 2, 1, 2, 3, 3]
In [127]:
nums.index(3)
Out[127]:
2
In [128]:
nums.count(3)
Out[128]:
4
In [129]:
nums.count(1)
Out[129]:
3

methods to add items to list

In [130]:
empty = []
In [131]:
empty.append(1)
In [132]:
empty
Out[132]:
[1]
In [133]:
empty.append(0)
In [134]:
empty
Out[134]:
[1, 0]
In [135]:
empty.append(1)
In [136]:
empty
Out[136]:
[1, 0, 1]
In [137]:
empty.append(1)
In [138]:
empty
Out[138]:
[1, 0, 1, 1]
In [139]:
empty.insert(0, 23) # insert 23 at location 0
In [140]:
empty
Out[140]:
[23, 1, 0, 1, 1]
In [143]:
empty.extend([0, 0, 0]) # this will add all items at end
In [142]:
empty
Out[142]:
[23, 1, 0, 1, 1, 0, 0, 0]

Method to remove

In [144]:
nums = [ 1, 2, 3]
In [145]:
nums.remove(2)
In [146]:
nums
Out[146]:
[1, 3]
In [148]:
nums.pop() # remove last item
Out[148]:
3
In [149]:
nums
Out[149]:
[1]
In [150]:
digits = [0, 1, 2, 3, 4, 5, 6]
In [151]:
digits.pop(2) # remove item at location 2
Out[151]:
2
In [152]:
digits
Out[152]:
[0, 1, 3, 4, 5, 6]
In [153]:
digits.clear() # remove all
In [154]:
digits
Out[154]:
[]
In [155]:
chars = ["a","b","c","a","a","b"]
In [156]:
chars
Out[156]:
['a', 'b', 'c', 'a', 'a', 'b']
In [157]:
chars.pop(2)
Out[157]:
'c'
In [159]:
chars
Out[159]:
['a', 'b', 'a', 'a', 'b']
In [160]:
chars.index('a')
Out[160]:
0
In [161]:
chars.pop(0)
Out[161]:
'a'
In [162]:
chars.index('a')
Out[162]:
1
In [163]:
chars.pop(1)
Out[163]:
'a'
In [164]:
chars.index('a')
Out[164]:
1
In [165]:
chars.pop(1)
Out[165]:
'a'
In [166]:
chars
Out[166]:
['b', 'b']

some other manipulations

In [167]:
nums = [3, 2, 4, 1]
In [168]:
nums.sort() # sort in place
In [169]:
nums
Out[169]:
[1, 2, 3, 4]
In [170]:
nums.reverse() # reverse in place
In [171]:
nums
Out[171]:
[4, 3, 2, 1]
In [173]:
nums.copy() # this is same as nums[::]
Out[173]:
[4, 3, 2, 1]
In [175]:
x = [23 ,23, 2, 424]
In [176]:
sorted(x)
Out[176]:
[2, 23, 23, 424]
In [177]:
x
Out[177]:
[23, 23, 2, 424]
In [178]:
x.sort()
In [179]:
x
Out[179]:
[2, 23, 23, 424]
In [180]:
x.append?
Signature: x.append(object, /)
Docstring: Append object to the end of the list.
Type:      builtin_function_or_method
In [181]:
x.append([1, 2, 3])
In [182]:
x
Out[182]:
[2, 23, 23, 424, [1, 2, 3]]
In [183]:
x.pop()
Out[183]:
[1, 2, 3]
In [184]:
x
Out[184]:
[2, 23, 23, 424]
In [185]:
x.extend([1, 2, 3])
In [186]:
x
Out[186]:
[2, 23, 23, 424, 1, 2, 3]
In [187]:
x
Out[187]:
[2, 23, 23, 424, 1, 2, 3]
In [188]:
y = x
In [189]:
x.append(0)
In [190]:
y
Out[190]:
[2, 23, 23, 424, 1, 2, 3, 0]
In [191]:
x
Out[191]:
[2, 23, 23, 424, 1, 2, 3, 0]
In [192]:
z = x.copy()
In [193]:
x
Out[193]:
[2, 23, 23, 424, 1, 2, 3, 0]
In [194]:
z
Out[194]:
[2, 23, 23, 424, 1, 2, 3, 0]
In [195]:
x.append(-1)
In [196]:
z
Out[196]:
[2, 23, 23, 424, 1, 2, 3, 0]
In [197]:
x
Out[197]:
[2, 23, 23, 424, 1, 2, 3, 0, -1]

Creating custom functions

                 +---------------+
                 |               |
    inputs ->----|   square      |--------> output
                 |               |
                 +---------------+
In [198]:
def square(x):
    sqrx = x**2
    return sqrx
In [199]:
square
Out[199]:
<function __main__.square(x)>
In [200]:
square(5)
Out[200]:
25
In [204]:
def sumofsquares(a, b): # function defination starts with def, has to end with :
    a2 = square(a) # next line has to be indented 4 spaces by convention
    b2 = square(b) # all lines in this code block has to indented at same level
    return a2 +b2  # finally return statement

    sumofsquares(3,4) # this statement is also inside function
In [206]:
def sumofsquares(a, b): # function defination starts with def, has to end with :
    a2 = square(a) # next line has to be indented 4 spaces by convention
    b2 = square(b) # all lines in this code block has to indented at same level
    return a2 +b2  # finally return statement

sumofsquares(3,4)  # this is outside function
Out[206]:
25

A function must have atlest one line in it

In [209]:
def donothing():
    pass # empty statement
In [210]:
donothing()

A function can be written without return statement

In [213]:
def say_hello(name):
    print("Hello", name + "!")
In [212]:
say_hello("python")
Hello python!
In [214]:
y = square(5)
In [216]:
y
Out[216]:
25
In [217]:
square(4)
16
Out[217]:
16
In [218]:
x = 10
y = 20
x+y
x*y
x**y
Out[218]:
100000000000000000000
In [219]:
square(4)
Out[219]:
16
In [220]:
square(5)
square(3)
sumofsquares(3, 4)
10
Out[220]:
10