Basic Python Training at Arcesium - Day 1

Oct 25-31, 2018 Vikrant Patil

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

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

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

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

In [1]:
2 + 3
Out[1]:
5
In [2]:
3.0 + 3
Out[2]:
6.0
In [3]:
2**100
Out[3]:
1267650600228229401496703205376

# header #

header1

## header ##

header2

### header ###

header3

Numeric data

In [4]:
 1 + 2
Out[4]:
3
In [5]:
3 - 5
Out[5]:
-2
In [6]:
2 * 5
Out[6]:
10
In [7]:
2 ** 5
Out[7]:
32
In [8]:
6/2
Out[8]:
3.0
In [9]:
6//2
Out[9]:
3
In [10]:
5//2
Out[10]:
2
In [11]:
5/2
Out[11]:
2.5
In [12]:
3.0 + 1.2
Out[12]:
4.2
In [13]:
4.5 - 5
Out[13]:
-0.5
In [14]:
4.4 * 2
Out[14]:
8.8
In [15]:
4.4**3
Out[15]:
85.18400000000003
In [16]:
5**0.5
Out[16]:
2.23606797749979

text data

In [17]:
language = "python"
In [18]:
language
Out[18]:
'python'
In [19]:
doublequoted = "double quoted string"
singlequoted = "single quoted string"
In [20]:
doublequoted
Out[20]:
'double quoted string'
In [21]:
singlequoted
Out[21]:
'single quoted string'
In [22]:
convers = 'he said, "I am fine"'
In [23]:
convers
Out[23]:
'he said, "I am fine"'
In [26]:
both = "\"'"
In [27]:
both
Out[27]:
'"\''
In [28]:
tabbed = "name\tsurname"
In [29]:
print(tabbed)
name	surname
In [30]:
print(both)
"'
In [31]:
both
Out[31]:
'"\''
In [32]:
twoline = "first line\nsecond line"
In [33]:
print(twoline)
first line
second line
In [34]:
multi= """
this is frist line
second line
thrid line
..
.
you can have as many as you want
"""
In [35]:
print(multi)
this is frist line
second line
thrid line
..
.
you can have as many as you want

In [36]:
s = """
hello
how's that
it"s good
"""
In [37]:
print(s)
hello
how's that
it"s good

In [38]:
'''
single quoted multiline string
hello
there
'''
Out[38]:
'\nsingle quoted multiline string\nhello\nthere\n'
In [39]:
s = "hello" "world"
In [40]:
s
Out[40]:
'helloworld'
In [45]:
unicode = "आ"
In [46]:
print(unicode)
आ
In [47]:
empty = ""

Lists

In [50]:
digits = [1,2,3,4,5,6,7,8,9]
In [51]:
digits
Out[51]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [52]:
digits[0]
Out[52]:
1
In [53]:
digits[-1]
Out[53]:
9
   [A, B , C, D]
->  0  1   2  3
   -4 -3  -2 -1 <-
      [1, 2, 3, 4, 5, 6, 7, 8, 9]
index  0  1  2  3  4  5  6  7  8
In [54]:
digits[2:6]  #start at index 2, end at 6(exlude)
Out[54]:
[3, 4, 5, 6]
In [55]:
digits[:2] #take first two
Out[55]:
[1, 2]
In [57]:
digits[2:]  #drop first two
Out[57]:
[3, 4, 5, 6, 7, 8, 9]
In [59]:
a = 3
b = 4
c = "hello"
d = """
multi
line
string
"""
In [60]:
collection = [a, b, c, d]
In [62]:
print(collection[-1])
multi
line
string

In [63]:
print(collection[0])
3
In [64]:
collection
Out[64]:
[3, 4, 'hello', '\nmulti\nline\nstring\n']
In [65]:
data2d = [[1,2,3],[4,5,6],[7,8,9]]
In [66]:
data2d
Out[66]:
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
In [67]:
data2d[0]
Out[67]:
[1, 2, 3]
In [68]:
data2d[-1] # last row
Out[68]:
[7, 8, 9]
In [71]:
data2d[0][0] # 0th element from 0th row
Out[71]:
1

tuple

In [72]:
t = (1, 2, 3, 4, 5)
In [73]:
numbers = [1, 1, 2, 3, 5, 8]
In [74]:
numbers[0] = 0
In [75]:
numbers
Out[75]:
[0, 1, 2, 3, 5, 8]
In [76]:
t[0] = 0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-76-6e5fc4c1fe4b> in <module>()
----> 1 t[0] = 0

TypeError: 'tuple' object does not support item assignment

set

In [77]:
players = ["David", "Alice", "Alex", "Lewis", "Anand", "Shiva"]
countries  = ["USA", "UK", "USA", "UK", "India", "India"]
In [79]:
cont = set(countries)
In [80]:
cont
Out[80]:
{'India', 'UK', 'USA'}
In [ ]:
 

dictionaries

In [81]:
person = {"name":"Alice", "email":"alice@wonder.land", "age":13}
In [82]:
person["name"]
Out[82]:
'Alice'
In [83]:
person["email"]
Out[83]:
'alice@wonder.land'
In [84]:
person["age"]
Out[84]:
13
In [86]:
sum(numbers)
Out[86]:
19
In [87]:
numbers
Out[87]:
[0, 1, 2, 3, 5, 8]
In [88]:
sum_ = 19
mean = sum_/6
In [89]:
data ={
    "numbers" : numbers,
    "sum":sum_,
    "mean":mean
}
In [90]:
data
Out[90]:
{'mean': 3.1666666666666665, 'numbers': [0, 1, 2, 3, 5, 8], 'sum': 19}
In [91]:
sum_
Out[91]:
19
In [92]:
sum = [2,3,4,5]
In [93]:
sum_ = sum(numbers)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-93-7730b25d884f> in <module>()
----> 1 sum_ = sum(1,2)

TypeError: 'list' object is not callable
In [94]:
del sum
In [95]:
sum = [2,3,4,5]
sum_ = sum[2:5]
In [96]:
sum_
Out[96]:
[4, 5]
In [97]:
sum(2,3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-97-498fc7f56b7c> in <module>()
----> 1 sum(2,3)

TypeError: 'list' object is not callable
In [98]:
del sum
In [100]:
sum([3,4])
Out[100]:
7
In [101]:
sum_
Out[101]:
[4, 5]

boolean

In [102]:
yes = True
In [103]:
yes
Out[103]:
True
In [104]:
no = False
In [105]:
no 
Out[105]:
False
In [106]:
x = 2
In [107]:
x == 2
Out[107]:
True
In [112]:
x == 3 # check if equal
Out[112]:
False
In [111]:
x != 0 ## check if not equal
Out[111]:
True
In [110]:
"hel" in "hello world"
Out[110]:
True

nothing

In [113]:
nothing = None
In [114]:
nothing
In [115]:
print(nothing)
None

try this

pre = "foo"
post = "bar"
together = pre post
In [116]:
"foo" "bar"
Out[116]:
'foobar'
In [117]:
pre = "foo"
post = "bar"
In [119]:
x = 4
y = 5
In [120]:
x +y 
Out[120]:
9
In [121]:
print(x,y)
4 5

functions

In [122]:
 3 + 4
Out[122]:
7
In [124]:
numbers = [1,2,3,4,5,6]
sum_ = sum(numbers)
mean = sum_/6
In [125]:
def stats(numbers):
    s = sum(numbers)
    m = s/len(numbers)
    return s,m
In [126]:
def add(x, y):
    return x+y
In [127]:
add(2, 3)
Out[127]:
5
In [128]:
stats(numbers)
Out[128]:
(21, 3.5)
In [129]:
len(numbers)
Out[129]:
6
In [130]:
numbers
Out[130]:
[1, 2, 3, 4, 5, 6]
In [131]:
len("How many char are there in this string")
Out[131]:
38
In [133]:
len(t) # t is tuple
Out[133]:
5
In [136]:
t
Out[136]:
(1, 2, 3, 4, 5)
In [135]:
len(person) # dictionary
Out[135]:
3
In [137]:
person
Out[137]:
{'age': 13, 'email': 'alice@wonder.land', 'name': 'Alice'}
In [138]:
cont
Out[138]:
{'India', 'UK', 'USA'}
In [139]:
len(cont)
Out[139]:
3
In [140]:
len(100)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-140-2bbfa4afcf73> in <module>()
----> 1 len(100)

TypeError: object of type 'int' has no len()
In [141]:
int("100")
Out[141]:
100
In [142]:
str100 = "100"
In [143]:
int(str100)
Out[143]:
100
In [144]:
len(str100)
Out[144]:
3
In [145]:
len(100)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-145-2bbfa4afcf73> in <module>()
----> 1 len(100)

TypeError: object of type 'int' has no len()
In [146]:
float("1.2")
Out[146]:
1.2
In [147]:
t
Out[147]:
(1, 2, 3, 4, 5)
In [148]:
len(w)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-148-5cd91cc38d09> in <module>()
----> 1 len(w)

NameError: name 'w' is not defined
In [149]:
str(1123)
Out[149]:
'1123'
In [151]:
sum([2,3,4,5,6])
Out[151]:
20
In [152]:
max([56,23,1,789,12323])
Out[152]:
12323

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

problem

  • find number of digits in 2**100
In [153]:
x = 2**100
strx = str(x)
len(strx)
Out[153]:
31

problem

  • Write a function count_digits which will return number of digits in given number
In [154]:
def count_digits(num):
    return len(str(num))
In [155]:
count_digits(2**1000)
Out[155]:
302

problem

  • write a function twice which returns twice of a number
  • make use of this fucntion to find 4 times of a number

bonus problem

  • Write a function sumnaturals which returns sum of first n natural numbers hint list(range(n))
In [156]:
list(range(10))
Out[156]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [157]:
def twice(x):
    return 2*x
In [159]:
def twice_(x):
    print(2*x)
In [160]:
twice(45)
Out[160]:
90
In [161]:
twice_(45)
90
In [162]:
x = 42
In [163]:
x2 = twice(x)
In [164]:
x2
Out[164]:
84
In [165]:
x2_ = twice_(x)
84
In [166]:
x2_
In [167]:
print(x2_)
None
twice(twice(2))
twice(4)
8
twice_(twice_(2))
twice_(None)
In [168]:
2*None
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-168-21056952a642> in <module>()
----> 1 2*None

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [170]:
numbers
Out[170]:
[1, 2, 3, 4, 5, 6]
In [171]:
singlequoted
Out[171]:
'single quoted string'
In [172]:
t
Out[172]:
(1, 2, 3, 4, 5)
In [173]:
person
Out[173]:
{'age': 13, 'email': 'alice@wonder.land', 'name': 'Alice'}
In [174]:
numbers.count(1)
Out[174]:
1
In [175]:
numbers.append(7)
In [176]:
numbers
Out[176]:
[1, 2, 3, 4, 5, 6, 7]
In [177]:
numbers.pop()
Out[177]:
7
In [178]:
numbers
Out[178]:
[1, 2, 3, 4, 5, 6]
In [179]:
numbers + numbers
Out[179]:
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
In [180]:
t + t
Out[180]:
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
In [181]:
numbers.pop()
Out[181]:
6
In [182]:
numbers[0] = -1
In [183]:
singlequoted
Out[183]:
'single quoted string'
In [184]:
singlequoted.count(" ")
Out[184]:
2
In [185]:
singlequoted.lower()
Out[185]:
'single quoted string'
In [186]:
singlequoted.upper()
Out[186]:
'SINGLE QUOTED STRING'
In [187]:
singlequoted.split(" ")
Out[187]:
['single', 'quoted', 'string']
In [188]:
singlequoted.split()
Out[188]:
['single', 'quoted', 'string']
In [189]:
"A,B,C,D".split(",")
Out[189]:
['A', 'B', 'C', 'D']
In [190]:
singlequoted.split(":")
Out[190]:
['single quoted string']
In [191]:
multi = """
  hello
world  
this has no trailing space
""" 
In [192]:
multi.split("\n")
Out[192]:
['', '  hello', 'world  ', 'this has no trailing space', '']
In [194]:
multi.strip().split()
Out[194]:
['hello', 'world', 'this', 'has', 'no', 'trailing', 'space']
In [195]:
x = "name:python"
x.split(":")
Out[195]:
['name', 'python']
In [196]:
x
Out[196]:
'name:python'
In [199]:
x.replace("python","english").replace("name", "NAME")
Out[199]:
'NAME:english'
In [201]:
singlequoted.startswith("hello")
Out[201]:
False
In [202]:
filename = "hello.py"
In [203]:
filename.endswith(".py")
Out[203]:
True
In [204]:
singlequoted.center(100)
Out[204]:
'                                        single quoted string                                        '
In [206]:
"*"*20 + singlequoted + "*"*20
Out[206]:
'********************single quoted string********************'
In [207]:
"python" in x
Out[207]:
True
In [209]:
".py" in filename
Out[209]:
True
In [ ]:
 

problems

  • write a function which decorates string as header of your file as given below

    >>> decorate("some header")
    ********************* SOME HEADER **********************
  • Write a function which tells whether given file is python file or not

    >>> is_python_file("system.dll")
    False
    >>> is_python_file("hello.py")
    True
  • Write a function to find extension of a file.

    >>> extension("system.dll")
    dll
    >>> extension("system.exe")
    exe
  • Write a function count_zeros which counts how many zeros are there in a number?

    >>> count_zeros(1000)
    3
In [1]:
x = [1,2,3,4]
In [2]:
x[-1]
Out[2]:
4
In [3]:
def decorate(header):
    pre = "*"*20
    return pre + " " + header.upper() + " " + pre
In [4]:
decorate("Hello world")
Out[4]:
'******************** HELLO WORLD ********************'
In [5]:
def is_python_file(filename):
    return filename.endswith(".py")
In [7]:
is_python_file("system.dll")
Out[7]:
False
In [8]:
is_python_file("hello.py")
Out[8]:
True
In [9]:
def extension(filename):
    return filename.split(".")[-1]
In [10]:
extension("python.exe")
Out[10]:
'exe'
In [11]:
extension("hello.py")
Out[11]:
'py'
In [12]:
extension("hello.py.tgz")
Out[12]:
'tgz'
In [13]:
"_".join(["hello", "world"])
Out[13]:
'hello_world'
In [14]:
filename = "hello.py.tgz"
In [17]:
tokens = filename.split(".")
In [18]:
tokens
Out[18]:
['hello', 'py', 'tgz']
In [19]:
tokens.pop()
Out[19]:
'tgz'
In [20]:
tokens
Out[20]:
['hello', 'py']
In [21]:
".".join(tokens)
Out[21]:
'hello.py'
In [22]:
help(filename.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings
    
    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

In [23]:
filename.split(".")[-1].pop()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-23-13f7fa9c5c1a> in <module>()
----> 1 filename.split(".")[-1].pop()

AttributeError: 'str' object has no attribute 'pop'
In [24]:
s = " there is this sentence with some trailing spaces, one more sentence    "
In [25]:
s.split(",")
Out[25]:
[' there is this sentence with some trailing spaces', ' one more sentence    ']
In [27]:
s.strip().split(",")
Out[27]:
['there is this sentence with some trailing spaces', ' one more sentence']
In [28]:
def count_zeros(n):
    return str(n).count('0')
In [29]:
count_zeros(1000)
Out[29]:
3

methods from lists

In [31]:
l = [1, 1, 1, 2, 3, 5, 6]
In [32]:
l.count(1)
Out[32]:
3
In [33]:
l.insert(0, -1)
In [34]:
l
Out[34]:
[-1, 1, 1, 1, 2, 3, 5, 6]
In [35]:
l.reverse()
In [36]:
l
Out[36]:
[6, 5, 3, 2, 1, 1, 1, -1]
In [37]:
l.sort()
In [38]:
l
Out[38]:
[-1, 1, 1, 1, 2, 3, 5, 6]
In [39]:
l.sort(reverse=True)
In [40]:
l
Out[40]:
[6, 5, 3, 2, 1, 1, 1, -1]
In [41]:
words = ["one", "two", "three", "four", "five"]
In [42]:
sorted(words)
Out[42]:
['five', 'four', 'one', 'three', 'two']
In [43]:
sorted(words, reverse=True)
Out[43]:
['two', 'three', 'one', 'four', 'five']
In [44]:
def fun():
    print("Fun!")
In [45]:
fun
Out[45]:
<function __main__.fun>
In [46]:
x
Out[46]:
[1, 2, 3, 4]
In [47]:
a = 2
In [48]:
a
Out[48]:
2
In [49]:
fun
Out[49]:
<function __main__.fun>
In [50]:
a()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-72f2e37b262f> in <module>()
----> 1 a()

TypeError: 'int' object is not callable
In [51]:
a
Out[51]:
2
In [52]:
fun
Out[52]:
<function __main__.fun>
In [53]:
fun()
Fun!
In [54]:
b = a
In [55]:
b
Out[55]:
2
In [57]:
aliasfun = fun
In [60]:
aliasfun
Out[60]:
<function __main__.fun>
In [62]:
aliasfun()
Fun!
In [63]:
def square(x):
    return x*x

def sumofsquares(x, y):
    return square(x) + square(y)

def cube(x):
    return x*x*x

def sumofcubes(x,y):
    return cube(x) + cube(y)
In [64]:
def sumof(f, x, y):
    return f(x) + f(y)
    
In [65]:
sumof(square, 2, 5)
Out[65]:
29
In [66]:
sumofsquares(2, 5)
Out[66]:
29
In [67]:
words
Out[67]:
['one', 'two', 'three', 'four', 'five']
In [68]:
max(words)
Out[68]:
'two'
In [69]:
max(words, key=len)
Out[69]:
'three'
In [70]:
sorted(words)
Out[70]:
['five', 'four', 'one', 'three', 'two']
In [71]:
sorted(words, key=len)
Out[71]:
['one', 'two', 'four', 'five', 'three']
In [ ]: