Python Virtual Training For Arcesium - Module I - Day 1

Aug 10-14, 2020 Vikrant Patil

These notes are available online at http://notes.pipal.in/2020/arcesium_finop_batch1_module1/day1.html

© Pipal Academy LLP

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

We will be using jupyter hub from http://lab1.pipal.in for this training.

Introduction to programming

multiply two and five and write down result in your notebook

How to work with this jupyter notebook

Esc + M -> converts the cell into markdown
Esc + y -> convertes the cell back to code cell
Shift + enter - > execute the current cell

Try this out!

### Header3 
## Header2
# Header1

If you type this in markdown cell you should see similar to this

Header3

Header2

Header1

In [2]:
42 * 42
Out[2]:
1764

Numeric And Text data

Very primitive way of looking at Programming is manipulating numbers and text. To do this python has got some primitives, which we will explore now

In [3]:
42 + 42
Out[3]:
84
In [4]:
42 -42
Out[4]:
0
In [5]:
42*2
Out[5]:
84
In [6]:
5 /2
Out[6]:
2.5
In [7]:
5 // 2
Out[7]:
2
In [9]:
2 ** 5 # 2 raised to 5
Out[9]:
32
In [10]:
5 % 2 # remainder when divided by 2
Out[10]:
1

Python has two types of numeric data, integers and real numbers. real numbers are represented by float in python

In [12]:
1.1 + 1.1
Out[12]:
2.2
In [14]:
1.0 - 0.1
Out[14]:
0.9
In [15]:
1.8 *2.0
Out[15]:
3.6
In [16]:
5.0 / 2
Out[16]:
2.5
In [17]:
5.0 // 2.0
Out[17]:
2.0
In [18]:
2.0 ** 5
Out[18]:
32.0

These symbols +, -, *, **, /, // are called operators. When there are multiple operators in same statement , there a priority to which one will be executed first

In [19]:
2 + 4*5
Out[19]:
22
operator    priority

  **         1
% // / *     2
+ -          3

For example have alook at complicated arithmatic expression in python

2 ** 5%5/2*7
32%5/2*7
2/2*7
1*7
7

Round braces help us to modify the precedence of execution.

In [20]:
(7+2)*3
Out[20]:
27
In [21]:
7+2*3
Out[21]:
13

Now have a look at text data in python. Anything between two " or ' is called at string. And it is text data representation in python

In [22]:
"Hello this is text"
Out[22]:
'Hello this is text'
In [27]:
'hello this is text'
Out[27]:
'hello this is text'

Question Does division operator return integer when integer divided integer?

No, It returns float always.

In [24]:
2/2
Out[24]:
1.0
In [25]:
4/4
Out[25]:
1.0
In [26]:
2**5
Out[26]:
32

Python supports multiline text too. As we will see later python supports writing human friendly code writing! ANything that starts with triple quotes " or ' and ends with triple quote is multiline string.

In [28]:
"""This is first line of my poem
This is second line
And this is the last one"""
Out[28]:
'This is first line of my poem\nThis is second line\nAnd this is the last one'
In [29]:
'''This is another text
Which has got multiple line
yet another line'''
Out[29]:
'This is another text\nWhich has got multiple line\nyet another line'

This character \n is called as new line character. There are ohter characters too which are special like new line. They are represented by escape sequence.

escape char     meaning

\n              new line
\t              tab
\\              \

Strings work with some operators as well

In [30]:
"*"
Out[30]:
'*'
In [31]:
"*"*5
Out[31]:
'*****'
In [32]:
"hello" + "world!"
Out[32]:
'helloworld!'

Problem

Use python to convert asset value, 20345.5 , originally in EUR to INR

Problem

Compound interest is calculated using formula P(1+r/n)^nt , P is principle amount, r is nominal rate of interest per year. n is the number of times in a year the interest is compounded and t denotes number of years. Use python compound interest for principle amount of 26780, rate of interest 7%, interst is compunded quarterly, and amount is invested for 5 years.

In [33]:
88.35*20345.5
Out[33]:
1797524.9249999998
In [34]:
26780*(1+0.07/4)**(4*5)
Out[34]:
37887.76008234032

Variables and literals

As of now we saw arithmatic operators , now let's have a look at an operator called as assignment operator =. It works like this. Suppose you write a statement which involves assignment operator

In [35]:
x = 2 + 3

The stetement on right hand side is computed first, the result is stored in python's memory. Then there is something called as namespace, in this namespace a new name x is created. and then this name is linked to the memory loction that we already have for the result.

In [36]:
x
Out[36]:
5
In [37]:
x
Out[37]:
5

Question

How do you delete x? can we delete 5 stored on x?

you can delete x using statement del x , this will delete only name x form namespace. it will not delete 5. When to delete 5 is decide by python, user can not control.

In [38]:
del x
In [39]:
x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-39-6fcf9dfbd479> in <module>
----> 1 x

NameError: name 'x' is not defined
In [40]:
10
Out[40]:
10
In [42]:
5 # literal
Out[42]:
5
In [43]:
x = 5
In [45]:
x # variable
Out[45]:
5

Be careful with string literals

In [46]:
vikrant = 10
In [47]:
"vikrant"  # this is literal and not a variable
Out[47]:
'vikrant'
In [48]:
"vikrant"
Out[48]:
'vikrant'
In [49]:
vikrant
Out[49]:
10
In [50]:
python training = 10
  File "<ipython-input-50-2d1d4c35e692>", line 1
    python training = 10
           ^
SyntaxError: invalid syntax

What are the rules by which variable name can be denifed?

  • The variable name can not have space in it, it has to be a single word
  • it can not start with a number
  • It can have aplahabets (A-Z, a-z) and numbers(0-9) and underscore (_) in it
In [51]:
2x = 3
  File "<ipython-input-51-5273a0c645fb>", line 1
    2x = 3
     ^
SyntaxError: invalid syntax
In [52]:
x2 = 3
In [53]:
square of two = 2*2
  File "<ipython-input-53-8889ce8da7d7>", line 1
    square of two = 2*2
           ^
SyntaxError: invalid syntax
In [54]:
square_of_two = 2*2
In [56]:
square_of_two
Out[56]:
4
In [57]:
a = 10
In [58]:
a, b = 10, 20
In [59]:
a
Out[59]:
10
In [60]:
b
Out[60]:
20

problem

Have a look at following statements.

    x = 10
    y = x
    x = x+ 10

What will be values y after this?

problem

Have a look at following statements.

    x = 10
    y = x
    y = 25

What will be values x after this?

Let's do more with strings

In [62]:
s = "Hello"
In [63]:
s[0]
Out[63]:
'H'
In [64]:
s[1]
Out[64]:
'e'
In [65]:
s[3]
Out[65]:
'l'
In [66]:
s[4]
Out[66]:
'o'
In [67]:
s[5]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-67-b5dece75d686> in <module>
----> 1 s[5]

IndexError: string index out of range
In [68]:
s[-1]
Out[68]:
'o'
   p  y   t   h   o   n
-> 0  1   2   3   4   5
  -6  -5  -4  -3 -2   -1   <-----

Collections

Other than basic data types we freequently need some data which need puting basic data in a sequence. Lists and tuples are such highe level datatypes which allows us to put items in a sequence.

In [69]:
[1, 1, 1]
Out[69]:
[1, 1, 1]
In [70]:
numbers = [1, 2, 3, 4]
In [71]:
words = ["one", "two", "three", "four"]
In [72]:
mixed = [1, "one", 2, "two", 3, "three", 4, "four"]
In [73]:
numbers[0]
Out[73]:
1
In [74]:
numbers[-1]
Out[74]:
4
In [75]:
numbers[3]
Out[75]:
4
In [76]:
mixed[-1]
Out[76]:
'four'
In [77]:
list_inside_list = [[1, 2, 1], ["one", "two", "three"]]
In [78]:
list_inside_list[0]
Out[78]:
[1, 2, 1]
In [79]:
list_inside_list[0][-1]
Out[79]:
1
In [80]:
words
Out[80]:
['one', 'two', 'three', 'four']
In [81]:
words[0] = "zero"
In [82]:
words
Out[82]:
['zero', 'two', 'three', 'four']
In [83]:
words[-1] = "last"
In [84]:
words
Out[84]:
['zero', 'two', 'three', 'last']

Just like strings lists can also work with some basic operators

In [85]:
words + words
Out[85]:
['zero', 'two', 'three', 'last', 'zero', 'two', 'three', 'last']
In [86]:
words + numbers
Out[86]:
['zero', 'two', 'three', 'last', 1, 2, 3, 4]
In [87]:
[0]*5
Out[87]:
[0, 0, 0, 0, 0]

Sibling of list is tuple. Very similar to lists, but can not be modified once created.

In [88]:
color = (0, 0, 1)
In [89]:
color[0]
Out[89]:
0
In [90]:
color[-1]
Out[90]:
1
In [91]:
color[0] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-91-5e3a77194efb> in <module>
----> 1 color[0] = 1

TypeError: 'tuple' object does not support item assignment
In [92]:
color + color
Out[92]:
(0, 0, 1, 0, 0, 1)
In [93]:
color * 3
Out[93]:
(0, 0, 1, 0, 0, 1, 0, 0, 1)

Lists and tuples allows us to save data by index. Dictionary is another higher level data type which allows us to save items by name.

In [94]:
scorebynames = {"rupali":20, "alice":19, "Elsa":18, "kavita":20}
In [95]:
scorebynames[0]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-95-4c6750235d1e> in <module>
----> 1 scorebynames[0]

KeyError: 0
In [96]:
scorebynames['alice']
Out[96]:
19
In [97]:
scorebynames["Elsa"]
Out[97]:
18
In [98]:
scorebynames['seema']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-98-b4b51d59e249> in <module>
----> 1 scorebynames['seema']

KeyError: 'seema'
In [99]:
scorebynames['seema'] = 20
In [100]:
scorebynames
Out[100]:
{'rupali': 20, 'alice': 19, 'Elsa': 18, 'kavita': 20, 'seema': 20}
In [101]:
stock = {"name":"IBM", "open":123, "high":126, "low":120, "close":123.5}
In [102]:
stock['name']
Out[102]:
'IBM'
In [103]:
stock['open']
Out[103]:
123
In [104]:
stock['close']
Out[104]:
123.5

Boolean

In [105]:
True
Out[105]:
True
In [106]:
False
Out[106]:
False

Functions

Functions are abstraction to combine multiple staements together and save it for later use.

In [107]:
name = "Rupali"
In [108]:
len(name)
Out[108]:
6
In [109]:
len(name)
Out[109]:
6
In [110]:
len(stock)
Out[110]:
5
In [111]:
stock
Out[111]:
{'name': 'IBM', 'open': 123, 'high': 126, 'low': 120, 'close': 123.5}
In [112]:
point = (0 , 0, 0)
In [113]:
len(point)
Out[113]:
3
In [114]:
len(numbers)
Out[114]:
4
In [115]:
numbers
Out[115]:
[1, 2, 3, 4]

len can be used to find number items in any collections including string(number of characters)

types and converting

In [116]:
name
Out[116]:
'Rupali'
In [117]:
type(name)
Out[117]:
str
In [118]:
type(numbers)
Out[118]:
list
In [119]:
type(point)
Out[119]:
tuple
In [120]:
type(stock)
Out[120]:
dict
In [121]:
type(1)
Out[121]:
int
In [122]:
type(1.2)
Out[122]:
float

Lets try to convert string to numbers and the other way

In [123]:
str(42)
Out[123]:
'42'
In [124]:
int('  23')
Out[124]:
23
In [125]:
int('42')
Out[125]:
42
In [126]:
float("23.4")
Out[126]:
23.4

max function allows us to find maximum number from a list/tuple

In [127]:
max([2, 1, 3, 1, 45, 24, 23])
Out[127]:
45
In [128]:
min([2, 1, 3, 1, 45, 24, 23])
Out[128]:
1
In [130]:
sum([2, 1, 3, 1, 45, 24, 23])
Out[130]:
99

Question

What if list contains strings/words? what will max return?

It will return last item if items are arranged in ASCII order (similar to dictionary but slightly different )

In [133]:
words = ["B", "b","A", "a",  "C", "c"]
max(words)
Out[133]:
'c'
In [134]:
min(words)
Out[134]:
'A'

problem

Use python to find total income of a person whic has five income sources giving income of 123330, 250000, 45555, 232130, 11123

problem

Find out how many digits are there in 2**42

problem

Using python functions find out highest income source in above example.

problem

Will this work?

    sum(["a","b","c","d"])
In [135]:
sum([1, 2, 3, 4])
Out[135]:
10
In [137]:
sum(["a","b","c","d"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-137-f71d5e307bee> in <module>
----> 1 sum(["a","b","c","d"])

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [138]:
sum?
Signature: sum(iterable, /, start=0)
Docstring:
Return the sum of a 'start' value (default: 0) plus an iterable of numbers

When the iterable is empty, return the start value.
This function is intended specifically for use with numeric values and may
reject non-numeric types.
Type:      builtin_function_or_method
In [139]:
sum([1, 1, 1, 1], 5)
Out[139]:
9
In [141]:
sum(["a","b","c","d"], start="")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-141-4ac4a0a49432> in <module>
----> 1 sum(["a","b","c","d"], start="")

TypeError: sum() can't sum strings [use ''.join(seq) instead]
In [143]:
^
  File "<ipython-input-143-8dc0322a0a7a>", line 1
    ^
    ^
SyntaxError: invalid syntax
In [144]:
incomes = [123330, 250000, 45555, 232130, 11123]
In [145]:
total_income = sum(incomes)
In [146]:
total_income
Out[146]:
662138
In [147]:
max_income = max(incomes)
In [148]:
max_income
Out[148]:
250000
In [149]:
2**42
Out[149]:
4398046511104
In [151]:
len(2) # len works only on collections!
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-151-9088f8f40ebb> in <module>
----> 1 len(2) # len works only on collections!

TypeError: object of type 'int' has no len()
In [152]:
strvalue = str(2**42)
In [153]:
len(strvalue)
Out[153]:
13
len(str(2**42))
len(str(4398046511104)
len('4398046511104')
13

List slicing

Form a list I would like to find some items, with rule.

lst[start:end:step]

In [155]:
digits = [0 , 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [156]:
digits[2:8:2] #start at 2 end at 8 (exluded) with step of 2
Out[156]:
[2, 4, 6]
In [157]:
digits[2:8:3]
Out[157]:
[2, 5]

If any of the parameter in slicing rule is not given , then default is taken.

  • if step is not given , then default step of 1 is taken
  • if end is not given , default is taken as end of list
  • if start is not given, it is taken as 0
In [158]:
digits[2:6] # be default step is taken as 1
Out[158]:
[2, 3, 4, 5]
In [159]:
digits[2:] # defualt end is taken as end of list
Out[159]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [161]:
digits[:5] # start is not given , zero is taken as start
Out[161]:
[0, 1, 2, 3, 4]
In [162]:
digits[:4] ## take first 4 items
Out[162]:
[0, 1, 2, 3]
In [163]:
digits[3:] ## drop first 3 items
Out[163]:
[3, 4, 5, 6, 7, 8, 9]
In [164]:
digits[::] # copy the list
Out[164]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [165]:
digits[::-1] ## reverse
Out[165]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

More built ins

In [166]:
print("Hello World")
Hello World
In [167]:
name = "Rahul"
In [172]:
name
Out[172]:
'Rahul'
In [173]:
print(name)
Rahul
In [174]:
print("hello", name, "How are you doing?" )
hello Rahul How are you doing?
In [175]:
x = input("Give value of x:")
In [176]:
print(x)
5
In [185]:
sorted([3, 2, 1, 4, 1, 1])
Out[185]:
[1, 1, 1, 2, 3, 4]
In [178]:
print("hello"+"world")
helloworld
In [179]:
print("hello", "world", sep="")
helloworld
In [180]:
print("hello", "world", sep="-")
hello-world
In [181]:
print("hello", name, "How are you doing?", sep="-")
hello-Rahul-How are you doing?
In [182]:
x = input()
In [184]:
type(x)
Out[184]:
str
In [186]:
nums = [3, 2, 1, 4, 1, 1]
sorted(nums)
Out[186]:
[1, 1, 1, 2, 3, 4]
In [187]:
nums
Out[187]:
[3, 2, 1, 4, 1, 1]
In [188]:
sorted(nums, reverse=True)
Out[188]:
[4, 3, 2, 1, 1, 1]
In [189]:
print("hello", "world", "-")
hello world -
In [190]:
print("hello", "world", sep = "-")
hello-world
In [191]:
sorted(nums, True)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-191-762eb70eb178> in <module>
----> 1 sorted(nums, True)

TypeError: sorted expected 1 argument, got 2
In [192]:
sorted(nums, reverse=True)
Out[192]:
[4, 3, 2, 1, 1, 1]
In [ ]: