Basic Python Training at Arcesium - Day 1

Jun 03-04, 2019 Vikrant Patil

These notes are available online at http://notes.pipal.in/2019/arcesium_basic_jun/day1.html

© Pipal Academy LLP

Day 1 | Day 2

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

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

# Header1 #
## Header2 ##
### Header3 ###

Header1

Header2

Header3

Starting

In [1]:
2 + 4
Out[1]:
6
In [2]:
2 ** 100
Out[2]:
1267650600228229401496703205376

Data types

there are integers

In [3]:
2 + 2
Out[3]:
4
In [4]:
2 - 3
Out[4]:
-1
In [5]:
2 / 3
Out[5]:
0.6666666666666666
In [6]:
3 // 2
Out[6]:
1
In [7]:
2 * 3
Out[7]:
6
In [8]:
2 **100
Out[8]:
1267650600228229401496703205376
In [9]:
5 % 2
Out[9]:
1

there are floats

In [10]:
2.5
Out[10]:
2.5
In [11]:
3/5
Out[11]:
0.6
In [12]:
3 + 5.0
Out[12]:
8.0
In [13]:
3.0 ** 5
Out[13]:
243.0
In [14]:
3.0 ** 4.5
Out[14]:
140.29611541307906

there are strings

In [15]:
"This is a text data"
Out[15]:
'This is a text data'
In [16]:
"Hello" + " World!"
Out[16]:
'Hello World!'
In [17]:
"*"*5
Out[17]:
'*****'
In [18]:
"hello"*5
Out[18]:
'hellohellohellohellohello'
In [19]:
text = "This is some random text"
In [20]:
text[0]
Out[20]:
'T'
In [21]:
text[2]
Out[21]:
'i'
In [22]:
text[-1]
Out[22]:
't'

Indexing strings

->0  1  2  3  4  5
  p  y  t  h  o  n
 -6 -5 -4 -3 -2 -1 <-
In [23]:
multiline = """ line 1
line2
line3
line4
"""
In [24]:
print(multiline)
 line 1
line2
line3
line4

In [25]:
print(text)
This is some random text
In [26]:
import this
The Zen of Python, by Tim Peters

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

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

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

In [29]:
multi= "line1\nline2\nline3"
In [30]:
multi1 = """line1
line2
line3"""
In [31]:
print(multi)
line1
line2
line3
In [33]:
print(multi1)
line1
line2
line3
In [34]:
"he said, 'I am fine'"
Out[34]:
"he said, 'I am fine'"
In [35]:
"hello\""
Out[35]:
'hello"'
In [36]:
'hello"'
Out[36]:
'hello"'

There are lists

In [37]:
emptylist = []
In [38]:
numbers = [1, 2, 3, 4, 5, 6]
In [39]:
print(numbers)
[1, 2, 3, 4, 5, 6]
In [40]:
numbers[0]
Out[40]:
1
In [41]:
numbers[-1]
Out[41]:
6
In [42]:
ones = [1, 1, 1, 1]
In [43]:
ones + ones
Out[43]:
[1, 1, 1, 1, 1, 1, 1, 1]
In [44]:
ones
Out[44]:
[1, 1, 1, 1]
In [45]:
ones*4
Out[45]:
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
In [46]:
mixed = [1, 2, "data1", "python", 2.5]
In [47]:
mixed[-1]
Out[47]:
2.5
In [48]:
mixed
Out[48]:
[1, 2, 'data1', 'python', 2.5]
In [49]:
mixed = [ones, numbers, 1, 2, 3, 4]
In [50]:
mixed
Out[50]:
[[1, 1, 1, 1], [1, 2, 3, 4, 5, 6], 1, 2, 3, 4]
In [51]:
ones.append(0)
In [52]:
ones
Out[52]:
[1, 1, 1, 1, 0]
In [53]:
mixed
Out[53]:
[[1, 1, 1, 1, 0], [1, 2, 3, 4, 5, 6], 1, 2, 3, 4]

there are tuples, sibling of list

In [54]:
t = (1, 2, 3, 4)
In [55]:
t[0]
Out[55]:
1
In [56]:
t[-1]
Out[56]:
4
In [57]:
t+ t
Out[57]:
(1, 2, 3, 4, 1, 2, 3, 4)
In [58]:
t*3
Out[58]:
(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4)
In [59]:
ones[-1] = 1
In [60]:
ones
Out[60]:
[1, 1, 1, 1, 1]
In [61]:
t[-1] = 0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-61-ee34ec2392d1> in <module>
----> 1 t[-1] = 0

TypeError: 'tuple' object does not support item assignment
In [62]:
name = "python"
In [63]:
name[0] = "P"
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-63-27dae8d01db1> in <module>
----> 1 name[0] = "P"

TypeError: 'str' object does not support item assignment
In [64]:
name[0]
Out[64]:
'p'

there is binary

In [65]:
binary = b"this i sstring strored as binary"
In [66]:
binary
Out[66]:
b'this i sstring strored as binary'
In [67]:
"hello" + binary
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-67-baf5b257ed49> in <module>
----> 1 "hello" + binary

TypeError: can only concatenate str (not "bytes") to str
In [69]:
binary = b"\x22\x67\x65"
In [70]:
binary
Out[70]:
b'"ge'
In [71]:
print(binary)
b'"ge'

there are dictionaries

In [73]:
company = {"name":"Arcesium", "location":"Hyderabad"}
In [74]:
company['name']
Out[74]:
'Arcesium'
In [75]:
company["location"]
Out[75]:
'Hyderabad'
In [76]:
company['ticker']
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-76-cccf87ddaf7e> in <module>
----> 1 company['ticker']

KeyError: 'ticker'
In [77]:
company['ticker'] = "ARC"
In [78]:
company['ticker']
Out[78]:
'ARC'
In [79]:
company
Out[79]:
{'name': 'Arcesium', 'location': 'Hyderabad', 'ticker': 'ARC'}

there are sets

In [80]:
chars = {"A","B","C","C","C"}
In [81]:
chars
Out[81]:
{'A', 'B', 'C'}
In [82]:
{"A":"a", "B","C"}
  File "<ipython-input-82-6b5ee8e42319>", line 1
    {"A":"a", "B","C"}
                 ^
SyntaxError: invalid syntax

boolean

In [83]:
yes = True
In [84]:
no = False

nothing

In [86]:
nothing = None
In [87]:
""
Out[87]:
''
In [88]:
[]
Out[88]:
[]
In [89]:
()
Out[89]:
()
In [90]:
{}
Out[90]:
{}
In [91]:
pass

Questions

In [93]:
key1= "processor"
key2 = "os"
key3 = "memory"
In [94]:
specs = {key1:"Corei5", key2:"mint", key3:"4GB"}
In [95]:
specs
Out[95]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '4GB'}
In [96]:
key3 = "RAM"
In [97]:
specs
Out[97]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '4GB'}
In [98]:
data = {1:"One", 2:"Two"}
In [99]:
data
Out[99]:
{1: 'One', 2: 'Two'}
In [100]:
data[1]
Out[100]:
'One'
In [101]:
data[-1]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-101-ae1b7cc684db> in <module>
----> 1 data[-1]

KeyError: -1
In [102]:
d = {1:[1, 1, 1, 1], 2:[2, 2, 2, 2]}
In [103]:
d[1]
Out[103]:
[1, 1, 1, 1]
In [104]:
d[2]
Out[104]:
[2, 2, 2, 2]
In [105]:
d = {"One":[1, 1, 1, 1], "Two":[2, 2, 2, 2]}
In [106]:
d = {(1, 1):"one", (2, 2):"two"}
In [107]:
d = {[1, 1]:"one", [2, 2]:"two"}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-107-61f9667ecaac> in <module>
----> 1 d = {[1, 1]:"one", [2, 2]:"two"}

TypeError: unhashable type: 'list'
In [108]:
specs['memory'] = "8GB"
In [109]:
specs
Out[109]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '8GB'}
In [110]:
specs["brand"] = "Acer"
In [111]:
specs
Out[111]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '8GB', 'brand': 'Acer'}
In [113]:
table = [specs]*10
In [118]:
table[4]['processor'] ## 4th row->dict->processor
Out[118]:
'Corei5'

Functions

In [119]:
len("this string")
Out[119]:
11
In [120]:
len(specs)
Out[120]:
4
In [121]:
len(table)
Out[121]:
10
In [122]:
len((1, 1, 1,1, 1))
Out[122]:
5
In [123]:
specs
Out[123]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '8GB', 'brand': 'Acer'}
In [124]:
int("45")
Out[124]:
45
In [125]:
float("3.0")
Out[125]:
3.0
In [126]:
str(3.0)
Out[126]:
'3.0'
In [129]:
r = range(10)
In [130]:
list(r)
Out[130]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [131]:
list(range(1,10))
Out[131]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
In [132]:
list(range(1,20,3))
Out[132]:
[1, 4, 7, 10, 13, 16, 19]
In [133]:
sum(ones)
Out[133]:
5

problems

  • Find sum of first 100 natural numbers
  • count number of digits in 2**1000
In [134]:
sum(range(1, 101))
Out[134]:
5050
In [136]:
n = 2**1000
In [137]:
len(n)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-137-efcb9d8dcfe2> in <module>
----> 1 len(n)

TypeError: object of type 'int' has no len()
In [138]:
len(str(n))
Out[138]:
302
In [140]:
len(str(3.45))
Out[140]:
4
In [143]:
def hello():
    print("Hello there!")
    print("Another Hello!")
    print("Task done!...exiting")
In [144]:
hello()
Hello there!
Another Hello!
Task done!...exiting
In [145]:
def hello():
    print("Hello there!")
    print("Another Hello!")
    
print("Task done!...exiting")
Task done!...exiting
In [146]:
hello()
Hello there!
Another Hello!
In [147]:
def count_digits(n):
    return len(str(n))
In [149]:
count_digits(2**100)
Out[149]:
31
In [150]:
count_digits(2**1000)
Out[150]:
302
In [151]:
n
Out[151]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
In [153]:
def add(x, y):
    return x+y
In [154]:
add(3, 5)
Out[154]:
8
In [155]:
x = 10
In [156]:
y = 45
In [157]:
add(5, 6)
Out[157]:
11
In [158]:
x
Out[158]:
10
In [159]:
y
Out[159]:
45
In [161]:
def twice(x):
    y = x
    return 2*x
In [162]:
twice(5)
Out[162]:
10
In [163]:
y
Out[163]:
45
In [164]:
g = 10
def accessgloabal():
    print(g)
In [165]:
accessgloabal()
10
In [166]:
def twice1(x):
    print(2*x)
In [167]:
twice1(5)
10
In [168]:
twice(5)
Out[168]:
10
In [169]:
a = add(3, 5)
In [170]:
t6 = twice(6)
In [171]:
t6
Out[171]:
12
In [172]:
t7  = twice1(7)
14
In [173]:
print(t7)
None

A function with no return statement by default returns None

In [174]:
twice(twice(5))
Out[174]:
20
In [175]:
twice1(twice1(5))
10
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-175-9c16ec1a24f8> in <module>
----> 1 twice1(twice1(5))

<ipython-input-166-22e986a8fae6> in twice1(x)
      1 def twice1(x):
----> 2     print(2*x)

TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'
In [176]:
def sumofsquares(x, y):
    return square(x) + square(y)
In [177]:
sumofsquares(5, 6)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-177-b72969aaf814> in <module>
----> 1 sumofsquares(5, 6)

<ipython-input-176-b43c31808bdd> in sumofsquares(x, y)
      1 def sumofsquares(x, y):
----> 2     return square(x) + square(y)

NameError: name 'square' is not defined
In [178]:
def square(a):
    return a*a
In [179]:
square
Out[179]:
<function __main__.square(a)>
In [180]:
square(4)
Out[180]:
16
In [181]:
sumofsquares(5, 6)
Out[181]:
61
In [182]:
fun = square
In [183]:
x = 5
y = x
In [184]:
square
Out[184]:
<function __main__.square(a)>
In [185]:
fun = square
In [186]:
fun
Out[186]:
<function __main__.square(a)>
In [187]:
fun(5)
Out[187]:
25
In [191]:
def square(a):
    return a*a

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

def zeta(x):
    return None

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

def sumofcubes(a, b):
    return cube(a) + cube(b)
In [192]:
def sumof(func, x, y):
    return func(x) + func(y)
In [193]:
sumof(square, 2, 3)
Out[193]:
13
In [195]:
sumof(cube, 3, 4)
Out[195]:
91
In [196]:
int("2")
Out[196]:
2
In [197]:
float("3.0")
Out[197]:
3.0
In [198]:
str(2324)
Out[198]:
'2324'
In [199]:
sum([1, 2, 3, 45])
Out[199]:
51
In [200]:
max([1, 2, 3, 45])
Out[200]:
45
In [201]:
min([-1, 2, 3, 4, 565])
Out[201]:
-1
In [202]:
words = ["one", "two", "three", "four", "five"]
In [203]:
max(words)
Out[203]:
'two'
In [204]:
max(words, key=len)
Out[204]:
'three'
In [205]:
help(max)
Help on built-in function max in module builtins:

max(...)
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value
    
    With a single iterable argument, return its biggest item. The
    default keyword-only argument specifies an object to return if
    the provided iterable is empty.
    With two or more arguments, return the largest argument.

In [206]:
max(words, len)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-206-173597093508> in <module>
----> 1 max(words, len)

TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'list'
In [208]:
max(words, key=len)
Out[208]:
'three'
In [209]:
2
3
4
Out[209]:
4
In [210]:
print(2)
print(3)
print(4)
2
3
4
In [211]:
text = "hello"
In [212]:
text
Out[212]:
'hello'
In [213]:
print(text)
hello
In [214]:
square
Out[214]:
<function __main__.square(a)>
In [215]:
print(square)
<function square at 0x7f5cb2d9c598>
In [218]:
# (ticker, value, gain)
stocks = [("HCL", 500.0, 10.0),
          ("INFY", 800.0, 8.0),
          ("TATA", 247, 3),
          ("MM", 530, -5)]

stocks = [("HCL", 500.0, 10.0), ("INFY", 800.0, 8.0), ("TATA", 247, 3),("MM", 530, -5)]
In [219]:
max(stocks)
Out[219]:
('TATA', 247, 3)
In [220]:
def getvalue(r):
    return r[1]

def getgain(r):
    return r[2]
In [222]:
max(stocks, key=getvalue)
Out[222]:
('INFY', 800.0, 8.0)
In [223]:
max(stocks, key=getgain)
Out[223]:
('HCL', 500.0, 10.0)
In [224]:
min(stocks, key=getgain)
Out[224]:
('MM', 530, -5)

Function as return value

In [225]:
def make_logger(type_):
    
    def logger(message):
        print("[" + type_ + "]:", message)
        
    return logger
In [226]:
info = make_logger("INFO")
In [227]:
print(info)
<function make_logger.<locals>.logger at 0x7f5cb2d9c0d0>
In [228]:
warning = make_logger("WARN")
In [229]:
error = make_logger("ERROR")
In [230]:
info("Just for information")
warning("Something might go wrong!")
error("Boom! Something went wrong")
[INFO]: Just for information
[WARN]: Something might go wrong!
[ERROR]: Boom! Something went wrong
In [231]:
def make_adder(x):
    
    def adder(y):
        return x+y
    
    return adder
In [232]:
adder5 = make_adder(5)
In [233]:
adder5(5)
Out[233]:
10
In [234]:
adder5(100)
Out[234]:
105
In [235]:
def foo():
    pass
In [236]:
f = lambda x,y: x+y
In [237]:
f(3,4)
Out[237]:
7
In [238]:
max(stocks, key=lambda r: r[1])
Out[238]:
('INFY', 800.0, 8.0)
In [239]:
sorted([3, 4, 5,6,1 ,4])
Out[239]:
[1, 3, 4, 4, 5, 6]
In [241]:
sorted(stocks, key=getvalue, reverse=True)
Out[241]:
[('INFY', 800.0, 8.0), ('MM', 530, -5), ('HCL', 500.0, 10.0), ('TATA', 247, 3)]
In [242]:
stocks[1]
Out[242]:
('INFY', 800.0, 8.0)
In [243]:
stocks
Out[243]:
[('HCL', 500.0, 10.0), ('INFY', 800.0, 8.0), ('TATA', 247, 3), ('MM', 530, -5)]
In [244]:
stocks[1]
Out[244]:
('INFY', 800.0, 8.0)
In [247]:
def column(colnum):
    return lambda r: r[colnum]
In [248]:
max(stocks, key= column(1))
Out[248]:
('INFY', 800.0, 8.0)
In [249]:
max(stocks, key= column(2))
Out[249]:
('HCL', 500.0, 10.0)

Methods

In [252]:
statement = "Wizard of oz is python!"
In [253]:
statement.upper()
Out[253]:
'WIZARD OF OZ IS PYTHON!'
In [255]:
statement.split() # without parameter is white space (any and any numner of)
Out[255]:
['Wizard', 'of', 'oz', 'is', 'python!']
In [256]:
words = statement.split()
In [257]:
words
Out[257]:
['Wizard', 'of', 'oz', 'is', 'python!']
In [258]:
",".join(words)
Out[258]:
'Wizard,of,oz,is,python!'
In [259]:
",".join(words).split(",")
Out[259]:
['Wizard', 'of', 'oz', 'is', 'python!']
In [260]:
statement.replace("python", "Haskell")
Out[260]:
'Wizard of oz is Haskell!'
In [261]:
statement.startswith("Wizard")
Out[261]:
True
In [263]:
statement.split('o')
Out[263]:
['Wizard ', 'f ', 'z is pyth', 'n!']
In [264]:
statement.lower().split("o")
Out[264]:
['wizard ', 'f ', 'z is pyth', 'n!']
In [265]:
" with some trainling spaces         \n".strip()
Out[265]:
'with some trainling spaces'
In [266]:
statement.endswith("sdasd")
Out[266]:
False
In [267]:
statement.center(50)
Out[267]:
'             Wizard of oz is python!              '
In [269]:
print(poem)
The Zen of Python, by Tim Peters

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

In [270]:
statement.ljust(50)
Out[270]:
'Wizard of oz is python!                           '
In [271]:
statement.rjust(50)
Out[271]:
'                           Wizard of oz is python!'
In [273]:
help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(self, /)
 |      Return a capitalized version of the string.
 |      
 |      More specifically, make the first character have upper case and the rest lower
 |      case.
 |  
 |  casefold(self, /)
 |      Return a version of the string suitable for caseless comparisons.
 |  
 |  center(self, width, fillchar=' ', /)
 |      Return a centered string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |  
 |  encode(self, /, encoding='utf-8', errors='strict')
 |      Encode the string using the codec registered for encoding.
 |      
 |      encoding
 |        The encoding in which to encode the string.
 |      errors
 |        The error handling scheme to use for encoding errors.
 |        The default is 'strict' meaning that encoding errors raise a
 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
 |        'xmlcharrefreplace' as well as any other name registered with
 |        codecs.register_error that can handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |      
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found, 
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  isalnum(self, /)
 |      Return True if the string is an alpha-numeric string, False otherwise.
 |      
 |      A string is alpha-numeric if all characters in the string are alpha-numeric and
 |      there is at least one character in the string.
 |  
 |  isalpha(self, /)
 |      Return True if the string is an alphabetic string, False otherwise.
 |      
 |      A string is alphabetic if all characters in the string are alphabetic and there
 |      is at least one character in the string.
 |  
 |  isascii(self, /)
 |      Return True if all characters in the string are ASCII, False otherwise.
 |      
 |      ASCII characters have code points in the range U+0000-U+007F.
 |      Empty string is ASCII too.
 |  
 |  isdecimal(self, /)
 |      Return True if the string is a decimal string, False otherwise.
 |      
 |      A string is a decimal string if all characters in the string are decimal and
 |      there is at least one character in the string.
 |  
 |  isdigit(self, /)
 |      Return True if the string is a digit string, False otherwise.
 |      
 |      A string is a digit string if all characters in the string are digits and there
 |      is at least one character in the string.
 |  
 |  isidentifier(self, /)
 |      Return True if the string is a valid Python identifier, False otherwise.
 |      
 |      Use keyword.iskeyword() to test for reserved identifiers such as "def" and
 |      "class".
 |  
 |  islower(self, /)
 |      Return True if the string is a lowercase string, False otherwise.
 |      
 |      A string is lowercase if all cased characters in the string are lowercase and
 |      there is at least one cased character in the string.
 |  
 |  isnumeric(self, /)
 |      Return True if the string is a numeric string, False otherwise.
 |      
 |      A string is numeric if all characters in the string are numeric and there is at
 |      least one character in the string.
 |  
 |  isprintable(self, /)
 |      Return True if the string is printable, False otherwise.
 |      
 |      A string is printable if all of its characters are considered printable in
 |      repr() or if it is empty.
 |  
 |  isspace(self, /)
 |      Return True if the string is a whitespace string, False otherwise.
 |      
 |      A string is whitespace if all characters in the string are whitespace and there
 |      is at least one character in the string.
 |  
 |  istitle(self, /)
 |      Return True if the string is a title-cased string, False otherwise.
 |      
 |      In a title-cased string, upper- and title-case characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |  
 |  isupper(self, /)
 |      Return True if the string is an uppercase string, False otherwise.
 |      
 |      A string is uppercase if all cased characters in the string are uppercase and
 |      there is at least one cased character in the string.
 |  
 |  join(self, iterable, /)
 |      Concatenate any number of strings.
 |      
 |      The string whose method is called is inserted in between each given string.
 |      The result is returned as a new string.
 |      
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 |  
 |  ljust(self, width, fillchar=' ', /)
 |      Return a left-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  lower(self, /)
 |      Return a copy of the string converted to lowercase.
 |  
 |  lstrip(self, chars=None, /)
 |      Return a copy of the string with leading whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  partition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string.  If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original string
 |      and two empty strings.
 |  
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |      
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |      
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  rjust(self, width, fillchar=' ', /)
 |      Return a right-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  rpartition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing two empty strings
 |      and the original string.
 |  
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |        sep
 |          The delimiter according which to split the string.
 |          None (the default value) means split according to any whitespace,
 |          and discard empty strings from the result.
 |        maxsplit
 |          Maximum number of splits to do.
 |          -1 (the default value) means no limit.
 |      
 |      Splits are done starting at the end of the string and working to the front.
 |  
 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |      sep
 |        The delimiter according which to split the string.
 |        None (the default value) means split according to any whitespace,
 |        and discard empty strings from the result.
 |      maxsplit
 |        Maximum number of splits to do.
 |        -1 (the default value) means no limit.
 |  
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the string, breaking at line boundaries.
 |      
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace remove.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  swapcase(self, /)
 |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
 |  
 |  title(self, /)
 |      Return a version of the string where each word is titlecased.
 |      
 |      More specifically, words start with uppercased characters and all remaining
 |      cased characters have lower case.
 |  
 |  translate(self, table, /)
 |      Replace each character in the string using the given translation table.
 |      
 |        table
 |          Translation table, which must be a mapping of Unicode ordinals to
 |          Unicode ordinals, strings, or None.
 |      
 |      The table must implement lookup/indexing via __getitem__, for instance a
 |      dictionary or list.  If this operation raises LookupError, the character is
 |      left untouched.  Characters mapped to None are deleted.
 |  
 |  upper(self, /)
 |      Return a copy of the string converted to uppercase.
 |  
 |  zfill(self, width, /)
 |      Pad a numeric string with zeros on the left, to fill a field of the given width.
 |      
 |      The string is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  maketrans(x, y=None, z=None, /)
 |      Return a translation table usable for str.translate().
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.

methods from list

In [293]:
digits = list(range(10))
In [294]:
digits
Out[294]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [295]:
digits.append(-1)
In [296]:
digits
Out[296]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1]
In [297]:
digits.pop() # remove last element 
Out[297]:
-1
In [298]:
digits.insert(0, -1) # insert element at position zero
In [299]:
digits
Out[299]:
[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [300]:
digits.pop(0) # it pops 0th element
Out[300]:
-1
In [301]:
digits
Out[301]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [302]:
digits.reverse()
In [303]:
digits
Out[303]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
In [304]:
digits.extend([1,1,1,1,1])
In [305]:
digits
Out[305]:
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 1, 1, 1, 1, 1]
In [306]:
digits.remove(5) # remove element '5'
In [307]:
digits
Out[307]:
[9, 8, 7, 6, 4, 3, 2, 1, 0, 1, 1, 1, 1, 1]
In [ ]:
 
In [308]:
digits.index(4)
Out[308]:
4
In [309]:
digits.index(9)
Out[309]:
0
In [310]:
digits.index(5)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-310-2cd46b5d7929> in <module>
----> 1 digits.index(5)

ValueError: 5 is not in list
In [311]:
digits.sort()
In [312]:
digits
Out[312]:
[0, 1, 1, 1, 1, 1, 1, 2, 3, 4, 6, 7, 8, 9]
In [313]:
digits.count(5)
Out[313]:
0
In [314]:
digits.count(1)
Out[314]:
6

conditions

In [315]:
1 == 1
Out[315]:
True
In [316]:
1 != 2
Out[316]:
True
In [317]:
statement
Out[317]:
'Wizard of oz is python!'
In [318]:
statement.startswith("W")
Out[318]:
True
In [319]:
statement.endswith("!")
Out[319]:
True
In [320]:
"python" in statement
Out[320]:
True
In [321]:
5 in digits
Out[321]:
False
In [323]:
specs
Out[323]:
{'processor': 'Corei5', 'os': 'mint', 'memory': '8GB', 'brand': 'Acer'}
In [324]:
"os" in specs
Out[324]:
True
In [325]:
"brand" in specs
Out[325]:
True
In [326]:
"Corei5" in specs.values()
Out[326]:
True
In [327]:
3 in 5
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-327-2ca14682119f> in <module>
----> 1 3 in 5

TypeError: argument of type 'int' is not iterable
In [329]:
"3" in "3333333"
Out[329]:
True
In [331]:
def filetype(filename):
    ext = filename.split(".")[-1]
    if ext == "py":
        return "python"
    elif ext == "exe":
        return "executable"
    elif ext == "hs":
        return "haskell"
    else:
        return "Unknown"
In [332]:
filetype("hello.py")
Out[332]:
'python'
In [333]:
def filetype(filename):
    if filename.endswith("py"):
        return "python"
    elif filename.endswith("exe"):
        return "executable"
    elif filename.endswith("hs"):
        return "haskell"
    else:
        return "Unknown"
In [334]:
filetype("windows.exe")
Out[334]:
'executable'

problems

  • write a function min2 which finds minimum from two numbers
    >>> min2(4,5)
    4
  • Write a fucntion min3 which finds minimum from three numbers
    >>> min3(3,4,1)
    1
In [335]:
def min2(x,y):
    if x < y:
        return x
    else:
        return y
In [336]:
def min3(x, y, z):
    return min2(min2(x, y), z)

modules

In [337]:
import math
In [338]:
import os
In [339]:
math
Out[339]:
<module 'math' from '/home/vikrant/anaconda3/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so'>
In [340]:
math.pi
Out[340]:
3.141592653589793
In [341]:
from math import sqrt
In [342]:
sqrt(4)
Out[342]:
2.0
In [344]:
from math import sqrt as suareroot
In [345]:
import time
In [346]:
time.time()
Out[346]:
1559560105.4262936
In [347]:
def timeit(f):
    start = time.time()
    f()
    end = time.time()
    return end - start
In [350]:
def distance(x1, y1, x2, y2):
    return math.sqrt((x2-x1)**2 + (y2-y1)**2)

def distance2(x1, y1, x2, y2):
    return sqrt((x2-x1)**2 + (y2-y1)**2)
In [359]:
def testfunc1():
    for i in range(10000000):
        distance(5,4,6,2)
        
def testfunc2():
    for i in range(10000000):
        distance2(5,4,6,2)
In [360]:
timeit(testfunc1)
Out[360]:
8.908982992172241
In [361]:
timeit(testfunc2)
Out[361]:
8.434070110321045
In [365]:
def foo1(a, b, c):
    print(a, b, c)
In [366]:
def foo2(a, b, c=0):
    print(a, b, c)
In [367]:
foo1(1, 2, 3)
1 2 3
In [368]:
foo2(1, 2)
1 2 0
In [369]:
foo2(1, 2, 4)
1 2 4
In [370]:
foo1(a=3, c=2, b =1)
3 1 2
In [371]:
args = (1, 2, 3)
foo1(*args)
1 2 3
In [372]:
foo1(args)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-372-a600bd2fd7f7> in <module>
----> 1 foo1(args)

TypeError: foo1() missing 2 required positional arguments: 'b' and 'c'
In [373]:
kwargs = {"a":1, "b":2, "c":3}
foo1(**kwargs)
1 2 3
In [374]:
kwargs = {"a":1, "b":2, "c":3, "d":5}
foo1(**kwargs)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-374-81323f53a340> in <module>
      1 kwargs = {"a":1, "b":2, "c":3, "d":5}
----> 2 foo1(**kwargs)

TypeError: foo1() got an unexpected keyword argument 'd'
In [375]:
import math
In [376]:
import math as m
In [378]:
from math import sqrt
In [379]:
from math import sqrt as squareroot
In [381]:
import pandas as pd
In [382]:
os.getcwd()
Out[382]:
'/home/vikrant/trainings/2019/arcesium_basic_jun'
In [383]:
import os
In [384]:
cwd = os.getcwd()
os.listdir(cwd)
Out[384]:
['.ipynb_checkpoints',
 'push',
 'day1.ipynb',
 'Untitled.ipynb',
 'day2.ipynb',
 'day2.html',
 'Untitled.html',
 'Makefile',
 'day1.html']
In [385]:
os.getlogin()
---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-385-0f8aa747d9ad> in <module>
----> 1 os.getlogin()

OSError: [Errno 25] Inappropriate ioctl for device
In [387]:
os.getenv("PYTHONPATH")
Out[387]:
':/home/vikrant/programming/work/gitrep/chitragupta/src/'
In [388]:
os.path.sep
Out[388]:
'/'
In [390]:
os.path.sep.join(["","home", "vikrant", "trainings"])
Out[390]:
'/home/vikrant/trainings'
In [391]:
os.path.getsize("day1.html")
Out[391]:
516390
In [392]:
max(os.listdir(cwd), key= os.path.getsize)
Out[392]:
'day1.html'
In [393]:
os.path.exists("hello.py")
Out[393]:
False
In [394]:
os.path.exists("day1.ipynb")
Out[394]:
True

Writing our own modules

In [395]:
%%file hello.py

def say_hello(name):
    print("Hello", name)
    
Writing hello.py
In [396]:
import hello
In [397]:
hello.say_hello("Python")
Hello Python
In [398]:
!python hello.py
In [399]:
%%file hello1.py

def say_hello(name):
    print("Hello", name)
    

print("Hello!")
Writing hello1.py
In [400]:
!python hello1.py
Hello!
In [401]:
%%file hello2.py
import sys

def say_hello(name):
    print("Hello", name)
    

print(sys.argv)
say_hello(sys.argv[1])
Writing hello2.py
In [405]:
!python hello2.py python kjsahd kjsahd askjh dskfh sd kdsjhfkasdj
['hello2.py', 'python', 'kjsahd', 'kjsahd', 'askjh', 'dskfh', 'sd', 'kdsjhfkasdj']
Hello python
In [408]:
%%file square.py
import sys

def square(x):
    return x*x

n = float(sys.argv[1])
print(square(n))
Overwriting square.py
In [409]:
!python square.py 5
25.0
In [410]:
import square
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-410-9e928442ab9c> in <module>
----> 1 import square

~/trainings/2019/arcesium_basic_jun/square.py in <module>
      4     return x*x
      5 
----> 6 n = float(sys.argv[1])
      7 print(square(n))

ValueError: could not convert string to float: '-f'
In [411]:
from square import square
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-411-8b35ce5fdde6> in <module>
----> 1 from square import square

~/trainings/2019/arcesium_basic_jun/square.py in <module>
      4     return x*x
      5 
----> 6 n = float(sys.argv[1])
      7 print(square(n))

ValueError: could not convert string to float: '-f'
In [412]:
fun
Out[412]:
<function __main__.square(a)>
In [413]:
__name__
Out[413]:
'__main__'
In [419]:
%%file square1.py
import sys

def square(x):
    return x*x


print(__name__)
if __name__ == "__main__":
    n = float(sys.argv[1])
    print(square(n))
Overwriting square1.py
In [415]:
!python square1.py 67
__main__
4489.0
In [416]:
import square1
square1
In [417]:
square1.square(45)
Out[417]:
2025
In [420]:
%%file square2.py
import sys

def square(x):
    return x*x

def modulename():
    print(__name__)
    
if __name__ == "__main__":
    n = float(sys.argv[1])
    print(square(n))
Overwriting square2.py
In [421]:
import square2
In [422]:
square2.modulename()
square2
In [423]:
__name__
Out[423]:
'__main__'
In [424]:
square2.__name__
Out[424]:
'square2'

list slicing

In [425]:
numbers = [1, 2, 3, 5, 8, 13, 21, 34, 55]
In [426]:
numbers[0]
Out[426]:
1
In [427]:
numbers[2:5] ## items from 2nd index till 5th index (excluded)
Out[427]:
[3, 5, 8]
In [429]:
numbers[:5] # from start till 5th index (exluded)
Out[429]:
[1, 2, 3, 5, 8]
In [430]:
numbers[3:] # start from 3rd index till end
Out[430]:
[5, 8, 13, 21, 34, 55]
In [431]:
numbers[:3] # take first 3
Out[431]:
[1, 2, 3]
In [432]:
numbers[2:] # drop first two
Out[432]:
[3, 5, 8, 13, 21, 34, 55]
In [433]:
numbers[1:8:2] # start at index 1 end at index 7 at distance of 2
Out[433]:
[2, 5, 13, 34]
In [435]:
numbers[:] # copy
Out[435]:
[1, 2, 3, 5, 8, 13, 21, 34, 55]
In [437]:
numbers[3:-1]  # drop 3 from front drop 1 from tail
Out[437]:
[5, 8, 13, 21, 34]
In [438]:
numbers[::-1] # reverse
Out[438]:
[55, 34, 21, 13, 8, 5, 3, 2, 1]
In [439]:
def is_palindrome(word):
    return word == word[::-1]
In [440]:
is_palindrome("madam")
Out[440]:
True
In [441]:
len(numbers)
Out[441]:
9
In [442]:
numbers[3:100]
Out[442]:
[5, 8, 13, 21, 34, 55]
In [443]:
numbers[100]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-443-6bd80f0b9f0d> in <module>
----> 1 numbers[100]

IndexError: list index out of range
In [444]:
numbers[300:]
Out[444]:
[]
In [445]:
"hello world"[::-1]
Out[445]:
'dlrow olleh'

While loop

In [446]:
x, y = 2, 3
In [447]:
x = 5
y = 10
In [448]:
y, x = x, y
In [449]:
x
Out[449]:
10
In [450]:
y
Out[450]:
5
In [451]:
prev = 1
curr = 1
while curr < 100:
    prev, curr = curr, prev+curr
    print(curr, end=",")
2,3,5,8,13,21,34,55,89,144,
In [453]:
def print_fibionacci(n):
    prev = 1
    curr = 1
    while curr < n:
        prev, curr = curr, prev+curr
        print(curr)
In [454]:
print_fibionacci(100)
2
3
5
8
13
21
34
55
89
144
In [455]:
def print_fibionacci(n):
    prev = 1
    curr = 1
    while curr < n:
        prev, curr = curr, prev+curr
        print(curr, end=" ")
In [456]:
print_fibionacci(100)
2 3 5 8 13 21 34 55 89 144 
In [461]:
def print_fibonacci(n):
    """
    prints all fibonacci numbers less than n
    """
    prev = 1
    curr = 1
    while curr < n:
        prev, curr = curr, prev+curr
        print(curr, end=" ")
In [462]:
help(print_fibonacci)
Help on function print_fibonacci in module __main__:

print_fibonacci(n)
    prints all fibonacci numbers less than n

for loops

In [463]:
numbers
Out[463]:
[1, 2, 3, 5, 8, 13, 21, 34, 55]
In [464]:
for fib in numbers:
    print(fib, end=",")
    
1,2,3,5,8,13,21,34,55,
In [465]:
for w in words:
    print(w)
Wizard
of
oz
is
python!
In [468]:
for c in statement:
    print(c, end=",")
W,i,z,a,r,d, ,o,f, ,o,z, ,i,s, ,p,y,t,h,o,n,!,
In [470]:
for item in specs:
    print(item, specs[item])
processor Corei5
os mint
memory 8GB
brand Acer
In [471]:
for key, value in specs.items():
    print(key, value)
processor Corei5
os mint
memory 8GB
brand Acer
In [472]:
for fib in numbers[:5]:
    print(fib, end=",")
1,2,3,5,8,
In [473]:
!ls
day1.html   day2.ipynb	hello.py  __pycache__  square.py
day1.ipynb  hello1.py	Makefile  square1.py   Untitled.html
day2.html   hello2.py	push	  square2.py   Untitled.ipynb
In [474]:
%%file ls.py
import os

def ls(location=None):
    if location==None:
        location = os.getcwd()
    files = os.listdir(location)
    for f in files:
        print(f)
        
if __name__ == "__main__":
    ls()
Writing ls.py
In [475]:
!python ls.py
.ipynb_checkpoints
push
day1.ipynb
Untitled.ipynb
square2.py
day2.ipynb
day2.html
Untitled.html
square.py
hello.py
hello2.py
hello1.py
Makefile
__pycache__
day1.html
ls.py
square1.py

problems

  • Write a function mysum which will sum all elements from a list
  • Write a fucntion product which will find product of all elements from a list
  • How about factorial?
In [476]:
sum(numbers)
Out[476]:
142
In [477]:
sum(words)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-477-8035aa90a51c> in <module>
----> 1 sum(words)

TypeError: unsupported operand type(s) for +: 'int' and 'str'
In [478]:
def mysum(items):
    s = 0
    for item in items:
        s += item
    return s

def product(items):
    p = 1
    for item in items:
        p *= item
    return p

def factorial(n):
    return product(range(1, n+1))
In [479]:
isinstance(2, int)
Out[479]:
True
In [480]:
def mysum(items):
    if items and isinstance(items[0], str):
        s = ""
    else:
        s = 0
    for item in items:
        s += item
    return s
In [481]:
mysum(words)
Out[481]:
'Wizardofozispython!'
In [482]:
mysum(numbers)
Out[482]:
142
In [483]:
from functools import reduce
In [484]:
help(reduce)
Help on built-in function reduce in module _functools:

reduce(...)
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.

In [485]:
reduce(lambda x, y: x+y , numbers)
Out[485]:
142
In [488]:
reduce(lambda x, y: x*y , range(1, 5))
Out[488]:
24
In [489]:
import operator
In [490]:
operator.add
Out[490]:
<function _operator.add(a, b, /)>

list comprehensions

In [491]:
for i in numbers:
    print(i*i, end=",")
1,4,9,25,64,169,441,1156,3025,
In [492]:
def squares(seq):
    s = []
    for item in seq:
        s.append(item**2)
    return s
In [493]:
[item**2 for item in numbers]
Out[493]:
[1, 4, 9, 25, 64, 169, 441, 1156, 3025]
In [494]:
squares(numbers)
Out[494]:
[1, 4, 9, 25, 64, 169, 441, 1156, 3025]
In [495]:
def squares(numbers):
    return [item**2 for item in numbers]
In [496]:
def evens(numbers):
    s = []
    for i in numbers:
        if i%2==0:
            s.append(i)
    return s
In [497]:
evens(numbers)
Out[497]:
[2, 8, 34]
In [498]:
[i for i in numbers if i%2==0]
Out[498]:
[2, 8, 34]
In [499]:
def listpy(location):
    files = os.listdir(location)
    return [f for f in files if f.endswith(".py")]
In [500]:
listpy(os.getcwd())
Out[500]:
['square2.py',
 'square.py',
 'hello.py',
 'hello2.py',
 'hello1.py',
 'ls.py',
 'square1.py']

problems

  • Write a function factors using list comprehension which finds all factors of given number.
  • write a function is_prime which tells whether given number is prime or not
  • write a function primes which generates all primes less than n
In [501]:
[i for i in range(5)]
Out[501]:
[0, 1, 2, 3, 4]
In [502]:
[[i+j for i in range(5)] for j in range(5)]
Out[502]:
[[0, 1, 2, 3, 4],
 [1, 2, 3, 4, 5],
 [2, 3, 4, 5, 6],
 [3, 4, 5, 6, 7],
 [4, 5, 6, 7, 8]]
In [ ]: