Basic Python Training at Arcesium - Day 1

Nov 26-30, 2018 Vikrant Patil

These notes are available online at http://notes.pipal.in/2018/arcesium-basic-nov/day1.html

© Pipal Academy LLP

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

We will be using python 3 (>= 3.0) from anaconda for this training. You can download it from

https://www.anaconda.com/download/

Header1

Header2

Header3

  • task1
  • task2
  • task3
In [1]:
2 + 3
Out[1]:
5
In [2]:
200000 * 20023232323
Out[2]:
4004646464600000
In [3]:
print("Hello World!")
Hello World!

Basic Data types

There are integers

In [4]:
2 + 3
Out[4]:
5
In [5]:
2 -4 
Out[5]:
-2
In [12]:
5 / 2 #division
Out[12]:
2.5
In [11]:
5 // 2 # this is integer division
Out[11]:
2
In [10]:
5 ** 5 # power
Out[10]:
3125
In [13]:
4 * 5 # multiplication
Out[13]:
20
In [15]:
2**1000 # you can have realy big integers
Out[15]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [16]:
10%2 #modulus  ... reminder when divided by 2
Out[16]:
0
In [17]:
9%2
Out[17]:
1

There are real numbers

In [18]:
1/3
Out[18]:
0.3333333333333333
In [19]:
0.5 * 10
Out[19]:
5.0
In [20]:
0.5 ** 5
Out[20]:
0.03125

There are strings to represent text data

In [21]:
"This is string ...text data"
Out[21]:
'This is string ...text data'
In [22]:
sentence = "Hello World!"
In [23]:
sentence
Out[23]:
'Hello World!'
In [24]:
print(sentence)
Hello World!
In [25]:
sentence = "hello world" + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-25-70b5cd3b1dac> in <module>()
----> 1 sentence = "hello world" + 2

TypeError: must be str, not int
In [26]:
"hello " + "world!"
Out[26]:
'hello world!'
In [27]:
greeting = "Hello" " World"
In [28]:
greeting
Out[28]:
'Hello World'
In [29]:
name = "Arcesium"
In [30]:
name
Out[30]:
'Arcesium'
In [31]:
name + greeting
Out[31]:
'ArcesiumHello World'
In [32]:
name greeting
  File "<ipython-input-32-58ba491cf5a6>", line 1
    name greeting
                ^
SyntaxError: invalid syntax
In [33]:
name  + greeting
Out[33]:
'ArcesiumHello World'
In [34]:
name  + " " + greeting
Out[34]:
'Arcesium Hello World'
In [35]:
twolines = "one\ntwo"
In [36]:
print(twolines)
one
two
In [37]:
twolines
Out[37]:
'one\ntwo'
In [38]:
import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
In [39]:
poem = "The Zen of Python, by Tim Peters\nBeautiful is better than ugly."
In [40]:
poem
Out[40]:
'The Zen of Python, by Tim Peters\nBeautiful is better than ugly.'
In [41]:
poem = """
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

poem = "The Zen of Python, by Tim Peters\nBeautiful is better than u
"""
In [42]:
poem
Out[42]:
'\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren\'t special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you\'re Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it\'s a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let\'s do more of those!\n\npoem = "The Zen of Python, by Tim Peters\nBeautiful is better than u\n'
In [43]:
print(poem)
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

poem = "The Zen of Python, by Tim Peters
Beautiful is better than u

In [44]:
double = "I have a string with ' quote in it"
In [45]:
double
Out[45]:
"I have a string with ' quote in it"
In [46]:
single = 'A string with a " qoute in it' 
In [47]:
single
Out[47]:
'A string with a " qoute in it'
In [50]:
s = "A string with a \" qoute in it" 
In [51]:
s
Out[51]:
'A string with a " qoute in it'
In [52]:
star = "*"
In [56]:
fivestar = star * 5  # multiplication just replicates the string 5 times
In [55]:
fivestar
Out[55]:
'*****'

Higher level data types

Lists

In [57]:
numbers = [1,2,3,4,5,6,7,8,9]
In [58]:
numbers[0]
Out[58]:
1
In [59]:
numbers[-1]
Out[59]:
9
  -> 0  1  2  3  4  5
     A  B  C  D  E  F
    -6 -5 -4 -3 -2 -1  <-
In [60]:
l = [1, 2, "A", "Hello", "World"]
In [61]:
l[0]
Out[61]:
1
In [62]:
l[-1]
Out[62]:
'World'
In [63]:
l
Out[63]:
[1, 2, 'A', 'Hello', 'World']
In [64]:
l[0] = -1
In [65]:
l
Out[65]:
[-1, 2, 'A', 'Hello', 'World']
In [ ]:
 

tuples

Tuples are siblings of lists, it works exactly as list except that it does not allow any modification after creation.

In [66]:
t = (1, 2, 3, 4, 5)
In [67]:
t[0]
Out[67]:
1
In [68]:
t[-1]
Out[68]:
5
In [69]:
t[0] = 878
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-69-33a48cac05ac> in <module>()
----> 1 t[0] = 878

TypeError: 'tuple' object does not support item assignment
In [70]:
x = 3
In [71]:
del x

dictionaries

lists are collections which can be accessed by indices while dictionaries are collections which can be accessed by names

In [72]:
person = {"name":"alice", "age":12, "language":"English"}
In [74]:
l = ["alice", 12, "English"]
In [75]:
person['name']
Out[75]:
'alice'
In [76]:
person['age']
Out[76]:
12
In [77]:
person['language']
Out[77]:
'English'
In [79]:
person1 = {"name":"David",
            "age":50,
            "launguage":"English"
           }
In [80]:
person1['name']
Out[80]:
'David'
In [81]:
person['name']
Out[81]:
'alice'
In [84]:
persons_ = {"names":["Alice", "David"],
          "ages":[12,50],
           "languages":["English", "English"]
          }
In [85]:
persons = [ person, person1]
In [86]:
persons_['names'][0]
Out[86]:
'Alice'
In [87]:
persons_['names'][1]
Out[87]:
'David'
In [88]:
persons_['names']
Out[88]:
['Alice', 'David']
In [90]:
persons[0]['name']
Out[90]:
'alice'
In [91]:
persons_['names'[1]]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-91-f9e32ad66e57> in <module>()
----> 1 persons_['names'[1]]

KeyError: 'a'
In [93]:
sentence
Out[93]:
'Hello World!'
In [94]:
sentence[0]
Out[94]:
'H'
In [95]:
'names'[1]
Out[95]:
'a'

problem Represent stocks using lists and dictionaries. A stock has attributes

  • ticker
  • value
  • name
  • volume

represent it for 4 different stocks

name     ticker    value  volume
Infosys  infy      1000   500
Tata     tata      500    50
Reliance reliance  700    100
In [96]:
x = 2 + 3
In [97]:
x, y = 2*2 ,  2**4
In [98]:
x
Out[98]:
4
In [99]:
y
Out[99]:
16
In [102]:
x,y = 2*2,2**4
In [105]:
I = {"ticker":"infy", "value":1000, "volume":500}
T = {"ticker":"tata", "value":500, "volume":50}
R = {"ticker":"reliance", "value":700, "volume":100}
stocks = {"Infosys":I,
         "Tata":T,
         "Reliance":R}
In [108]:
stocks["Tata"]['ticker']
Out[108]:
'tata'
In [109]:
stocks["Tata"]['value']
Out[109]:
500
In [110]:
stocks["Tata"]['volume']
Out[110]:
50

boolean

In [111]:
yes = True
In [112]:
no = False
In [113]:
yes
Out[113]:
True
In [114]:
yes or no
Out[114]:
True
In [115]:
yes and no
Out[115]:
False
In [116]:
2 > 3
Out[116]:
False
In [117]:
no and no
Out[117]:
False
  • and results in true if both are True, otherwise False
  • or results in True in at least one is True
In [119]:
stocks['Tata']['value'] > 200 
Out[119]:
True
In [121]:
stocks['Tata']['value'] > 200 and stocks['Tata']['volume'] > 10
Out[121]:
True
In [122]:
"Tata" in stocks
Out[122]:
True
In [123]:
"Citi" in stocks
Out[123]:
False
In [124]:
2 in [1,2,3,5,7,11]
Out[124]:
True
In [125]:
"Citi" not in stocks
Out[125]:
True
In [126]:
stocks.keys()
Out[126]:
dict_keys(['Infosys', 'Tata', 'Reliance'])
In [127]:
person
Out[127]:
{'age': 12, 'language': 'English', 'name': 'alice'}
In [128]:
"Tata" in stocks
Out[128]:
True
In [129]:
stocks['Tata']
Out[129]:
{'ticker': 'tata', 'value': 500, 'volume': 50}
In [130]:
print(stocks['Tata'])
{'ticker': 'tata', 'value': 500, 'volume': 50}

Nothing

In [131]:
None
In [132]:
x 
Out[132]:
4
In [133]:
del x
In [134]:
x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-134-401b30e3b8b5> in <module>()
----> 1 x

NameError: name 'x' is not defined
In [135]:
x = None
In [136]:
print(x)
None
In [137]:
x
In [138]:
2 != 3
Out[138]:
True
In [139]:
2 == 2
Out[139]:
True

functions

In [140]:
l 
Out[140]:
['alice', 12, 'English']
In [145]:
len(l) #list
Out[145]:
3
In [146]:
len(stocks) # dict
Out[146]:
3
In [147]:
len("Hello World!") # string
Out[147]:
12
In [148]:
len(t) # tuple
Out[148]:
5
In [149]:
int("2")
Out[149]:
2
In [150]:
str(2)
Out[150]:
'2'
In [151]:
float("2.3")
Out[151]:
2.3
In [152]:
fs = "2.3"
In [153]:
fs + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-153-8592301a8f79> in <module>()
----> 1 fs + 2

TypeError: must be str, not int
In [154]:
float(fs) + 2
Out[154]:
4.3
In [155]:
l = [1,2,3,4,5]
In [156]:
n = len(l)
In [157]:
len(str(100))
Out[157]:
3
len(str(100))
len('100')
3
In [158]:
list((1,2,3,4))
Out[158]:
[1, 2, 3, 4]
In [160]:
list(range(0,10))
Out[160]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [161]:
list(range(10))
Out[161]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [162]:
list(range(1,10))
Out[162]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [163]:
list(range(1,20, 2))
Out[163]:
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
In [165]:
print(range(1,20, 2))
range(1, 20, 2)
In [167]:
items = [("name", "alice"),("age",12), ("language","english")]
In [168]:
items[0]
Out[168]:
('name', 'alice')
In [169]:
dict(items)
Out[169]:
{'age': 12, 'language': 'english', 'name': 'alice'}
In [170]:
dict(range(5))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-170-5bc7246e1a5e> in <module>()
----> 1 dict(range(5))

TypeError: cannot convert dictionary update sequence element #0 to a sequence
In [171]:
list(range(5))
Out[171]:
[0, 1, 2, 3, 4]
In [172]:
items = [["name", "alice"],["age",12], ["language","english"]]
In [173]:
dict(items)
Out[173]:
{'age': 12, 'language': 'english', 'name': 'alice'}
In [174]:
tuple(range(5))
Out[174]:
(0, 1, 2, 3, 4)
In [175]:
sum(range(1,101))
Out[175]:
5050
In [177]:
2**100 # how many digits are there?
Out[177]:
1267650600228229401496703205376

custom functions

In [178]:
def count_digits(n):
    s = str(n)
    digits = len(s)
    return digits
In [179]:
count_digits(100)
Out[179]:
3
In [180]:
count_digits(2**100)
Out[180]:
31
In [181]:
def add(x,y):
    return x+y
In [182]:
add(3,4)
Out[182]:
7
In [183]:
add([1,2,3],[5,6])
Out[183]:
[1, 2, 3, 5, 6]
In [184]:
add("hello", " world")
Out[184]:
'hello world'
In [185]:
[1, 2, 3] + [1,1,1]
Out[185]:
[1, 2, 3, 1, 1, 1]
In [186]:
x = 3
In [187]:
add(6,7)
Out[187]:
13
In [188]:
x
Out[188]:
3

problem

  • write a function tp find sum of first n natural numbers?
    >>> sumnatural(10)
    55
  • Write a function to twice a number
In [189]:
def twice(x):
    return 2*x

def twice_(x):
    print(2*x)
In [190]:
twice(3)
Out[190]:
6
In [191]:
twice_(3)
6
In [192]:
y = twice(3)
In [193]:
z = twice_(3)
6
In [194]:
print(y)
6
In [195]:
print(z)
None
In [196]:
twice(twice(4))
Out[196]:
16
In [197]:
twice_(twice_(4))
8
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-197-f7bc40748394> in <module>()
----> 1 twice_(twice_(4))

<ipython-input-189-b7a810d8d8c4> in twice_(x)
      3 
      4 def twice_(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [198]:
def sumnaturals(n):
    return sum(range(1,n+1))
In [199]:
sumnaturals(100)
Out[199]:
5050

methods

In [200]:
name = "ARCESIUM"
In [201]:
name
Out[201]:
'ARCESIUM'
In [202]:
name.lower()
Out[202]:
'arcesium'
In [203]:
name1 = name.lower()
In [205]:
name1.replace("a","A")
Out[205]:
'Arcesium'
In [206]:
name
Out[206]:
'ARCESIUM'
In [207]:
name.lower()
Out[207]:
'arcesium'
In [208]:
"xyz".upper()
Out[208]:
'XYZ'
In [209]:
random = "I have a random string to do some operations"
In [210]:
random.count("o")
Out[210]:
6
In [211]:
random.count("ing")
Out[211]:
1
In [212]:
random.split(" ")
Out[212]:
['I', 'have', 'a', 'random', 'string', 'to', 'do', 'some', 'operations']
In [213]:
csvline = "a,b,c,d,e,xyz,hello"
In [214]:
csvline.split(",")
Out[214]:
['a', 'b', 'c', 'd', 'e', 'xyz', 'hello']
In [215]:
poem
Out[215]:
'\nThe Zen of Python, by Tim Peters\n\nBeautiful is better than ugly.\nExplicit is better than implicit.\nSimple is better than complex.\nComplex is better than complicated.\nFlat is better than nested.\nSparse is better than dense.\nReadability counts.\nSpecial cases aren\'t special enough to break the rules.\nAlthough practicality beats purity.\nErrors should never pass silently.\nUnless explicitly silenced.\nIn the face of ambiguity, refuse the temptation to guess.\nThere should be one-- and preferably only one --obvious way to do it.\nAlthough that way may not be obvious at first unless you\'re Dutch.\nNow is better than never.\nAlthough never is often better than *right* now.\nIf the implementation is hard to explain, it\'s a bad idea.\nIf the implementation is easy to explain, it may be a good idea.\nNamespaces are one honking great idea -- let\'s do more of those!\n\npoem = "The Zen of Python, by Tim Peters\nBeautiful is better than u\n'
In [217]:
words = poem.split()
In [218]:
len(words)
Out[218]:
158
In [221]:
poem.lower().count(" ")
Out[221]:
136
In [222]:
poem.lower().count("\n")
Out[222]:
25
In [229]:
len(poem) # alphabet count which includes spaces
Out[229]:
927
In [224]:
words[0]
Out[224]:
'The'
In [225]:
poem[0]
Out[225]:
'\n'
In [230]:
len(poem.replace(" ","").replace("\n","").replace("\t","")) # alphabet count without spaces
Out[230]:
766
In [231]:
random.startswith("some")
Out[231]:
False
In [232]:
random.startswith("I")
Out[232]:
True
In [233]:
filename = "hello.py"
In [234]:
filename.endswith(".py")
Out[234]:
True
In [235]:
greeting
Out[235]:
'Hello World'
In [237]:
greeting.center(100)
Out[237]:
'                                            Hello World                                             '
In [238]:
greeting.ljust(100)
Out[238]:
'Hello World                                                                                         '
In [239]:
greeting.rjust(100)
Out[239]:
'                                                                                         Hello World'

problem

  • count number of zeros in 2**1000
In [ ]: