Python Training at VMWare Pune - Day 1

Dec 13-15, 2017 Vikrant Patil

These notes are available online at http://notes.pipal.in/2017/vmware-nov-python

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

Quick start

In [1]:
2 + 3
Out[1]:
5
In [2]:
print("hello")
hello
In [3]:
name = "Python"
In [4]:
name
Out[4]:
'Python'
In [5]:
print(name)
Python

Basic datatypes

In [6]:
2 + 3
Out[6]:
5
In [7]:
2 - 4
Out[7]:
-2
In [8]:
3 ** 2
Out[8]:
9
In [9]:
2 ** 1000
Out[9]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [10]:
3 / 2
Out[10]:
1.5
In [11]:
3 // 2
Out[11]:
1
In [12]:
2.0 + 1
Out[12]:
3.0
In [13]:
name = "Rupali"
In [14]:
second = "Rupak"
In [15]:
name + " " + second
Out[15]:
'Rupali Rupak'
In [16]:
star = "*"
In [17]:
star*5
Out[17]:
'*****'
In [18]:
singlequoted = 'string with " quote inside'
In [19]:
print(singlequoted)
string with " quote inside
In [20]:
doublequoted = "string with ' quote inside"
In [21]:
multiline = """
this is a multi
line
string
with 4 lines
"""
In [22]:
print(multiline)
this is a multi
line
string
with 4 lines

In [23]:
multiline
Out[23]:
'\nthis is a multi\nline\nstring\nwith 4 lines\n'
In [27]:
tabed = "rupali\trupak"
In [28]:
print(tabed)
rupali	rupak
In [29]:
regional = "आ ष"
In [30]:
regional
Out[30]:
'आ ष'
In [31]:
unicode = "\uc085"
In [32]:
print(unicode)
ì‚…
In [33]:
binary = b'hello python'
In [34]:
print(binary)
b'hello python'
In [35]:
binary.decode()
Out[35]:
'hello python'
In [36]:
"string".encode()
Out[36]:
b'string'

lists

In [37]:
ones = [1,1,1,1]
In [38]:
ones[0]
Out[38]:
1
In [39]:
digits = [1,2,3,4,5,6,7,8,9]
In [40]:
digits[0]
Out[40]:
1
In [41]:
digits[2]
Out[41]:
3
In [42]:
digits[-1]
Out[42]:
9
In [43]:
digits[-5]
Out[43]:
5
In [44]:
digits[:2] # everything till second index
Out[44]:
[1, 2]
In [45]:
digits[2:] # drop first two
Out[45]:
[3, 4, 5, 6, 7, 8, 9]
In [46]:
ones
Out[46]:
[1, 1, 1, 1]
In [47]:
moreones = ones * 5
In [48]:
moreones
Out[48]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [49]:
len(ones)
Out[49]:
4

tuples

In [50]:
tigits  = (1,2,3,4,5,6,7,8,9)
In [51]:
tigits*2
Out[51]:
(1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9)
In [52]:
tigits[0]
Out[52]:
1
In [53]:
tigits[-1]
Out[53]:
9
In [54]:
tigits[1:]
Out[54]:
(2, 3, 4, 5, 6, 7, 8, 9)
In [55]:
sentence = """
some random statement
just to check how many english alphabets
are used in it
"""
In [60]:
s = set(sentence)
In [61]:
s
Out[61]:
{'\n',
 ' ',
 'a',
 'b',
 'c',
 'd',
 'e',
 'g',
 'h',
 'i',
 'j',
 'k',
 'l',
 'm',
 'n',
 'o',
 'p',
 'r',
 's',
 't',
 'u',
 'w',
 'y'}

Dictionaries

In [63]:
person = {"name":"alice", "email":"alice@wonder.land"}
In [64]:
person['name']
Out[64]:
'alice'

Some built in functions

In [ ]:
 
In [57]:
len("this is a string to test len")
Out[57]:
28
In [58]:
len(ones)
Out[58]:
4
In [59]:
len(tigits)
Out[59]:
9
In [62]:
len(s)
Out[62]:
23
In [65]:
len(person)
Out[65]:
2
In [66]:
str(121232)
Out[66]:
'121232'
In [67]:
int("45")
Out[67]:
45

problem find number of digits in 2**100

In [68]:
value = 2**100
In [69]:
value
Out[69]:
1267650600228229401496703205376
In [70]:
strvalue = str(value)
In [71]:
strvalue
Out[71]:
'1267650600228229401496703205376'
In [72]:
len(strvalue)
Out[72]:
31
In [73]:
s = "some string so that you understand \n new line"
In [74]:
s
Out[74]:
'some string so that you understand \n new line'
In [75]:
print(s)
some string so that you understand 
 new line
In [76]:
repr(s)
Out[76]:
"'some string so that you understand \\n new line'"
In [77]:
total = "first" "second"
In [78]:
total
Out[78]:
'firstsecond'

Will this work?

pre = "Isac"
post = "Asimove"
name = pre post
In [79]:
2 + "3"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-79-2068cae7beb7> in <module>()
----> 1 2 + "3"

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [80]:
len([1,2,3,4])
Out[80]:
4

custom functions

In [81]:
def square(x):
    return x*x

def say_hello(name):
    print("hello", name)
In [82]:
square(2)
Out[82]:
4
In [83]:
say_hello("python")
hello python
In [84]:
sqr2 = square(2)
In [85]:
sqr2
Out[85]:
4
In [86]:
value = say_hello("Python")
hello Python
In [87]:
print(value)
None
In [88]:
value
In [89]:
value = None
In [90]:
def twice(x):
    return 2*x

def twice1(x):
    print(2*x)
In [91]:
twice(twice(twice(2)))
Out[91]:
16
In [92]:
twice1(twice1(2))
4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-92-d2f7a8448481> in <module>()
----> 1 twice1(twice1(2))

<ipython-input-90-3d4ed9845aa2> in twice1(x)
      3 
      4 def twice1(x):
----> 5     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [93]:
def count_digits(n):
    return len(str(n))
In [95]:
count_digits(2**1000)
Out[95]:
302

More about functions

In [96]:
def add(x, y):
    return x+y
In [97]:
add
Out[97]:
<function __main__.add>
In [98]:
print(add)
<function add at 0x7f6f0ce7a2f0>
In [99]:
aliasadd = add
In [100]:
aliasadd
Out[100]:
<function __main__.add>
In [101]:
add(2,4)
Out[101]:
6
In [102]:
aliasadd(2,4)
Out[102]:
6
In [103]:
def square(x):
    return x*x

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

def cube(x):
    return x**3

def sumofcubes(x,y):
    return cube(x) + cube(y)
In [104]:
def sumof(func, x, y):
    return func(x) + func(y)
In [105]:
sumofsquares(2,3)
Out[105]:
13
In [106]:
sumof(square, 2, 3)
Out[106]:
13
In [107]:
sumofcubes(2,3)
Out[107]:
35
In [108]:
sumof(cube, 2, 3)
Out[108]:
35
In [109]:
def fourthpower(x):
    return x**4

sumof(fourthpower, 3, 4)
Out[109]:
337

Functions are just like any other object. You can pass functions as argument just like any other variables, you can return functions just like a variable.

In [110]:
squares = lambda x: x*x
In [111]:
square(2)
Out[111]:
4
In [112]:
sumof(lambda y:y**4, 3,4)
Out[112]:
337
In [113]:
diff = lambda x,y : y-x
In [114]:
diff(5,7)
Out[114]:
2
In [115]:
def make_adder(x):
    
    def adder(y):
        return x+y
    
    return adder
In [117]:
adder5 = make_adder(5)
In [118]:
adder5
Out[118]:
<function __main__.make_adder.<locals>.adder>
In [119]:
adder5(4)
Out[119]:
9
In [120]:
adder5(5)
Out[120]:
10
In [121]:
adder5(6)
Out[121]:
11

Passing functions as parameter to function makes that function usable in multiple conditions. This is used in many built in functions

In [122]:
max(3,5)
Out[122]:
5
In [123]:
max([1,2,3,4,5,6])
Out[123]:
6
In [124]:
max(["one", "two", "three"])
Out[124]:
'two'
In [126]:
max(["one", "two", "three"], len)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-126-32a9f08fb46b> in <module>()
----> 1 max(["one", "two", "three"], len)

TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'list'
In [127]:
def volume(radius, height):
    return 3.14*radius**2*height
In [128]:
volume(1, 5)
Out[128]:
15.700000000000001
In [129]:
volume(5, 1)
Out[129]:
78.5
In [130]:
volume(radius=1, height=5)
Out[130]:
15.700000000000001
In [131]:
volume(1, height=5)
Out[131]:
15.700000000000001
In [132]:
volume(radius=1, 5)
  File "<ipython-input-132-711677c22153>", line 1
    volume(radius=1, 5)
                    ^
SyntaxError: positional argument follows keyword argument
In [133]:
def volume1(radius, * , height=5):
    return 3.14*radius**2*height
In [134]:
volume1(1)
Out[134]:
15.700000000000001
In [135]:
volume1(1, 5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-135-9089165886c3> in <module>()
----> 1 volume1(1, 5)

TypeError: volume1() takes 1 positional argument but 2 were given
In [136]:
volume1(1, height=5)
Out[136]:
15.700000000000001
In [140]:
records = [
    ("A", 8.9),
    ("B", 3.4),
    ("C", 9.0),
    ("D", 4.0),
    ("E", 3.8)
]
In [141]:
max(records)
Out[141]:
('E', 3.8)
In [142]:
def get_score(record):
    return record[1]
In [143]:
max(records, key=get_score)
Out[143]:
('C', 9.0)
In [144]:
records[0]
Out[144]:
('A', 8.9)
In [145]:
records[-1]
Out[145]:
('E', 3.8)
In [146]:
r = records[0]
In [147]:
r
Out[147]:
('A', 8.9)
In [148]:
r[1]
Out[148]:
8.9
In [149]:
r[0]
Out[149]:
'A'

methods from objects

string

In [150]:
book = "Alice in wonderland"
In [151]:
book.lower()
Out[151]:
'alice in wonderland'
In [152]:
book.upper()
Out[152]:
'ALICE IN WONDERLAND'
In [153]:
len(book)
Out[153]:
19
In [154]:
book.endswith("land")
Out[154]:
True
In [155]:
book.startswith("Alice")
Out[155]:
True
In [156]:
book.count("i")
Out[156]:
2
In [157]:
book.count("d")
Out[157]:
2
In [158]:
book.split()
Out[158]:
['Alice', 'in', 'wonderland']
In [159]:
words = book.split()
In [160]:
"_".join(words)
Out[160]:
'Alice_in_wonderland'

problem: Write a function to find number of zeros in a given number.

count_zeros(1000)
3
In [165]:
def count_zeros(x):
   
    return str(x).count('0')
In [166]:
count_zeros(1000)
Out[166]:
3
In [167]:
count_zeros(2**10000)
Out[167]:
292

lists

In [168]:
numbers = list(range(5, 25, 2))
In [169]:
numbers.count(5)
Out[169]:
1
In [170]:
numbers.reverse()
In [171]:
numbers
Out[171]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [172]:
numbers.reverse()
In [173]:
numbers
Out[173]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [174]:
numbers.append(25)
In [175]:
numbers
Out[175]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25]
In [177]:
numbers.pop()
Out[177]:
25
In [178]:
numbers
Out[178]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [179]:
numbers.pop(0)
Out[179]:
5
In [180]:
numbers
Out[180]:
[7, 9, 11, 13, 15, 17, 19, 21, 23]
In [181]:
numbers.insert(0, 5)
In [182]:
numbers
Out[182]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [183]:
numbers.push()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-183-a3627ce841a4> in <module>()
----> 1 numbers.push()

AttributeError: 'list' object has no attribute 'push'
In [184]:
len(numbers)
Out[184]:
10

numbers.drop(5)

In [186]:
numbers.sort()
In [187]:
numbers
Out[187]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [188]:
numbers.sort(reverse=True)
In [189]:
numbers
Out[189]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [191]:
sorted(numbers)
Out[191]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [192]:
numbers
Out[192]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [193]:
names = ["tilak kamod", "bhimpalas", "yaman", "bageshri"]
In [194]:
names.extend(["durga", "bhoopali"])
In [195]:
names
Out[195]:
['tilak kamod', 'bhimpalas', 'yaman', 'bageshri', 'durga', 'bhoopali']
In [196]:
numbers
Out[196]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [197]:
numbers.insert(23, 7)
In [198]:
numbers
Out[198]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 7]
In [199]:
numbers[-1]
Out[199]:
7
In [200]:
numbers.insert(100, 56)
In [201]:
numbers
Out[201]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 7, 56]
In [202]:
numbers[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-202-c6a53c9e4685> in <module>()
----> 1 numbers[100]

IndexError: list index out of range
In [203]:
numbers[:100]
Out[203]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 7, 56]

tuples

In [204]:
tigits = (1, 2, 3, 4, 5, 6, 7, 8, 9)
In [205]:
tigits.count(2)
Out[205]:
1
In [206]:
tigits.index(5)
Out[206]:
4
In [207]:
numbers[0] = 25
In [208]:
numbers
Out[208]:
[25, 21, 19, 17, 15, 13, 11, 9, 7, 5, 7, 56]
In [209]:
tigits[0]
Out[209]:
1
In [210]:
tigits[0] = 4
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-210-51c80574f471> in <module>()
----> 1 tigits[0] = 4

TypeError: 'tuple' object does not support item assignment

problem: write a function head that takes a list and n , and returns first n items from the list

head(["python", "lisp", "ruby", "haskell", "java"], 2)
["python", "lisp"]

problem: Write a function rearrangemax that takes integer as an argument and returns a new integer with digits rearraged from max to min

rearrangemax(436218)
864321
In [216]:
def head(items, n=2):
    return items[:n]
In [223]:
def tail(items, n=2):
    return items[n+1:]
In [224]:
head(["python", "lisp", "ruby", "haskell", "java"])
Out[224]:
['python', 'lisp']
In [225]:
tail(["python", "lisp", "ruby", "haskell", "java"])
Out[225]:
['haskell', 'java']
In [226]:
n = 56456878
In [227]:
strnum = str(n)
In [228]:
strnum
Out[228]:
'56456878'
In [230]:
sorted(strnum, reverse=True)
Out[230]:
['8', '8', '7', '6', '6', '5', '5', '4']
In [231]:
"".join(sorted(strnum, reverse=True))
Out[231]:
'88766554'
In [232]:
int("".join(sorted(strnum, reverse=True)))
Out[232]:
88766554
In [233]:
def rearrangemax(n):
    ordereddigits = sorted(str(n), reverse=True)
    return int("".join(ordereddigits))
In [234]:
rearrangemax(34534543543)
Out[234]:
55544443333

modules

In [235]:
import math
In [236]:
def area_circle(r):
    return math.pi * r**r
In [237]:
math
Out[237]:
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [238]:
import math as m
In [239]:
m
Out[239]:
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [240]:
import sys
In [241]:
sys
Out[241]:
<module 'sys' (built-in)>
In [242]:
sys.argv
Out[242]:
['/home/vikrant/usr/local/anaconda3/lib/python3.6/site-packages/ipykernel_launcher.py',
 '-f',
 '/run/user/1000/jupyter/kernel-fe00131e-ab2e-4c8a-a393-c74f85c5f5e8.json']
In [243]:
math.sqrt(343)
Out[243]:
18.520259177452136
In [244]:
math.pi
Out[244]:
3.141592653589793
In [245]:
m.pow(3.4, 5)
Out[245]:
454.35423999999995
In [246]:
m.pi
Out[246]:
3.141592653589793
In [247]:
import os
In [248]:
os.getcwd()
Out[248]:
'/home/vikrant/trainings/2017/vmware-nov-python'
In [249]:
os.getenv("HOME")
Out[249]:
'/home/vikrant'
In [250]:
os.mkdir("/tmp/test1")
In [251]:
!ls /tmp/
config-err-g6eZHj
firefox_vikrant
mintUpdate
ssh-SF1u5QKR2E7i
systemd-private-4e09723323a443d7981af23065093b20-colord.service-YeLAo6
systemd-private-4e09723323a443d7981af23065093b20-rtkit-daemon.service-EPxOA0
test1
In [252]:
os.listdir(os.getcwd())
Out[252]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'day2.ipynb',
 'day2.html',
 'Makefile',
 'day1.html']
In [254]:
os.path.exists("/tmp/test")
Out[254]:
False
In [255]:
os.path.exists("/tmp/test1")
Out[255]:
True
In [256]:
os.path.getsize("./day1.html")
Out[256]:
402976

problem:

  • Write a function countfiles which counts number of files in given directory
  • Write a function biggestfile to find biggest file in given given directory.
In [257]:
def countfiles(path):
    return len(os.listdir(path))
In [258]:
countfiles(os.getcwd())
Out[258]:
7
In [259]:
def biggestfile(path):
    files = os.listdir(path)
    return max(files, key=os.path.getsize)
In [260]:
biggestfile(os.getcwd())
Out[260]:
'day1.html'

Custom modules

In [261]:
%%file mymodule.py

def say_hello(name):
    print("hello", name)
Writing mymodule.py
In [262]:
import mymodule
In [263]:
mymodule.say_hello("python")
hello python
In [264]:
%%file mymodule1.py
import sys

def say_hello(name):
    print("hello", name)
    
say_hello(sys.argv[1])
Writing mymodule1.py
In [265]:
!python mymodule1.py python
hello python
In [266]:
!python mymodule1.py java
hello java
In [267]:
import mymodule1
hello -f
In [268]:
%%file module.py
print(__name__)
Writing module.py
In [269]:
import module
module
In [270]:
!python module.py
__main__
In [271]:
%%file module1.py

def add(x,y):
    return x+y

def hello(name):
    print("hello", name)
Writing module1.py
In [272]:
import module1
In [273]:
module1.add(3,4)
Out[273]:
7
In [277]:
%%file arguments.py
import sys

def print_arguments():
    """
    prints system arguments
    """
    print(sys.argv)

if __name__ == "__main__":
    print_arguments()
Overwriting arguments.py
In [278]:
import arguments
In [280]:
!python arguments.py hello arg1 arg2 arg3
['arguments.py', 'hello', 'arg1', 'arg2', 'arg3']
In [281]:
help(os.listdir)
Help on built-in function listdir in module posix:

listdir(path=None)
    Return a list containing the names of the files in the directory.
    
    path can be specified as either str or bytes.  If path is bytes,
      the filenames returned will also be bytes; in all other circumstances
      the filenames returned will be str.
    If path is None, uses the path='.'.
    On some platforms, path may also be specified as an open file descriptor;\
      the file descriptor must refer to a directory.
      If this functionality is unavailable, using it raises NotImplementedError.
    
    The list is in arbitrary order.  It does not include the special
    entries '.' and '..' even if they are present in the directory.

In [282]:
help(arguments.print_arguments)
Help on function print_arguments in module arguments:

print_arguments()
    prints system arguments

In [283]:
import random
In [284]:
random.choice(["python", "java", "haskell", "lisp", "ruby"])
Out[284]:
'python'

problems:

  • Write a python script square.py that takes a number as commandline argument and prints square of it
  • write a python script echo.py equivalent of unix command echo
In [285]:
%%file square.py
import sys

def square(x):
    return x*x

if __name__ == "__main__":
    print(square(int(sys.argv[1])))
Writing square.py
In [286]:
!python square.py 5
25
In [287]:
import square
In [288]:
square.square(65)
Out[288]:
4225
In [289]:
%%file echo.py
import sys

def echo(args):
    print(" ".join(args))
    
if __name__ == "__main__":
    echo(sys.argv[1:])
Writing echo.py
In [290]:
!python echo.py hello this is echo command
hello this is echo command

Conditions

In [291]:
__name__ == "__main__"
Out[291]:
True
In [292]:
2 == 2
Out[292]:
True
In [293]:
1 > 2
Out[293]:
False
In [294]:
1.99 <= 2
Out[294]:
True
In [295]:
2 !=3 
Out[295]:
True
In [296]:
"python" > "c++"
Out[296]:
True
In [297]:
"alice" in "alice in wonderland"
Out[297]:
True
In [298]:
"this" is not "english"
Out[298]:
True
In [299]:
"alex" not in "alice in wonderland"
Out[299]:
True
In [300]:
book
Out[300]:
'Alice in wonderland'
In [301]:
book.endswith("land")
Out[301]:
True
In [302]:
book.startswith("Alice")
Out[302]:
True
In [303]:
if book.startswith("Alice"):
    print(book)
elif book.endswith("something"):
    print("elif1")
elif "python" in ["python", "c++", "ark"]:
    print("elif2")
elif True:
    print("you can have long list of elifs")
else:
    print("Finally end with else")
Alice in wonderland
In [304]:
emptylist = []
In [305]:
emptydict = {}
In [306]:
emptystr = ""
In [307]:
if emptylist:
    print("Not here")
else:
    print("yes here!")
yes here!
In [308]:
noneobject = None
In [309]:
if not noneobject:
    print("Yes it is None")
Yes it is None
In [310]:
def is_python_file(filename):
    return filename.endswith(".py")
In [311]:
is_python_file("mymodule.py")
Out[311]:
True
In [312]:
filename = "hello.py"
if is_python_file(filename):
    print(filename, "is python source file.")
else:
    print(filename, "is not python source file.")
hello.py is python source file.
In [313]:
def even(n):
    return n%2==0
In [314]:
def odd(n):
    return not even(n)

problem

  • write a python function filetype which determines type of file. file types supported by your function are listsed below
    type    extension
    java    .java
    python  .py
    haskell .hs
    c       .c
    text    .text
    >>> filetype("square.py")
    python
    >>> filetype("square.txt")
    text
  • Write a function minimum without using built in min! to find minimum of given two numbers
    >>> minimum(2,3)
    2
  • Write a function minimum3 which finds minimum from given 3 numbers
    >>> minimum3(1,2,3)
    1
In [315]:
2 == 2 and 2 !=3
Out[315]:
True
In [316]:
2==2 or 2==3
Out[316]:
True
In [317]:
def filetype(filename):
    if filename.endswith(".java"):
        return "java"
    elif filename.endswith(".py"):
        return "python"
    elif filename.endswith(".hs"):
        return "haskell"
    elif filename.endswith("c"):
        return "c"
    elif filename.endswith("txt"):
        return "text"
    else: return "Unknown"
In [318]:
filetype("hello.dffdf")
Out[318]:
'Unknown'
In [319]:
def minimum(x, y):
    if x <y:
        return x
    else:
        return y
In [320]:
def minimum3(x,y,z):
    return minimum(minimum(x,y), z)
In [321]:
primes = [2, 3, 5, 7, 11, 13, 17]
In [322]:
5 in primes
Out[322]:
True
In [323]:
primes2 = primes
In [325]:
primes2 == primes
Out[325]:
True
In [326]:
primes2 is primes
Out[326]:
True
In [327]:
primes3 = [2, 3, 5, 7, 11, 13, 17]
In [329]:
primes2 == primes3
Out[329]:
True
In [330]:
primes2 is primes3
Out[330]:
False
In [331]:
person = {"name":"robinson",
          "books":["Element", "Finding your element"],
          "language":"English"
         }
In [332]:
"robinson" in person
Out[332]:
False
In [333]:
"name" in person
Out[333]:
True
In [334]:
"robinson" in person.values()
Out[334]:
True

while loop

In [335]:
def print_fibonacci(n):
    """
    print sequence of fibonacci numbers less than n
    """
    
    prev, current = 1, 1
    while current < n:
        prev , current = current, prev+current
        print(prev, end=",")
In [336]:
print_fibonacci(25)
1,2,3,5,8,13,21,
In [337]:
print_fibonacci(100)
1,2,3,5,8,13,21,34,55,89,

for loop

In [338]:
items = primes
for item in items:
    print(item, end=",")
2,3,5,7,11,13,17,
In [339]:
range(10)
Out[339]:
range(0, 10)
In [340]:
for i in range(10):
    print(i, end=",")
0,1,2,3,4,5,6,7,8,9,
In [341]:
for name in ["elsa", "alice", "alex", "anand"]:
    print(name)
elsa
alice
alex
anand
In [342]:
for c in "this is a string to test for loop over chars":
    print(c, end=",")
t,h,i,s, ,i,s, ,a, ,s,t,r,i,n,g, ,t,o, ,t,e,s,t, ,f,o,r, ,l,o,o,p, ,o,v,e,r, ,c,h,a,r,s,
In [343]:
for i in range(2, 50, 5):
    print(i, end=",")
2,7,12,17,22,27,32,37,42,47,

problem:

  • write a python script ls.py which mimics unix command ls. i.e. it prints all the files in given directory

    python ls.py
    arguments.py 
    day1.html     
    day1.ipynb
  • write a function product that finds product of all items from given sequence.

  • can you make use of above function to find factorial of a number? write factorial function
In [344]:
!ls
arguments.py  day2.html   Makefile    mymodule1.py  __pycache__
day1.html     day2.ipynb  module1.py  mymodule.py   square.py
day1.ipynb    echo.py	  module.py   push
In [345]:
def product(numbers):
    p = numbers[0]
    for num in numbers[1:]:
        p = p*num
    return p
In [346]:
product([2,3,4])
Out[346]:
24
In [347]:
product(range(1,5))
Out[347]:
24
In [348]:
def fact(n):
    return product(range(1, n+1))
In [349]:
factorial = lambda n : product(range(1, n+1))
In [350]:
factorial(10)
Out[350]:
3628800
In [351]:
factorial(4)
Out[351]:
24
In [352]:
fact(5)
Out[352]:
120
In [353]:
factorial(5)
Out[353]:
120
In [354]:
def print_primes(n):
    for i in range(1, n+1):
        for j in range(2,i):
            if i%j==0:
                break
        else:
            print(i, end=",")
In [355]:
print_primes(100)
1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,

recap list slicing

In [356]:
numbers = list(range(10))
In [357]:
numbers[1:6:1] #start at index 1 end at 6(exculsive) at step of 1
Out[357]:
[1, 2, 3, 4, 5]
In [358]:
numbers[1:6]
Out[358]:
[1, 2, 3, 4, 5]
In [360]:
numbers[:6] #starts at zero and ends at 6
Out[360]:
[0, 1, 2, 3, 4, 5]
In [361]:
numbers[6:] #starts at 6 ends at end
Out[361]:
[6, 7, 8, 9]
In [362]:
numbers[:100]
Out[362]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [363]:
numbers[::-1]
Out[363]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [364]:
numbers[:]
Out[364]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [365]:
numbers[:-1] # all except last
Out[365]:
[0, 1, 2, 3, 4, 5, 6, 7, 8]
In [367]:
numbers[:-2] # all till second last
Out[367]:
[0, 1, 2, 3, 4, 5, 6, 7]
In [368]:
word = "madam"
In [369]:
is_palindrome = lambda w : w==w[::-1]
In [370]:
is_palindrome(word)
Out[370]:
True

problem:

  • Write a function to find out even numbers from a list of numbers
    >>> evens([1,2,3,4,5,6,7,8,9])
    [2,4,6,8]
  • Write a function split_at which will split given list in two parts, one before given index and one after the index
    >>> split_at([0,1,2,3,4,5,6,7,8], 2)
    ([0,1], [2,3,4,5,6,7,8])
  • write a function find_extension to find extension of a file, given file name.
    >>> find_extension("python.exe")
    exe
In [371]:
def evens(numbers):
    evens_ = []
    for n in numbers:
        if n%2 == 0:
            evens_.append(n)
    return evens_
In [373]:
evens(range(20))
Out[373]:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
In [374]:
def split_at(items, index):
    return items[:index], items[index:]
In [375]:
def find_extension(filename):
    return filename.split(".")[-1]
In [376]:
find_extension("anaconda.tar.gz")
Out[376]:
'gz'
In [ ]: