Python Foundation Training Day 1

by Vikrant Patil

at MIT Pune, IT Dept. Mar 12-16, 2018

Notes are available online at

https://notes.pipal.in/2018/mit-pune-march/

In [1]:
print("Hello World!")
Hello World!
In [2]:
name = input()
python
In [3]:
print(name)
python

Basic data types

There are integers

In [4]:
1 + 2
Out[4]:
3
In [5]:
2 -3
Out[5]:
-1
In [6]:
2 *3
Out[6]:
6
In [7]:
4/2
Out[7]:
2.0
In [8]:
5//2
Out[8]:
2
In [9]:
2 ** 3
Out[9]:
8
In [10]:
2 ** 100
Out[10]:
1267650600228229401496703205376
In [11]:
2 ** 1000
Out[11]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [12]:
5 % 2
Out[12]:
1

There are floats

In [13]:
2.3 + 3.4
Out[13]:
5.699999999999999

There are strings

In [14]:
name = "Rupali"
In [15]:
print(name)
Rupali
In [16]:
single = 'a string " quote inside it'
In [18]:
print(single)
a string " quote inside it
In [19]:
doublequotes = "a string with ' inside it"
In [20]:
print(doublequotes)
a string with ' inside it
In [21]:
name
Out[21]:
'Rupali'
In [22]:
surname = "Rupak"
In [23]:
name + surname
Out[23]:
'RupaliRupak'
In [24]:
x = "Rupali" "Rupak"
In [25]:
x
Out[25]:
'RupaliRupak'
In [27]:
star = "*"
In [28]:
star*5
Out[28]:
'*****'
In [29]:
"="*20
Out[29]:
'===================='
In [30]:
multiline = """
this is
multi line string 
with few 
lines in
it
"""
In [31]:
print(multiline)
this is
multi line string 
with few 
lines in
it

In [34]:
s = "sdkjfhsdkjfhdskhjgf sdjgsad dkjhfds gkjhdsfgkjhadfg ksdjhgfkjdshg kjdfhg dfkjghdfgkjdsfh g dfkghdfkjgh dsfkhkgjdsfh "
In [35]:
s
Out[35]:
'sdkjfhsdkjfhdskhjgf sdjgsad dkjhfds gkjhdsfgkjhadfg ksdjhgfkjdshg kjdfhg dfkjghdfgkjdsfh g dfkghdfkjgh dsfkhkgjdsfh '
In [36]:
print(multiline)
this is
multi line string 
with few 
lines in
it

In [37]:
multiline
Out[37]:
'\nthis is\nmulti line string \nwith few \nlines in\nit\n'
In [38]:
twolines = "one\ntwo\t2"
In [39]:
print(twolines)
one
two	2
In [40]:
name1 = "Rupali Rupak"
In [41]:
name1
Out[41]:
'Rupali Rupak'
In [42]:
"""one
two
three"""
Out[42]:
'one\ntwo\nthree'
In [43]:
unicode = "\u0c85"
In [44]:
print(unicode)
ಅ
In [45]:
regional = "आ ड ब"
In [46]:
regional
Out[46]:
'आ ड ब'
In [47]:
empty = ""
In [48]:
print(empty)

In [49]:
empty
Out[49]:
''

There are binary arrays

In [50]:
binary = b"This is binary string"
In [51]:
binary
Out[51]:
b'This is binary string'
In [52]:
binary1 = "\x056"
In [53]:
binary1
Out[53]:
'\x056'

There are higher level data types.. Lists

In [54]:
digits = [0,1,2,3,4,5,6,7,8,9]
In [55]:
print(digits)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [56]:
digits[0]
Out[56]:
0
In [57]:
digits[-1]
Out[57]:
9
In [58]:
digits[1:] # drop first
Out[58]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [62]:
digits[3:] #drop first 3
Out[62]:
[3, 4, 5, 6, 7, 8, 9]
In [61]:
digits[:3] # take first three
Out[61]:
[0, 1, 2]
In [63]:
ones = [1,1,1,1]
In [64]:
ones + ones
Out[64]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [65]:
firstthree = digits[:3]
In [66]:
firstthree
Out[66]:
[0, 1, 2]
In [67]:
digits
Out[67]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [68]:
ones
Out[68]:
[1, 1, 1, 1]
In [69]:
ones + ones
Out[69]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [70]:
ones * 5
Out[70]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [71]:
ones - ones
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-71-dd003c98adda> in <module>()
----> 1 ones - ones

TypeError: unsupported operand type(s) for -: 'list' and 'list'
In [72]:
ones * 1.2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-72-50c18fd420ad> in <module>()
----> 1 ones * 1.2

TypeError: can't multiply sequence by non-int of type 'float'
In [73]:
ones - 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-73-80d12b1d54e4> in <module>()
----> 1 ones - 1

TypeError: unsupported operand type(s) for -: 'list' and 'int'
In [74]:
mixed = ["ones", "two", 1, 2, 3]
In [75]:
mixed
Out[75]:
['ones', 'two', 1, 2, 3]
In [77]:
m = [[1,2,3],[4,5,6],[7,8,9]]
In [81]:
m[0] # 0th row
Out[81]:
[1, 2, 3]
In [82]:
m[-1] # last row
Out[82]:
[7, 8, 9]
In [83]:
m[0][2] #2nd element from 0th row
Out[83]:
3
In [84]:
ones 
Out[84]:
[1, 1, 1, 1]
In [85]:
ones[0]
Out[85]:
1
In [86]:
ones[0] = 0
In [87]:
ones
Out[87]:
[0, 1, 1, 1]
In [88]:
ones[0] = 1

tuples .. sibling of lists

In [89]:
t = (0,1,2,3,4)
In [90]:
t + t
Out[90]:
(0, 1, 2, 3, 4, 0, 1, 2, 3, 4)
In [91]:
t * 4
Out[91]:
(0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4)
In [92]:
t[0]
Out[92]:
0
In [93]:
t[-1]
Out[93]:
4
In [94]:
t[2:]
Out[94]:
(2, 3, 4)
In [95]:
t[0] = 1
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-95-0a69537257d5> in <module>()
----> 1 t[0] = 1

TypeError: 'tuple' object does not support item assignment
In [96]:
origin = (0,0)
In [97]:
origin[0] = 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-97-415448be37c7> in <module>()
----> 1 origin[0] = 2

TypeError: 'tuple' object does not support item assignment

Dictionaries

In [98]:
person = {"name":"alice", "email":"alice@wonder.land", 
          "place":"wonmderland", "PIN":42}
In [99]:
person
Out[99]:
{'PIN': 42,
 'email': 'alice@wonder.land',
 'name': 'alice',
 'place': 'wonmderland'}
In [100]:
person["name"]
Out[100]:
'alice'
In [101]:
person["place"]
Out[101]:
'wonmderland'
In [102]:
person['email']
Out[102]:
'alice@wonder.land'
In [103]:
person
Out[103]:
{'PIN': 42,
 'email': 'alice@wonder.land',
 'name': 'alice',
 'place': 'wonmderland'}
In [104]:
person["PIN"]
Out[104]:
42
In [105]:
d = {"integer":2,
    "list":[1,2,3,4],
    "tuple":(1,2,3),
    2:"two"}
In [106]:
d
Out[106]:
{'integer': 2, 'list': [1, 2, 3, 4], 'tuple': (1, 2, 3), 2: 'two'}
In [107]:
person['PIN'],person['email']
Out[107]:
(42, 'alice@wonder.land')
In [108]:
x,y = 2,3

There are sets

In [119]:
s = {1,2,3}
In [120]:
sentence = """This is a randome statement from which we
will find out which english alphabets are used in this!"""
In [121]:
alphabets = set(sentence)
In [122]:
alphabets
Out[122]:
{'\n',
 ' ',
 '!',
 'T',
 'a',
 'b',
 'c',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'l',
 'm',
 'n',
 'o',
 'p',
 'r',
 's',
 't',
 'u',
 'w'}
In [ ]:
 

What will be output?

In [109]:
s = "first second \nthird"
In [110]:
print(s)
first second 
third
In [111]:
s
Out[111]:
'first second \nthird'
In [112]:
pre = "Isac"
post = "Asimove"
In [113]:
pre post
  File "<ipython-input-113-9f3396fba351>", line 1
    pre post
           ^
SyntaxError: invalid syntax
In [114]:
"Isac" "Asimove"
Out[114]:
'IsacAsimove'
In [116]:
{"key":{"one":1}}
Out[116]:
{'key': {'one': 1}}

Functions

In [123]:
len("what is length of this string")
Out[123]:
29
In [124]:
len([1,2,3,4,5])
Out[124]:
5
In [125]:
len((0,1,2,3,4))
Out[125]:
5
In [126]:
len(person)
Out[126]:
4
In [127]:
len(alphabets)
Out[127]:
23
In [128]:
int("43")
Out[128]:
43
In [129]:
int("A")
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-129-2e0b20450aad> in <module>()
----> 1 int("A")

ValueError: invalid literal for int() with base 10: 'A'
In [130]:
str(43)
Out[130]:
'43'
In [131]:
list((1,2,3,4))
Out[131]:
[1, 2, 3, 4]
In [132]:
t = (1,2,3,4)
In [133]:
l = list(t)
In [134]:
l
Out[134]:
[1, 2, 3, 4]
In [135]:
t
Out[135]:
(1, 2, 3, 4)
In [136]:
range(10)
Out[136]:
range(0, 10)
In [137]:
list(range(10))
Out[137]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [139]:
#list(range(100))
In [140]:
sum([1,2,3])
Out[140]:
6
In [141]:
sum(["one", "two", "three"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-141-40a4ca8389f8> in <module>()
----> 1 sum(["one", "two", "three"])

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [142]:
help(sum)
Help on built-in function sum in module builtins:

sum(iterable, start=0, /)
    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.

In [144]:
sum(["one", "two", "three"])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-144-83f2b8125102> in <module>()
----> 1 sum(["one", "two", "three"], "")

TypeError: sum() can't sum strings [use ''.join(seq) instead]
In [145]:
sum((1,2,3,4,5))
Out[145]:
15

problems

find number of digits in 2^1000

In [146]:
2**1000
Out[146]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [147]:
n = 2**1000
In [148]:
n
Out[148]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [149]:
digits = str(n)
In [150]:
digits
Out[150]:
'10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376'
In [151]:
len(digits)
Out[151]:
302
In [152]:
2 ** 100
Out[152]:
1267650600228229401496703205376
In [153]:
x = 2**100

Custom function

In [154]:
def add(x, y):
    s = x + y
    return s

def dummy():
    pass
In [155]:
def do_nothing():
    print("Print nothing")
    s = 2 +3
    
def twice(x):
    return 2*x
In [156]:
add(2,3)
Out[156]:
5
In [157]:
dummy()
In [158]:
twice(3)
Out[158]:
6
In [159]:
do_nothing()
Print nothing
In [ ]:
 

problem

  • Write a function count_digits which counts number of digits from given number
  • Write a function sum_natural to find sum of first n natural numbers
In [160]:
def twice(x):
    return 2*x

def twice1(x):
    print(2*x)
    

What will be output of

print(twice(twice(3)))

What will be output of

print(twice1(twice1(4)))
In [161]:
a = add(2,3)
In [162]:
print(a)
5
In [163]:
def dummy():
    pass
In [164]:
r = dummy()
In [165]:
print(r)
None
In [166]:
r
In [169]:
def twice(x):
    return 2*x

def twice1(x):
    print(2*x)
    
In [167]:
twice(3)
Out[167]:
6
In [168]:
twice1(4)
8
In [170]:
t = twice(3)
In [171]:
print(t)
6
In [172]:
t1 = twice1(4)
8
In [173]:
t1
In [174]:
print(t1)
None

More about functions

In [175]:
x = 2
In [176]:
x
Out[176]:
2
In [177]:
def fun(x):
    return 3*x
In [178]:
fun
Out[178]:
<function __main__.fun>
In [179]:
print(x)
2
In [180]:
print(fun)
<function fun at 0x7f19b84cfd08>
In [181]:
y = x
In [182]:
print(y)
2
In [183]:
aliasfun = fun
In [184]:
print(aliasfun)
<function fun at 0x7f19b84cfd08>
In [185]:
print(fun)
<function fun at 0x7f19b84cfd08>
In [186]:
fun(3)
Out[186]:
9
In [187]:
aliasfun(4)
Out[187]:
12
In [188]:
def sqaure(x):
    return x*x

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

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

def sumofcubes(x,y):
    return cube(x) + cube(y)
In [189]:
def sumof(f, x , y):
    return f(x) + f(y)
In [190]:
sumofsquares(2,3)
Out[190]:
13
In [191]:
sumof(sqaure, 2, 3)
Out[191]:
13
In [192]:
sumofcubes(2,3)
Out[192]:
35
In [193]:
sumof(cube, 2, 3)
Out[193]:
35
In [194]:
def make_adder(x):
    def adder(y):
        return x+y
    
    return adder
In [195]:
adder5 = make_adder(5)
In [196]:
adder5
Out[196]:
<function __main__.make_adder.<locals>.adder>
In [197]:
type(adder5)
Out[197]:
function
In [198]:
adder5(6)
Out[198]:
11
In [199]:
adder5(7)
Out[199]:
12
In [200]:
adder4 = make_adder(4)
In [201]:
adder4(5)
Out[201]:
9
In [202]:
sum3 = lambda x,y,z : x+y+z
In [203]:
sum3(2,3,4)
Out[203]:
9

problem

  • Using lambda expression write above function make_adder
In [204]:
def make_adder(x):
    return lambda y: x+y
In [205]:
max([3,4,51,2,3,4])
Out[205]:
51
In [206]:
max(["one","two","three","four","five"])
Out[206]:
'two'
In [207]:
words = ["one","two","three","four","five"]
In [208]:
max(words)
Out[208]:
'two'
In [209]:
max(words, key=len)
Out[209]:
'three'
In [211]:
records = [
    ("A", 7.8),
    ("B", 8.7),
    ("C", 7.0),
    ("D", 5.5),
    ("E", 7.7)
]
In [212]:
records
Out[212]:
[('A', 7.8), ('B', 8.7), ('C', 7.0), ('D', 5.5), ('E', 7.7)]
In [213]:
max(records)
Out[213]:
('E', 7.7)
In [214]:
def get_score(t):
    return t[1]
In [215]:
max(records, key=get_score)
Out[215]:
('B', 8.7)
In [216]:
min(records)
Out[216]:
('A', 7.8)
In [217]:
min(records, key=get_score)
Out[217]:
('D', 5.5)
In [218]:
sorted(records, key=get_score)
Out[218]:
[('D', 5.5), ('C', 7.0), ('E', 7.7), ('A', 7.8), ('B', 8.7)]
In [219]:
sorted(words, key=len)
Out[219]:
['one', 'two', 'four', 'five', 'three']
In [220]:
sorted(words)
Out[220]:
['five', 'four', 'one', 'three', 'two']
In [221]:
sorted(records, key=lambda r:r[1])
Out[221]:
[('D', 5.5), ('C', 7.0), ('E', 7.7), ('A', 7.8), ('B', 8.7)]

Methods from objects

Strings

In [222]:
s = "Some random statement"
In [223]:
s.lower()
Out[223]:
'some random statement'
In [224]:
s.upper()
Out[224]:
'SOME RANDOM STATEMENT'
In [225]:
s.count("e")
Out[225]:
3
In [226]:
s.split(" ")
Out[226]:
['Some', 'random', 'statement']
In [227]:
s.split()
Out[227]:
['Some', 'random', 'statement']
In [228]:
words 
Out[228]:
['one', 'two', 'three', 'four', 'five']
In [229]:
"_".join(words)
Out[229]:
'one_two_three_four_five'
In [230]:
"/".join(["","home","vikrant", "trainings","2018"])
Out[230]:
'/home/vikrant/trainings/2018'
In [231]:
" ".join(words)
Out[231]:
'one two three four five'
In [232]:
trailingspces = "   jdkslfd kjdhsfkjhsd kjhfsdkfh      "
In [233]:
trailingspces.strip()
Out[233]:
'jdkslfd kjdhsfkjhsd kjhfsdkfh'
In [234]:
"Wizard of oz was lisp".replace("lisp", "python")
Out[234]:
'Wizard of oz was python'
In [235]:
filename = "hello.py"
In [236]:
filename.startswith("hello")
Out[236]:
True
In [237]:
filename.endswith(".py")
Out[237]:
True
In [238]:
s.center(50)
Out[238]:
'              Some random statement               '
In [239]:
s.rjust(50)
Out[239]:
'                             Some random statement'
In [240]:
s.ljust(50)
Out[240]:
'Some random statement                             '

Lists

In [241]:
numbers = list(range(10))
In [242]:
numbers
Out[242]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [243]:
numbers.count(0)
Out[243]:
1
In [244]:
ones.count(1)
Out[244]:
4
In [246]:
ones
Out[246]:
[1, 1, 1, 1]
In [247]:
numbers.append(10)
In [248]:
numbers
Out[248]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In [249]:
numbers.pop()
Out[249]:
10
In [250]:
numbers
Out[250]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [251]:
numbers.pop(0)
Out[251]:
0
In [252]:
numbers
Out[252]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [253]:
numbers.insert(0, -1)
In [254]:
numbers
Out[254]:
[-1, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [255]:
numbers.pop()
Out[255]:
9
In [256]:
numbers.pop(0)
Out[256]:
-1
In [257]:
numbers
Out[257]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [258]:
numbers.sort()
In [259]:
numbers
Out[259]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [260]:
numbers.sort(reverse=True)
In [261]:
numbers
Out[261]:
[8, 7, 6, 5, 4, 3, 2, 1]
In [262]:
numbers.reverse()
In [263]:
numbers
Out[263]:
[1, 2, 3, 4, 5, 6, 7, 8]
In [264]:
words
Out[264]:
['one', 'two', 'three', 'four', 'five']
In [265]:
words.sort(key=len)
In [266]:
words
Out[266]:
['one', 'two', 'four', 'five', 'three']
In [267]:
sorted(words, key=len, reverse=True)
Out[267]:
['three', 'four', 'five', 'one', 'two']
In [268]:
words.extend(["six", "seven"])
In [269]:
words
Out[269]:
['one', 'two', 'four', 'five', 'three', 'six', 'seven']

problem

  • Write a function count_zeros which counts number of zeros in given number
    >>> count_zeros(1000)
    3
  • Write a function head which returns first n elements from a list
    >>> head([1,2,3,4,5,6,7,8,9], 4)
    [1,2,3,4]
  • Write a function rearrangemax which rearranges digits of given number to form a max number out of it.
    >>> rearrangemax(5498)
    9854
In [270]:
sum = 6
In [271]:
sum([1,2,3])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-271-748a1806f572> in <module>()
----> 1 sum([1,2,3])

TypeError: 'int' object is not callable
In [272]:
del sum
In [273]:
sorted("hello world")
Out[273]:
[' ', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
In [274]:
def count_zeros(n):
    return str(n).count("0")

def head(items, n):
    return items[:n]

def rearrangemax(n):
    strn = str(n)
    orderd = sorted(strn, reverse=True)
    return int("".join(orderd))
In [275]:
count_zeros(10002)
Out[275]:
3
In [277]:
head([1,2,3,4,5,6,7], 3)
Out[277]:
[1, 2, 3]
In [278]:
rearrangemax(5678)
Out[278]:
8765
In [279]:
filename
Out[279]:
'hello.py'
In [281]:
i = filename.index(".")
In [286]:
filename[i+1:]
Out[286]:
'py'
In [287]:
filename.split(".")
Out[287]:
['hello', 'py']
In [288]:
filename.split(".")[-1]
Out[288]:
'py'

tuples

In [289]:
t = (1,1,1,1,0,0,0)
In [290]:
t.count(1)
Out[290]:
4
In [291]:
t.index(0)
Out[291]:
4
In [292]:
t.append(0)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-292-78592bf72d62> in <module>()
----> 1 t.append(0)

AttributeError: 'tuple' object has no attribute 'append'
In [293]:
t.sort()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-293-0708f4171c7e> in <module>()
----> 1 t.sort()

AttributeError: 'tuple' object has no attribute 'sort'

modules

In [294]:
import os
In [295]:
os
Out[295]:
<module 'os' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/os.py'>
In [296]:
type(os)
Out[296]:
module
In [297]:
os.getcwd()
Out[297]:
'/home/vikrant/trainings/2018/mit-pune-march'
In [298]:
os.listdir(os.getcwd())
Out[298]:
['.ipynb_checkpoints', 'day1.ipynb']
In [300]:
os.listdir("/home/")
Out[300]:
['mohini', 'lost+found', 'vikrant']
In [301]:
import math
In [302]:
math.pi
Out[302]:
3.141592653589793
In [304]:
math.sin(math.pi)
Out[304]:
1.2246467991473532e-16
In [305]:
from math import cos
In [306]:
cos(3.14)
Out[306]:
-0.9999987317275395
In [307]:
import math as m
In [308]:
m.pi
Out[308]:
3.141592653589793
In [309]:
m.sin(m.pi)
Out[309]:
1.2246467991473532e-16
In [310]:
del math
In [311]:
math
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-311-674f3def7873> in <module>()
----> 1 math

NameError: name 'math' is not defined
In [312]:
m
Out[312]:
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [313]:
m.pi
Out[313]:
3.141592653589793
In [314]:
cos
Out[314]:
<function math.cos>
In [315]:
from math import sin
In [316]:
sin(3.14)
Out[316]:
0.0015926529164868282
In [317]:
math
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-317-674f3def7873> in <module>()
----> 1 math

NameError: name 'math' is not defined
In [320]:
os.path.exists("/home")
Out[320]:
True
In [321]:
os.path.getsize("day1.ipynb")
Out[321]:
94690
In [322]:
os.listdir(os.getcwd())
Out[322]:
['.ipynb_checkpoints', 'day1.ipynb']
In [323]:
def count_files(path):
    return len(os.listdir(path))
In [324]:
count_files("/home/vikrant")
Out[324]:
63
In [325]:
count_files(".")
Out[325]:
2
In [326]:
os.mkdir("/tmp/xyz")
In [328]:
os.path.exists("/tmp/xyz")
Out[328]:
True
In [329]:
os.path.exists("/tmp/xyz1")
Out[329]:
False
In [330]:
True
Out[330]:
True
In [331]:
False
Out[331]:
False

problem

  • write a function biggestfile to find file with largest size from given directory
In [332]:
import os
def biggestfile(path):
    files = os.listdir(path)
    return max(files, key=os.path.getsize)
In [335]:
biggestfile(".")
Out[335]:
'day1.ipynb'

Custom modules

In [336]:
%%file module.py
x = 42

def square(x):
    return x*x

def mean(x,y):
    return  (x+y)/2

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


def say_hello(name):
    print("Hello ", name)
Writing module.py
In [337]:
import module
In [338]:
module.x
Out[338]:
42
In [339]:
module.square(43)
Out[339]:
1849
In [340]:
module.say_hello("python!")
Hello  python!
In [342]:
%%file module1.py
import sys

def say_hello(name):
    print("Hello ", name)
    
print(sys.argv)
Overwriting module1.py
In [343]:
!python module1.py MIT
['module1.py', 'MIT']
In [345]:
!python module1.py MIT ITDEPT PUNE
['module1.py', 'MIT', 'ITDEPT', 'PUNE']
In [346]:
%%file hello.py
import sys


def say_hello(name):
    print("Hello ", name)
    
say_hello(sys.argv[1])
Writing hello.py
In [347]:
!python hello.py MIT
Hello  MIT
In [ ]: