Python Virtual Training For Arcesium - Module I - Day 2

Dec 07-11, 2020 Vikrant Patil

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

© Pipal Academy LLP

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

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

Functions

Functions are nothing but combining multiple statements together and giving it a name. so that all those statements can be executed at once whenever we need it.

In [3]:
text = "This is a long string with some length"
In [4]:
text[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-4-c8b5ecea273b> in <module>
----> 1 text[100]

IndexError: string index out of range
In [5]:
len(text) # here len is function name, text is argument/parameter of the function
Out[5]:
38
In [8]:
len("Vikrant") # litteral string
Out[8]:
7
In [7]:
len("Any string can work")
Out[7]:
19
In [9]:
name = "Vikrant"
In [11]:
len(name) # passing variable as argument/parameter
Out[11]:
7
In [12]:
ones = [1, 1,1, 1, ]
In [13]:
ones
Out[13]:
[1, 1, 1, 1]
In [15]:
len(ones) # length of list
Out[15]:
4
In [17]:
len([1, 2, 3, 4, 5, 1])
Out[17]:
6
In [18]:
len((0, 0, 256))
Out[18]:
3
In [19]:
person = {"name":"alice",
         "age":13,
         "email":"alice@wonder.land"}
In [20]:
len(person)
Out[20]:
3

type conversion

In [21]:
x = 10
In [22]:
type(x)
Out[22]:
int
In [23]:
y = 1.2
In [24]:
type(y)
Out[24]:
float
In [25]:
name
Out[25]:
'Vikrant'
In [26]:
type(name)
Out[26]:
str
In [27]:
type(ones)
Out[27]:
list
In [28]:
type((1, 2, 3, 4))
Out[28]:
tuple
In [29]:
type(person)
Out[29]:
dict
In [30]:
x = 10000
In [31]:
statement = "There are many people in this town, do you know how many? " + x
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-31-7467e3da0d96> in <module>
----> 1 statement = "There are many people in this town, do you know how many? " + x

TypeError: can only concatenate str (not "int") to str
In [32]:
"There are many people in this town, do you know how many? " + "10000"
Out[32]:
'There are many people in this town, do you know how many? 10000'
In [33]:
"There are many people in this town, do you know how many? " + str(x)
Out[33]:
'There are many people in this town, do you know how many? 10000'
In [37]:
str(232) # covert the data / argument into text/string
Out[37]:
'232'
In [35]:
str(1.2)
Out[35]:
'1.2'
In [36]:
str([1, 2, 2])
Out[36]:
'[1, 2, 2]'
In [39]:
int("42") # convert string into integer
Out[39]:
42
In [42]:
int("hello") # only things which can be converted into integer will work
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-42-e4c815424943> in <module>
----> 1 int("hello") # only things which can be converted into integer will work

ValueError: invalid literal for int() with base 10: 'hello'
In [43]:
float("2.3")
Out[43]:
2.3
In [44]:
float("hello")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-44-7124e8e12e61> in <module>
----> 1 float("hello")

ValueError: could not convert string to float: 'hello'
In [45]:
float("1")
Out[45]:
1.0
In [46]:
float(45)
Out[46]:
45.0

some basic numeric and usefull functions

In [47]:
max([45, 56, 67, 78, 84, 2, 4, 5])
Out[47]:
84
In [48]:
numbers = [23,56, 23, 42, 5, 1, 1]
In [49]:
max(numbers)
Out[49]:
56
In [50]:
min(numbers)
Out[50]:
1
In [51]:
sum(numbers)
Out[51]:
151
In [52]:
sum([1.2, 2, 2,3, 2.2, 1.1])
Out[52]:
11.499999999999998

len,type, str, int, float, min, max, sum these are few built-ins

In [53]:
min((1, 2, 3, 4, 5))
Out[53]:
1
In [54]:
f = 1.2 ## Floating point standard causes the precision
In [56]:
len
Out[56]:
<function len(obj, /)>
In [57]:
max
Out[57]:
<function max>
In [64]:
max = (1, 2, 3, 4)
In [59]:
max
Out[59]:
(1, 2, 3, 4)
In [65]:
max([2, 3, 4, 5])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-65-fb8f9092c964> in <module>
----> 1 max([2, 3, 4, 5])

TypeError: 'tuple' object is not callable
In [60]:
x = 10 # <----- 
x = 20
In [63]:
del max # this will delete 

When to use which bracket

Square bracket []

  • creation of a list square bracket = > [1, 2, 3, 4]
  • access of elements from list/dict/tuple/str => name[0], numbers[0], color[0], stock['name']

round bracker ()

  • creation of tuple = > (1, 2, 3, 4)
  • function call -> len(arg)

curley bracket {}

  • creation of dictionary/set
In [67]:
len([1, 2, 3, 4]) 
# len(...something) # function call , we used ()
# len( [1, 2, 3, 4] ) # argument to function is a list created using []
Out[67]:
4

Problems:

  • Use python to find total income if the person has five sources of incomes. each source giving income as 123330, 250000, 45555, 232130, 111134
  • Find out how many digits are there in 3 raise to power 42.
  • Using one of the functions that we learnt find highest income from given income sources.
  • will this work? sum(["a","b","c","d"])
In [68]:
3**42
Out[68]:
109418989131512359209
In [69]:
len(3**42)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-51de09464338> in <module>
----> 1 len(3**42)

TypeError: object of type 'int' has no len()
In [70]:
incomes = [123330, 250000, 45555, 232130, 111134]
In [71]:
total_income = sum(incomes)
In [72]:
total_income
Out[72]:
762149
In [73]:
highest_income = max(incomes)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-6a4d29d78329> in <module>
----> 1 highest_income = max(incomes)

TypeError: 'tuple' object is not callable
In [74]:
del max
In [75]:
highest_income = max(incomes)
In [76]:
highest_income
Out[76]:
250000
In [77]:
3**42
Out[77]:
109418989131512359209
In [78]:
str_num = str(3**42)
In [79]:
str_num
Out[79]:
'109418989131512359209'
In [80]:
len(str_num)
Out[80]:
21
In [81]:
"a" + "b"
Out[81]:
'ab'
In [82]:
sum(["a","b","c","d"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-82-f71d5e307bee> in <module>
----> 1 sum(["a","b","c","d"])

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [83]:
 
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-83-b1abd82ba469> in <module>
----> 1 sum(['a','b','c','d'],start=0)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [84]:
"a" + "b"
Out[84]:
'ab'
In [88]:
'0' + "a"
Out[88]:
'0a'
In [89]:
0 + "a"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-89-0023ad6f1937> in <module>
----> 1 0 + "a"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [87]:
sum([1, 2, 3])
Out[87]:
6
In [ ]:
sum([0])

List slicing

subset of lists/string can be accesseed using list slicing

items[start:end:step]

In [102]:
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [103]:
digits[2:6:2] # start 2 (inclusive) end at 6 (exlude this index) at steps of 2
Out[103]:
[2, 4]
In [93]:
digits[2:6:1]
Out[93]:
[2, 3, 4, 5]
In [94]:
digits[2:6] 
Out[94]:
[2, 3, 4, 5]
In [95]:
digits
Out[95]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [96]:
digits[0]
Out[96]:
0
In [97]:
digits[3]
Out[97]:
3
In [98]:
digits[0:4]
Out[98]:
[0, 1, 2, 3]
In [99]:
digits[0:7:2]
Out[99]:
[0, 2, 4, 6]
In [100]:
name = "vikrant"
In [101]:
name[0::2]
Out[101]:
'vkat'
In [104]:
digits
Out[104]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [105]:
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [106]:
digits[1:6]
Out[106]:
[1, 2, 3, 4, 5]
In [109]:
digitis [3:6]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-109-47ad4968311f> in <module>
----> 1 digitis [3:6]

NameError: name 'digitis' is not defined

Make note if some default values

In [111]:
digits[:] # start =0 , end => length of that list/string ... making a copy
Out[111]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [112]:
digits[3:] # start = 3, end ..till end... drop first 3
Out[112]:
[3, 4, 5, 6, 7, 8, 9]
In [113]:
digits[:3]  # start =0, end 3 .. this mean ... take first 3
Out[113]:
[0, 1, 2]
In [114]:
digits[::1]
Out[114]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [115]:
digits[::2]
Out[115]:
[0, 2, 4, 6, 8]
In [116]:
digits[::3]
Out[116]:
[0, 3, 6, 9]
In [118]:
digits[::-1] # start at end  and go till initial pos in reversed fashion, reverse the list
Out[118]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [119]:
digits[:5] # take first five
Out[119]:
[0, 1, 2, 3, 4]
In [120]:
digits[5:] # drop first five
Out[120]:
[5, 6, 7, 8, 9]
In [121]:
digits[::2] # take alternate item
Out[121]:
[0, 2, 4, 6, 8]
In [122]:
digits[::-1] # reverse the list
Out[122]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [123]:
digits[3:8:-1]
Out[123]:
[]
In [128]:
digits[::-1] # python is taking decision of making the defaults here
Out[128]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [129]:
digits[8:3:-1]
Out[129]:
[8, 7, 6, 5, 4]

More build ins

In [130]:
print("Hello World!")
Hello World!
In [131]:
name
Out[131]:
'vikrant'
In [132]:
print("Hello", name)
Hello vikrant
In [138]:
print("Hello", name,"how are you doing?") # three arguments
Hello vikrant how are you doing?
In [135]:
x, y, z = 1, 2, 3
In [136]:
print(x, y, z)
1 2 3
In [139]:
print("Hello " + name + " " + "How are you doing?") # single argument
Hello vikrant How are you doing?
In [140]:
name # is variable
Out[140]:
'vikrant'
In [141]:
"Hello" # is litteral
Out[141]:
'Hello'
In [142]:
name = "Vikant"
In [143]:
name
Out[143]:
'Vikant'
In [144]:
'name' # this is not variable.... this is a litteral with 'name'
Out[144]:
'name'
In [145]:
print(name)
Vikant
In [146]:
print('name')
name
In [147]:
print(3)
3
In [148]:
x = 5
In [151]:
print(x) # this variable
5
In [152]:
print(5) # this is litteral
5
In [153]:
5
Out[153]:
5
In [154]:
x = input("Enter value of x")
In [155]:
x
Out[155]:
'30'
In [156]:
type(x)
Out[156]:
str
In [157]:
i = input("Enter number of iterations")
In [158]:
i
Out[158]:
'[1, 2, 3, 4, 5]'
In [159]:
ints = input("Enter comma sepearted ints")
In [160]:
ints
Out[160]:
'3,4,5,6,7'
In [161]:
sorted([4, 5, 6, 2, 5,11, 2])
Out[161]:
[2, 2, 4, 5, 5, 6, 11]
In [162]:
incomes
Out[162]:
[123330, 250000, 45555, 232130, 111134]
In [168]:
sorted(incomes) # this creates a new list in sorted form, it will not change original list
Out[168]:
[45555, 111134, 123330, 232130, 250000]
In [169]:
incomes
Out[169]:
[123330, 250000, 45555, 232130, 111134]
In [170]:
sorted(incomes, reverse=True)
Out[170]:
[250000, 232130, 123330, 111134, 45555]
In [171]:
incomes
Out[171]:
[123330, 250000, 45555, 232130, 111134]

String methods

In [172]:
len([1, 2, 3])
Out[172]:
3
In [173]:
sentence = "These are few wise words"
In [175]:
sentence.startswith("These") # this will tell me whether sentence starts with "These"
Out[175]:
True
In [176]:
sentence.startswith('these')
Out[176]:
False
In [177]:
sentence.endswith('x')
Out[177]:
False
In [178]:
sentence.endswith("words")
Out[178]:
True
In [179]:
sentence.isupper()
Out[179]:
False
In [180]:
sentence.islower()
Out[180]:
False
In [181]:
"alllower".islower()
Out[181]:
True
In [182]:
help(sentence.isascii)
Help on built-in function isascii:

isascii() method of builtins.str instance
    Return True if all characters in the string are ASCII, False otherwise.
    
    ASCII characters have code points in the range U+0000-U+007F.
    Empty string is ASCII too.

In [183]:
help(sentence.center)
Help on built-in function center:

center(width, fillchar=' ', /) method of builtins.str instance
    Return a centered string of length width.
    
    Padding is done using the specified fill character (default is a space).

In [187]:
help(sentence.center)
Help on built-in function center:

center(width, fillchar=' ', /) method of builtins.str instance
    Return a centered string of length width.
    
    Padding is done using the specified fill character (default is a space).

In [188]:
sentence.istitle()
Out[188]:
False
In [190]:
help(sentence.isalpha)
Help on built-in function isalpha:

isalpha() method of builtins.str instance
    Return True if the string is an alphabetic string, False otherwise.
    
    A string is alphabetic if all characters in the string are alphabetic and there
    is at least one character in the string.

In [191]:
"a".isalpha()
Out[191]:
True
In [192]:
"a b".isalpha()
Out[192]:
False
In [194]:
sentence.isalnum()# whether the string has only alphabets and digits
Out[194]:
False
In [195]:
"user123".isalnum()
Out[195]:
True
In [196]:
sentence.capitalize()
Out[196]:
'These are few wise words'
In [197]:
"vikrant".capitalize()
Out[197]:
'Vikrant'
In [198]:
sentence.upper()
Out[198]:
'THESE ARE FEW WISE WORDS'
In [199]:
sentence.lower()
Out[199]:
'these are few wise words'
In [200]:
sentence.title()
Out[200]:
'These Are Few Wise Words'
In [201]:
len(sentence)
Out[201]:
24
In [202]:
sentence.title()
Out[202]:
'These Are Few Wise Words'
In [203]:
title()
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-203-0df94ee1f940> in <module>
----> 1 title()

NameError: name 'title' is not defined
In [204]:
sentence.title()
Out[204]:
'These Are Few Wise Words'
In [205]:
len
Out[205]:
<function len(obj, /)>
In [207]:
len(sentence)
Out[207]:
24
In [208]:
len([1, 2, 3, 4])
Out[208]:
4
In [209]:
len({'x':1})
Out[209]:
1
In [210]:
sentence.title()
Out[210]:
'These Are Few Wise Words'
In [211]:
"vikrant".title()
Out[211]:
'Vikrant'
In [212]:
sentence
Out[212]:
'These are few wise words'
In [213]:
"vikrant"
Out[213]:
'vikrant'
In [214]:
x = 10
In [215]:
y = 10
In [216]:
x
Out[216]:
10
In [217]:
y
Out[217]:
10
In [218]:
id(x) 
Out[218]:
94324436541024
In [219]:
id(y)
Out[219]:
94324436541024
In [221]:
x
Out[221]:
10
In [222]:
x = [1, 2, 3]
In [223]:
y = [1, 2, 3]
In [224]:
"hello"
Out[224]:
'hello'
In [225]:
x
Out[225]:
[1, 2, 3]
In [226]:
y
Out[226]:
[1, 2, 3]
In [227]:
x.append(1)
In [228]:
x
Out[228]:
[1, 2, 3, 1]
In [229]:
y.append(2)
In [230]:
y
Out[230]:
[1, 2, 3, 2]
In [231]:
x
Out[231]:
[1, 2, 3, 1]

methods vs functions

function(arg, arg1)

object.method(args)-> might return result or might change object
In [232]:
sentence
Out[232]:
'These are few wise words'
In [233]:
sentence.split() # splits the string into multiple strings using empty spaces
Out[233]:
['These', 'are', 'few', 'wise', 'words']
In [234]:
words = sentence.split()
In [235]:
words
Out[235]:
['These', 'are', 'few', 'wise', 'words']
In [236]:
words[-1]
Out[236]:
'words'
In [237]:
words[2]
Out[237]:
'few'
In [238]:
ints = input("Enter comma separated ints")
In [239]:
ints
Out[239]:
'1,2,3,4'
In [240]:
ints.split(",")
Out[240]:
['1', '2', '3', '4']
In [241]:
'[1,2,3,4]'
Out[241]:
'[1,2,3,4]'
In [242]:
words
Out[242]:
['These', 'are', 'few', 'wise', 'words']
In [243]:
" ".join(words)
Out[243]:
'These are few wise words'
In [244]:
",".join(words)
Out[244]:
'These,are,few,wise,words'
In [245]:
"_".join(words)
Out[245]:
'These_are_few_wise_words'

Problems:

  • A sentence has hyphen between every two word.
text = "Yet-another-sentence-with-nothing-in-it'

How can you transform it such that there will be space beween two words.

  • A path separator for windows os is
    sep = "\\" escapce char
    Thers is list of folders from C:
folders = ["C:", "Program Files", "python3.9"]

can you make a string for complete path to python installation folder? "c:\Program Files\python3.9"

  • On unix system a path of file is given
path = "/home/vikrant/training/module-day1.ipynb"

can you find out only filename?

  • Can you find out extension of a file given in variable filename
    filename = "hello.xlsx"
In [ ]: