Python Training at Arcesium - Day 1

Oct 25-27, 2017 Vikrant Patil

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

© Pipal Academy LLP

Day 1 | Day 2 | Day 3

In [1]:
2 + 3
Out[1]:
5
In [2]:
x = 3
In [3]:
x
Out[3]:
3
In [4]:
x
Out[4]:
3
In [5]:
print(x)
3
In [6]:
name = "Krishna"
In [7]:
print(name)
Krishna
In [8]:
raga = input()
asawary
In [10]:
print(raga)
asawary
In [11]:
print("Hello", name)
Hello Krishna

Basic data types

There are integers

In [13]:
2 + 2
Out[13]:
4
In [14]:
2 * 2
Out[14]:
4
In [15]:
2 - 4
Out[15]:
-2
In [16]:
2 ** 5
Out[16]:
32
In [17]:
8 % 2
Out[17]:
0
In [21]:
2 ** 1000 # integers can be big!
Out[21]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [19]:
5 / 2
Out[19]:
2.5
In [20]:
5 // 2
Out[20]:
2

Python has floats

In [22]:
0.0001 + 1
Out[22]:
1.0001

Python has string

In [23]:
first = "Rupali"
In [24]:
second = "Rupak"
In [25]:
print(first, second)
Rupali Rupak
In [27]:
name = first + " " + second
In [28]:
print(name)
Rupali Rupak
In [29]:
name = "Rupali" "Rupak"
In [30]:
name
Out[30]:
'RupaliRupak'
In [31]:
five = str(5)
In [32]:
print(five)
5
In [33]:
five
Out[33]:
'5'
In [34]:
star = "*"
In [36]:
rating = star *5
In [37]:
rating
Out[37]:
'*****'
In [38]:
print("="*30)
==============================
In [44]:
twolines = "first\nsecond\nthird"
In [42]:
print(twolines)
first
second
third
In [43]:
multiline = """
first
second
third
"""
In [45]:
print(multiline)
first
second
third

In [46]:
s = "what's your name?"
In [47]:
print(s)
what's your name?
In [48]:
singlequote = 'in this string i can put double "'
In [49]:
print(singlequote)
in this string i can put double "
In [50]:
multi = '''
multiline
with 
signle quote
'''
In [51]:
print(multi)
multiline
with 
signle quote

In [52]:
regional = "आ ष"
In [53]:
print(regional)
आ ष
In [54]:
print("\u0c85\u0c86")
ಅಆ

Python has binary data reprersentation as bytes

In [55]:
binary = b'binary'
In [56]:
print(binary)
b'binary'
In [57]:
hex(ord("b"))
Out[57]:
'0x62'
In [58]:
binary  = b'\x62\x69\x6e\x61\x72\x79'
In [59]:
print(binary)
b'binary'

There are special high level data types like list

In [63]:
letters = ['x','y','z']
In [64]:
letters[0]
Out[64]:
'x'
In [65]:
letters[1]
Out[65]:
'y'
In [66]:
letters[2]
Out[66]:
'z'
In [67]:
len(letters)
Out[67]:
3
In [68]:
ones = [1, 1, 1, 1]
In [69]:
moreones = ones + ones
In [70]:
moreones
Out[70]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [73]:
stillmoreones = ones * 5
In [74]:
stillmoreones
Out[74]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [75]:
mixedtypes = ["one", "two", 1, 2]
In [76]:
mixedtypes
Out[76]:
['one', 'two', 1, 2]
In [77]:
mixedtypes[0] = "zero"
In [78]:
mixedtypes
Out[78]:
['zero', 'two', 1, 2]

List has special mechanism to index various items

In [79]:
topten = [0,1,2,3,4,5,6,7,8,9]
In [80]:
topten[-1]
Out[80]:
9
In [81]:
topten[-2]
Out[81]:
8
In [82]:
print(topten)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [84]:
topten[:2]  #take first two elements
Out[84]:
[0, 1]
In [85]:
topten[2:] # drop first two elements
Out[85]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [86]:
head = topten[:2]
In [87]:
print(head)
[0, 1]
In [88]:
tail = topten[2:]
In [89]:
print(tail)
[2, 3, 4, 5, 6, 7, 8, 9]
In [90]:
tail
Out[90]:
[2, 3, 4, 5, 6, 7, 8, 9]
In [91]:
topten
Out[91]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [92]:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
In [94]:
matrix[0] # 0th row
Out[94]:
[1, 2, 3]
In [95]:
matrix[1] # 1st row
Out[95]:
[4, 5, 6]
In [96]:
matrix[0][-1] # last element in 0th row
Out[96]:
3
In [97]:
matrix[-1]
Out[97]:
[7, 8, 9]
In [98]:
matrix[0] = [7,8,9]
In [99]:
matrix
Out[99]:
[[7, 8, 9], [4, 5, 6], [7, 8, 9]]

There is another datatype similar to lists...called tuple ..

In [100]:
point = (1.1, 2.0)
In [101]:
print(point)
(1.1, 2.0)
In [102]:
triangle = ((0,0), (0,1), (1,1))
In [103]:
triangle[0] = (0,0.5)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-103-8608e9339ebf> in <module>()
----> 1 triangle[0] = (0,0.5)

TypeError: 'tuple' object does not support item assignment
In [104]:
ones = (1,1,1)
In [105]:
ones*5
Out[105]:
(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
In [106]:
ones + ones
Out[106]:
(1, 1, 1, 1, 1, 1)
In [107]:
manyobjects = ((1,1,1), "one", ('a','b','c'))
In [108]:
t = (1,2,3, (1,1,1), [0,0,0])
In [109]:
t[2]
Out[109]:
3
In [110]:
t[4]
Out[110]:
[0, 0, 0]
In [111]:
t[4] = [3,4,5]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-111-a8406b5489df> in <module>()
----> 1 t[4] = [3,4,5]

TypeError: 'tuple' object does not support item assignment
In [112]:
t[4][0] = 1
In [113]:
t
Out[113]:
(1, 2, 3, (1, 1, 1), [1, 0, 0])
In [114]:
t[:2]
Out[114]:
(1, 2)
In [115]:
t[2:]
Out[115]:
(3, (1, 1, 1), [1, 0, 0])
In [116]:
t[-1]
Out[116]:
[1, 0, 0]

Dictionary is named collection of objects

In [117]:
data = {"one":1, "two":2, "three":3}
In [118]:
data["one"]
Out[118]:
1
In [120]:
machine = {"name":"mozart", "os":"mint", "brand":"acer"}
In [121]:
machine['name']
Out[121]:
'mozart'
In [122]:
machine['os']
Out[122]:
'mint'
In [123]:
d = {"names":["alice", "alex","david"]}
In [124]:
d['names']
Out[124]:
['alice', 'alex', 'david']

Set

In [128]:
paragraph = """
1 some random text
2 to see how many english aphabets 
3 are being used while writing this
4 if I have some numbers in it 
"""
In [129]:
set(paragraph)
Out[129]:
{'\n',
 ' ',
 '1',
 '2',
 '3',
 '4',
 'I',
 'a',
 'b',
 'd',
 'e',
 'f',
 'g',
 'h',
 'i',
 'l',
 'm',
 'n',
 'o',
 'p',
 'r',
 's',
 't',
 'u',
 'v',
 'w',
 'x',
 'y'}
In [130]:
set([1,2,1,1,2,3])
Out[130]:
{1, 2, 3}

And of course there are booleans

In [131]:
sure  = True
arrr = False
In [132]:
print(sure, arrr)
True False

There is one more type for nothing

In [133]:
nothing = None
In [134]:
print(nothing)
None

Do it yourself

  • What is the difference in output of interpreter and output of print function for following case?
    s = "Just to make sure , \nthat you understand new line"
    s
    print(s)
  • will this work?
    pre  = "Isac"
    post = "Asimov"
    name = pre post
In [142]:
p = "Isac"
post = "Asimove"
together = p post
  File "<ipython-input-142-f04b22fac1c7>", line 3
    together = p post
                    ^
SyntaxError: invalid syntax
In [141]:
print(name)
RupaliRupak
In [135]:
s = "some value\n another value"
In [136]:
s
Out[136]:
'some value\n another value'
In [137]:
print(s)
some value
 another value

Functions

In [143]:
len("Python")
Out[143]:
6
In [144]:
len([1,2,3,4,5])
Out[144]:
5
In [145]:
len((1,2,3,4,5,56))
Out[145]:
6
In [146]:
len({"jan":31, "feb":28,"Mar":31})
Out[146]:
3
In [147]:
4 + int("2")
Out[147]:
6
In [149]:
str(4) + "2"
Out[149]:
'42'

Problem Using the function we know as of now, find number of digits in a given number. lets say 2 ** 100

In [150]:
digits = str(2**100)
In [151]:
digits
Out[151]:
'1267650600228229401496703205376'
In [152]:
len(digits)
Out[152]:
31

Custom functions

In [154]:
def square(x):
    v = x *x
    return v

print(square(4))
16
In [155]:
def say_hello(name):
    print("hello", name)
In [156]:
say_hello("Python")
hello Python
In [157]:
value = square(5)
In [158]:
print(value)
25
In [159]:
value = say_hello("Hari")
hello Hari
In [160]:
print(value)
None

Do it yourself

  • Write a function count_digits to count number of digits in given number. it should work as given below
    >>> count_digits(2*100)
    31
  • Before trying following code in interpreter , guess what will be output?
def twice(x):
    return 2*x

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

twice(twice(3))
twice1(twice1(3))
In [161]:
def twice1(x):
    print(2*x)

def twice(x):
    return 2*x
In [162]:
v = twice(3)
In [163]:
v
Out[163]:
6
In [164]:
v1 = twice1(3)
6
In [165]:
print(v1)
None
In [166]:
twice1(None)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-166-d7c6acf71719> in <module>()
----> 1 twice1(None)

<ipython-input-161-ba865fe1e32f> in twice1(x)
      1 def twice1(x):
----> 2     print(2*x)
      3 
      4 def twice(x):
      5     return 2*x

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [168]:
def count_digits(number):
    digits = str(number)
    return len(digits)
In [170]:
count_digits(2**1000)
Out[170]:
302

More about functions

Functions in python are ordinary just like any ohter data type like integers, floats, lists... But that makes them special

In [171]:
def func(x):
    return 2*x
In [172]:
func
Out[172]:
<function __main__.func>
In [173]:
print(func)
<function func at 0x7fa3140d7510>
In [174]:
type(func)
Out[174]:
function
In [175]:
type(4)
Out[175]:
int
In [176]:
type([1,2,3,4])
Out[176]:
list
In [177]:
twotimes = func
In [178]:
func(5)
Out[178]:
10
In [179]:
twotimes(5)
Out[179]:
10
In [180]:
twotimes
Out[180]:
<function __main__.func>
In [181]:
type(twotimes)
Out[181]:
function
In [182]:
def sumation(x, y):
    return x + y
In [183]:
def square(x):
    return x*x

def sumofsquares(x,y):
    return square(x) + square(y)
In [184]:
def cube(x):
    return x*x*x

def sumofcubes(x,y):
    return cube(x) + cube(y)
In [185]:
def sumof(f, x, y):
    return f(x) + f(y)
In [186]:
sumofsquares(5,6)
Out[186]:
61
In [187]:
sumof(square, 5, 6)
Out[187]:
61
In [188]:
def make_adder(y):
    def add(x):
        return x+y
    
    return add
In [189]:
adder5 = make_adder(5)
In [190]:
adder5
Out[190]:
<function __main__.make_adder.<locals>.add>
In [191]:
adder5(8)
Out[191]:
13
In [192]:
adder5(9)
Out[192]:
14
In [193]:
adder6 = make_adder(6)
In [194]:
adder6(9)
Out[194]:
15
In [195]:
def f(a):
    return a+a
In [196]:
f
Out[196]:
<function __main__.f>
In [197]:
adder6 = make_adder(6)
In [198]:
adder6
Out[198]:
<function __main__.make_adder.<locals>.add>
In [199]:
adder6(7)
Out[199]:
13
In [200]:
def add(x,y):
    return x+y
In [201]:
f = lambda x,y: x+y
In [202]:
f
Out[202]:
<function __main__.<lambda>>
In [203]:
f(4,5)
Out[203]:
9
In [204]:
def make_adder(y):
    return lambda x : x+y
In [205]:
adder7 = make_adder(7)
In [206]:
adder7(10)
Out[206]:
17
In [207]:
print(f)
<function <lambda> at 0x7fa31407c268>
In [208]:
type(f)
Out[208]:
function

Passing functions as parameter is so usefull, that in built python functions make use of it at many places

In [209]:
max(0,42)
Out[209]:
42
In [210]:
max([0,1,2,3,5])
Out[210]:
5
In [211]:
max(["one", "two", "three", "four"])# what would be output?
Out[211]:
'two'
In [215]:
words = ["one", "two", "three", "four"]
In [216]:
max(words, key=len)# this is how I find longest word
Out[216]:
'three'
In [217]:
min(words, key=len) #this is how I find shortest word
Out[217]:
'one'
In [218]:
scoresheet = [("vinay",8.8),
              ("vijay",8.9),
              ("vijaya",9.0),
              ("vilas",7.8),
              ("vishakha",9.1)
             ]
In [219]:
scoresheet
Out[219]:
[('vinay', 8.8),
 ('vijay', 8.9),
 ('vijaya', 9.0),
 ('vilas', 7.8),
 ('vishakha', 9.1)]
In [220]:
def get_score(record):
    return record[1]
In [221]:
max(scoresheet, key=get_score)
Out[221]:
('vishakha', 9.1)
In [222]:
min(scoresheet, key=get_score)
Out[222]:
('vilas', 7.8)
In [223]:
max(scoresheet, key=get_score)[0]
Out[223]:
'vishakha'
In [224]:
max(scoresheet, key=get_score)[1]
Out[224]:
9.1

Methods from objects

Built in obejcts have udefull functions built in as part of object itself. These functions are called methods

In [226]:
book = "Alice in wonderland"
In [227]:
book.lower()
Out[227]:
'alice in wonderland'
In [228]:
book.upper()
Out[228]:
'ALICE IN WONDERLAND'
In [229]:
book.count("n")
Out[229]:
3
In [230]:
book.split(" ")
Out[230]:
['Alice', 'in', 'wonderland']
In [231]:
book.replace(" ", "_")
Out[231]:
'Alice_in_wonderland'
In [232]:
book
Out[232]:
'Alice in wonderland'
In [233]:
book.replace(" ","_").split("_")
Out[233]:
['Alice', 'in', 'wonderland']
In [234]:
book.startswith("Alice")
Out[234]:
True
In [235]:
book.endswith("land")
Out[235]:
True

lists

In [237]:
numbers = list(range(5, 25, 2))
In [238]:
numbers
Out[238]:
[5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
In [239]:
numbers.count(5)
Out[239]:
1
In [240]:
numbers.reverse()
In [241]:
numbers
Out[241]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [242]:
numbers.append(3)
In [243]:
numbers
Out[243]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5, 3]
In [244]:
numbers.pop()
Out[244]:
3
In [245]:
numbers
Out[245]:
[23, 21, 19, 17, 15, 13, 11, 9, 7, 5]
In [246]:
numbers.pop(0)
Out[246]:
23
In [247]:
numbers
Out[247]:
[21, 19, 17, 15, 13, 11, 9, 7, 5]
In [248]:
numbers.sort()
In [249]:
numbers
Out[249]:
[5, 7, 9, 11, 13, 15, 17, 19, 21]
In [250]:
numbers.sort(reverse=True)
In [251]:
numbers
Out[251]:
[21, 19, 17, 15, 13, 11, 9, 7, 5]
In [252]:
words = ["One","two","Three"]
In [253]:
max(words, key=lambda w:w.lower())
Out[253]:
'two'
In [254]:
sorted(numbers, key=lambda x:x, reverse=True)
Out[254]:
[21, 19, 17, 15, 13, 11, 9, 7, 5]
In [255]:
numbers.extend([3,1])
In [256]:
numbers
Out[256]:
[21, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]
In [257]:
numbers.index(15)
Out[257]:
3

tuples

In [258]:
numbers = (1,1,2,3,5,8)
In [259]:
numbers.count(1)
Out[259]:
2
In [260]:
numbers.index(3)
Out[260]:
3

problem

  • Write a function count_zeros which will count zeros in given number
>>> count_zeros(1000)
3
  • Write a function head that takes a list of words and n as an argument and returns first n words by dictionary order
head(["python", "lisp", "haskell", "ark", "java", "ocamel"], 3)
['ark', 'haskell', 'java']

bonus problem

  • write a function rearrangemax that takes an integer as an argument and returns a new integer with digits rearranged from max to min.
    rearrangemax(43567)
    76543
In [262]:
def count_zeros(n):
    return str(n).count("0")
In [263]:
count_zeros(1000)
Out[263]:
3
In [264]:
def head(data, n):
    return sorted(data)[:n]
    
In [265]:
head(["python", "lisp", "haskell", "ark", "java", "ocamel"],3)
Out[265]:
['ark', 'haskell', 'java']
In [268]:
def rearragemax(n):
    digits = str(n)
    sorteddigits = sorted(digits, key=int, reverse=True)
    return int("".join(sorteddigits))
In [269]:
rearragemax(343524)
Out[269]:
544332

modules

In [282]:
import math

def area_circle(radius):
    return math.pi*radius*radius

def polar_to_rectangular(radius, theta):
    return radius*math.cos(theta), radius*math.sin(theta)
In [271]:
area_circle(1)
Out[271]:
3.141592653589793
In [284]:
x, y = polar_to_rectangular(1, math.pi/2)
In [285]:
print(x, y)
6.123233995736766e-17 1.0
In [272]:
import os
In [273]:
os.getcwd()
Out[273]:
'/home/vikrant/trainings/2017/arcesium-oct-python'
In [275]:
os.getenv("HOME")
Out[275]:
'/home/vikrant'
In [276]:
os.mkdir("/tmp/test1")
In [277]:
!ls /tmp/
config-err-tgKHDJ
firefox_vikrant
mintUpdate
ssh-oQgxr2OpAizg
systemd-private-f443c63d224a4f4d9e3c0415e5f622e1-colord.service-bEyWJv
systemd-private-f443c63d224a4f4d9e3c0415e5f622e1-rtkit-daemon.service-LW9Bft
test1
In [278]:
print(math)
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [279]:
os.listdir("/tmp/")
Out[279]:
['.XIM-unix',
 'systemd-private-f443c63d224a4f4d9e3c0415e5f622e1-colord.service-bEyWJv',
 '.font-unix',
 'systemd-private-f443c63d224a4f4d9e3c0415e5f622e1-rtkit-daemon.service-LW9Bft',
 'firefox_vikrant',
 'ssh-oQgxr2OpAizg',
 '.ICE-unix',
 '.X11-unix',
 'test1',
 '.X0-lock',
 '.Test-unix',
 'config-err-tgKHDJ',
 'mintUpdate']
In [280]:
math
Out[280]:
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [281]:
type(math)
Out[281]:
module
In [288]:
os.path.exists("/tmp")
Out[288]:
True
In [289]:
os.path.getsize("./day1.html")
Out[289]:
419342

problem

  • Write a function countfiles to find number of files in given directory.
    >>> countfiles("/tmp")
    13
  • Write a function biggestfile to find a file of maximum size in given directory.
    >>> biggestfile(os.getcwd())
    day1.html
In [290]:
def countfiles(location):
    return len(os.listdir(location))
In [299]:
def biggestfile(location):
    files = os.listdir(location)
    return max(files, key=os.path.getsize)
In [300]:
biggestfile(os.getcwd())
Out[300]:
'day1.html'

Writing cutom module

In [301]:
%%file mymodule.py
import sys

def say_hello(name):
    print("Hello", name)
Writing mymodule.py
In [302]:
import mymodule
In [303]:
mymodule.say_hello("Python")
Hello Python
In [304]:
%%file mymodule1.py
import sys

print(sys.argv)
Writing mymodule1.py
In [305]:
!python mymodule1.py arg1 arg2 arg3
['mymodule1.py', 'arg1', 'arg2', 'arg3']
In [309]:
%%file mymodule2.py
import sys

print(sys.argv)

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

def mult(x,y):
    return x*y

print(mult(3,4))
Overwriting mymodule2.py
In [310]:
!python mymodule2.py 
['mymodule2.py']
12
In [316]:
%%file circle.py
import sys

a = 3
pi = 3.14

def area(r):
    return pi*r*r

def perimeter(r):
    return 2*pi*r

radius = float(sys.argv[1])
print("Area of a circle :", area(radius))
print("Perimenter of a circle:", perimeter(radius))
Overwriting circle.py
In [315]:
!python circle.py 10 20
Area of a circle : 314.0
Perimenter of a circle: 62.800000000000004
In [317]:
%%file rectangle.py
import sys

def area(l, w):
    return l*w

def perimeter(l, w):
    return 2*(l+w)

length = float(sys.argv[1])
width = float(sys.argv[2])

print("Area of rectangle :", area(length, width))
print("Perimenter of rectangle:", perimeter(length, width))
Writing rectangle.py
In [318]:
!python rectangle.py 2 5
Area of rectangle : 10.0
Perimenter of rectangle: 14.0
In [319]:
import rectangle
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-319-4efccc52c587> in <module>()
----> 1 import rectangle

/home/vikrant/trainings/2017/arcesium-oct-python/rectangle.py in <module>()
      7     return 2*(l+w)
      8 
----> 9 length = float(sys.argv[1])
     10 width = float(sys.argv[2])
     11 

ValueError: could not convert string to float: '-f'
In [320]:
%%file main.py

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

def sub(x,y):
    return x-y

print(__name__)
Writing main.py
In [321]:
!python  main.py
__main__
In [322]:
import main
main
In [324]:
main.sub(3,4)
Out[324]:
-1
In [325]:
main.add(2,3)
Out[325]:
5
In [326]:
from main import add
In [327]:
from os.path import getsize
In [328]:
from math import pi
In [329]:
help(getsize)
Help on function getsize in module genericpath:

getsize(filename)
    Return the size of a file, reported by os.stat().

In [331]:
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.6/library/math
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

FUNCTIONS
    acos(...)
        acos(x)
        
        Return the arc cosine (measured in radians) of x.
    
    acosh(...)
        acosh(x)
        
        Return the inverse hyperbolic cosine of x.
    
    asin(...)
        asin(x)
        
        Return the arc sine (measured in radians) of x.
    
    asinh(...)
        asinh(x)
        
        Return the inverse hyperbolic sine of x.
    
    atan(...)
        atan(x)
        
        Return the arc tangent (measured in radians) of x.
    
    atan2(...)
        atan2(y, x)
        
        Return the arc tangent (measured in radians) of y/x.
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(...)
        atanh(x)
        
        Return the inverse hyperbolic tangent of x.
    
    ceil(...)
        ceil(x)
        
        Return the ceiling of x as an Integral.
        This is the smallest integer >= x.
    
    copysign(...)
        copysign(x, y)
        
        Return a float with the magnitude (absolute value) of x but the sign 
        of y. On platforms that support signed zeros, copysign(1.0, -0.0) 
        returns -1.0.
    
    cos(...)
        cos(x)
        
        Return the cosine of x (measured in radians).
    
    cosh(...)
        cosh(x)
        
        Return the hyperbolic cosine of x.
    
    degrees(...)
        degrees(x)
        
        Convert angle x from radians to degrees.
    
    erf(...)
        erf(x)
        
        Error function at x.
    
    erfc(...)
        erfc(x)
        
        Complementary error function at x.
    
    exp(...)
        exp(x)
        
        Return e raised to the power of x.
    
    expm1(...)
        expm1(x)
        
        Return exp(x)-1.
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(...)
        fabs(x)
        
        Return the absolute value of the float x.
    
    factorial(...)
        factorial(x) -> Integral
        
        Find x!. Raise a ValueError if x is negative or non-integral.
    
    floor(...)
        floor(x)
        
        Return the floor of x as an Integral.
        This is the largest integer <= x.
    
    fmod(...)
        fmod(x, y)
        
        Return fmod(x, y), according to platform C.  x % y may differ.
    
    frexp(...)
        frexp(x)
        
        Return the mantissa and exponent of x, as pair (m, e).
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(...)
        fsum(iterable)
        
        Return an accurate floating point sum of values in the iterable.
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(...)
        gamma(x)
        
        Gamma function at x.
    
    gcd(...)
        gcd(x, y) -> int
        greatest common divisor of x and y
    
    hypot(...)
        hypot(x, y)
        
        Return the Euclidean distance, sqrt(x*x + y*y).
    
    isclose(...)
        isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool
        
        Determine whether two floating point numbers are close in value.
        
           rel_tol
               maximum difference for being considered "close", relative to the
               magnitude of the input values
            abs_tol
               maximum difference for being considered "close", regardless of the
               magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(...)
        isfinite(x) -> bool
        
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(...)
        isinf(x) -> bool
        
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(...)
        isnan(x) -> bool
        
        Return True if x is a NaN (not a number), and False otherwise.
    
    ldexp(...)
        ldexp(x, i)
        
        Return x * (2**i).
    
    lgamma(...)
        lgamma(x)
        
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x[, base])
        
        Return the logarithm of x to the given base.
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(...)
        log10(x)
        
        Return the base 10 logarithm of x.
    
    log1p(...)
        log1p(x)
        
        Return the natural logarithm of 1+x (base e).
        The result is computed in a way which is accurate for x near zero.
    
    log2(...)
        log2(x)
        
        Return the base 2 logarithm of x.
    
    modf(...)
        modf(x)
        
        Return the fractional and integer parts of x.  Both results carry the sign
        of x and are floats.
    
    pow(...)
        pow(x, y)
        
        Return x**y (x to the power of y).
    
    radians(...)
        radians(x)
        
        Convert angle x from degrees to radians.
    
    sin(...)
        sin(x)
        
        Return the sine of x (measured in radians).
    
    sinh(...)
        sinh(x)
        
        Return the hyperbolic sine of x.
    
    sqrt(...)
        sqrt(x)
        
        Return the square root of x.
    
    tan(...)
        tan(x)
        
        Return the tangent of x (measured in radians).
    
    tanh(...)
        tanh(x)
        
        Return the hyperbolic tangent of x.
    
    trunc(...)
        trunc(x:Real) -> Integral
        
        Truncates x to the nearest Integral toward 0. Uses the __trunc__ magic method.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so


In [332]:
help(circle)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-332-ba8c55c95943> in <module>()
----> 1 help(circle)

NameError: name 'circle' is not defined
In [333]:
help(main)
Help on module main:

NAME
    main

FUNCTIONS
    add(x, y)
    
    sub(x, y)

FILE
    /home/vikrant/trainings/2017/arcesium-oct-python/main.py


In [335]:
import random
In [336]:
help(random.choice)
Help on method choice in module random:

choice(seq) method of random.Random instance
    Choose a random element from a non-empty sequence.

In [337]:
sentence = "The beauty of pascal trianlge is that it is simple yet mathematically rich"
In [338]:
random.choice(sentence.split())
Out[338]:
'it'
In [339]:
random.choice(sentence.split())
Out[339]:
'it'
In [340]:
help("".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.

problems

  • Write a python script square.py which takes an integer as an argument and prints square of that number
  • Write a python script add.py which takes two integers from commandline and prints addition of those numbers
  • Write a python script echo.py which is roughly equivalent to unix command echo. echo just prints the input string to standard output
In [341]:
%%file square.py
import sys

def square(x):
    return x*x

n = int(sys.argv[1])
print(square(n))
Writing square.py
In [342]:
!python square.py 4
16
In [343]:
%%file add.py
import sys

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

a = int(sys.argv[1])
b = int(sys.argv[2])
print(add(a,b))
Writing add.py
In [344]:
!python add.py 5 6
11
In [347]:
%%file echo.py
import sys

print(" ".join(sys.argv[1:]))
Overwriting echo.py
In [348]:
!python echo.py hello this is echo
hello this is echo

Environment

In [350]:
a = 2.0 + 3.0
In [351]:
a
Out[351]:
5.0
In [352]:
import math
In [353]:
import math as m
In [354]:
m
Out[354]:
<module 'math' from '/home/vikrant/usr/local/anaconda3/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'>
In [356]:
cash = 10000
balance = 50000

def withdraw(balance, amount):
    balance = balance - amount
    return balance

cash = withdraw(balance, 1000)
print("balance = ", balance)
print("cash =", cash)

withdraw(60000, 2000)
print(balance)
balance =  50000
cash = 49000
50000

Conditions

In [357]:
1 > 2
Out[357]:
False
In [358]:
1.99 <= 2.0
Out[358]:
True
In [359]:
2 != 3
Out[359]:
True
In [360]:
2 <= 2
Out[360]:
True
In [362]:
"python" > "java"
Out[362]:
True
In [363]:
"alice" in "alice in wonderland"
Out[363]:
True
In [364]:
"alice" not in "alice in wonderland"
Out[364]:
False
In [365]:
book = "alice in wonderland"
In [366]:
book.startswith("alice")
Out[366]:
True
In [367]:
book.endswith("land")
Out[367]:
True
In [368]:
def is_python_script(filename):
    return filename.endswith(".py")
In [369]:
is_python_script("hello.py")
Out[369]:
True
In [370]:
python = [3.4, "if"]
if "if" in python:
    print("Obviously python has if")
elif python[0] > 3:
    print("python can have long list of elifs")
elif len(python) > 1:
    print("still ...long")
else:
    print("it will come here if none of above condition is True")
Obviously python has if
In [371]:
def even(n):
    if n%2 == 0:
        return True
    else:
        return False
In [372]:
even(5)
Out[372]:
False

The conditional after if is True for

  • For nonzero integer value
  • for object that is not None
  • for nonempty sequences
In [373]:
def even(n):
    return not n%2
In [374]:
even(2)
Out[374]:
True
In [375]:
def odd(n):
    return not even(n)
In [376]:
odd(3)
Out[376]:
True

Do it yourself

  • Write a python function filetype which will take filename as argument and return file type. it should recognise following file types. If filetype is not from given list , it should return None
    type     extension
    python   .py
    java     .java
    c        .c
    text     .txt
>>> filetype("square.py")
python
>>> filetype("square.txt")
text
  • Write a function minimum (without using in build function min) to find minimum of two numbers
    >>> minimum(3,4)
    3
  • write a function minimum3 to find minimum of three numbers
    minimum3(2,3,4)
    2
In [377]:
def minimum(a,b):
    if a < b:
        return a
    else:
        return b
    
def minimum3(x,y,z):
    return minimum(minimum(x,y), z)
In [378]:
minimum3(3,4,5)
Out[378]:
3
In [379]:
primes = [2,3,5,7,11,13,17]
In [380]:
5 in primes
Out[380]:
True
In [381]:
primes2 = primes
In [382]:
primes is primes2
Out[382]:
True
In [383]:
primes == primes2
Out[383]:
True
In [384]:
prime3 = list(primes)
In [385]:
prime3 == primes
Out[385]:
True
In [386]:
prime3 is primes
Out[386]:
False
In [387]:
a = "abcd"
In [388]:
b = a
In [389]:
a.replace("ab", "ef")
Out[389]:
'efcd'
In [390]:
a
Out[390]:
'abcd'
In [391]:
b
Out[391]:
'abcd'
In [392]:
a.sort()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-392-e7eb8b51a6fa> in <module>()
----> 1 a.sort()

AttributeError: 'str' object has no attribute 'sort'
In [ ]: