In [2]:
print("Hello world")


Hello world

In [3]:
'Single quoted string'


Out[3]:
'Single quoted string'

In [4]:
"double quoted string"


Out[4]:
'double quoted string'

In [5]:
''' This is is tripple quoted string

contains new lines and 
preserves them.'''


Out[5]:
' This is is tripple quoted string\n\ncontains new lines and \npreserves them.'

In [6]:
""" THisi is same as above

has new lines"""


Out[6]:
' THisi is same as above\n\nhas new lines'

In [7]:
'kasdkjasd
asdlkalsdk'


  File "<ipython-input-7-85f5e5d6ec51>", line 1
    'kasdkjasd
              ^
SyntaxError: EOL while scanning string literal

In [9]:
# integers
1
2
99


Out[9]:
99

In [10]:
# floats
1.2
0.1
9.4
2.0


Out[10]:
2.0

In [11]:
# booleans
True
False


Out[11]:
False

In [12]:
# Null / nothing
None

In [13]:
1 + 3


Out[13]:
4

In [14]:
1.0 + 3


Out[14]:
4.0

In [15]:
2.3 + 5.6


Out[15]:
7.8999999999999995

In [16]:
'a string ' + 'added later'


Out[16]:
'a string added later'

In [17]:
5 - 4


Out[17]:
1

In [18]:
2 - 3


Out[18]:
-1

In [19]:
1.2 - 1.6


Out[19]:
-0.40000000000000013

In [20]:
2 ** 7


Out[20]:
128

In [21]:
'a string' - 'p'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-dca95bbfb9c1> in <module>()
----> 1 'a string' - 'p'

TypeError: unsupported operand type(s) for -: 'str' and 'str'

In [22]:
1 * 2


Out[22]:
2

In [23]:
2.3 * 6


Out[23]:
13.799999999999999

In [24]:
'abc' * 3


Out[24]:
'abcabcabc'

In [25]:
5 / 4


Out[25]:
1.25

In [26]:
5 // 4


Out[26]:
1

In [28]:
5.0 // 4


Out[28]:
1.0

In [30]:
5 % 2


Out[30]:
1

if / elif / else


In [31]:
if True:
    print("true")


true

In [32]:
if not False:
    print("not false")


not false

In [33]:
if not True:
    pass
else:
    print("true inside else")


true inside else

In [35]:
if '':
    pass
elif ' ':
    print('some string')
else:
    print("never here")


some string

In [37]:
ord('1')


Out[37]:
49

In [38]:
ord('A')


Out[38]:
65

In [39]:
ord(' ')


Out[39]:
32

In [40]:
ord('ल')


Out[40]:
2354

In [41]:
ord('')


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-41-aa71af3e4bfb> in <module>()
----> 1 ord('')

TypeError: ord() expected a character, but string of length 0 found

In [42]:
if 1:
    print("true")


true

In [43]:
if 0:
    print("inside if")
else:
    print("inside else")


inside else

In [44]:
0.0 == True


Out[44]:
False

In [45]:
0 == True


Out[45]:
False

In [46]:
'' == True


Out[46]:
False

In [48]:
' ' == True


Out[48]:
False

In [49]:
' ' == ' '


Out[49]:
True

In [50]:
2 > 3


Out[50]:
False

In [52]:
3 < 4


Out[52]:
True

In [53]:
'a' < 'b'


Out[53]:
True

In [54]:
'p' > 'r'


Out[54]:
False

In [55]:
'a' == 'A'


Out[55]:
False

In [56]:
'a' < 'A'


Out[56]:
False

In [57]:
ord('A')


Out[57]:
65

In [58]:
ord('a')


Out[58]:
97

In [59]:
2 <= 2


Out[59]:
True

In [60]:
4 >= 3


Out[60]:
True

In [61]:
2 < 3 < 4


Out[61]:
True

In [63]:
4 > 5 > 6


Out[63]:
False

String



In [65]:
dir('')


Out[65]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']

In [66]:
'Abc'.lower()


Out[66]:
'abc'

In [67]:
'capital'.upper()


Out[67]:
'CAPITAL'

In [68]:
'kathmandu'.capitalize()


Out[68]:
'Kathmandu'

In [69]:
'KaThMandU'.swapcase()


Out[69]:
'kAtHmANDu'

H/W test all string methods

docs.python.org


In [ ]:

Complex numbers



In [70]:
(1 + 2j)


Out[70]:
(1+2j)

In [71]:
complex_number = 4 + 7j

In [72]:
complex_number - (5 + 2j)


Out[72]:
(-1+5j)

In [74]:
complex_number.real


Out[74]:
4.0

In [75]:
complex_number.imag


Out[75]:
7.0

In [77]:
complex_number.conjugate()


Out[77]:
(4-7j)

In [ ]:

string slicing and for/while loops



In [78]:
city = 'Kathmandu'

In [79]:
city[3]


Out[79]:
'h'

In [80]:
city[-1]


Out[80]:
'u'

In [81]:
city[len(city) - 1]


Out[81]:
'u'

In [82]:
city[0]


Out[82]:
'K'

In [83]:
city[-4]


Out[83]:
'a'

In [86]:
city[1:4]


Out[86]:
'ath'

In [85]:
city


Out[85]:
'Kathmandu'

In [87]:
city[3:7]


Out[87]:
'hman'

In [88]:
city[1:7:2]


Out[88]:
'aha'

In [89]:
city[:]


Out[89]:
'Kathmandu'

In [90]:
city[::]


Out[90]:
'Kathmandu'

In [91]:
len(city)


Out[91]:
9

In [92]:
city[0:9]


Out[92]:
'Kathmandu'

In [93]:
city[9]


---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-93-29a18b8624f3> in <module>()
----> 1 city[9]

IndexError: string index out of range

In [96]:
city[::-1]


Out[96]:
'udnamhtaK'

In [97]:
city[-5:-8:-1]


Out[97]:
'mht'

In [100]:
city[3:-5]


Out[100]:
'h'

In [101]:
city[3:-7]


Out[101]:
''

In [ ]:


In [102]:
for c in city:
    print(c)


K
a
t
h
m
a
n
d
u

In [103]:
index = 0
while index < len(city):
    print(city[index])
    index += 1


K
a
t
h
m
a
n
d
u

In [ ]:

Lists



In [104]:
cities = ['kathmandu', 'Biratnagar', 'Pokhara', 'Birgunj', 'Hetauda']

In [105]:
for city in cities:
    print(city)


kathmandu
Biratnagar
Pokhara
Birgunj
Hetauda

In [106]:
[1, 2, 5]


Out[106]:
[1, 2, 5]

In [107]:
[[2, 3], [6, 7]]


Out[107]:
[[2, 3], [6, 7]]

In [108]:
[5.6, 6.7, 9.0]


Out[108]:
[5.6, 6.7, 9.0]

In [109]:
['a', 'string', 4, 9, 2.3, 2 + 7j]


Out[109]:
['a', 'string', 4, 9, 2.3, (2+7j)]

In [ ]:


In [110]:
[2, 3] + [5, 6]


Out[110]:
[2, 3, 5, 6]

In [111]:
[3, 4] + [[3, 4], 7]


Out[111]:
[3, 4, [3, 4], 7]

In [112]:
cities


Out[112]:
['kathmandu', 'Biratnagar', 'Pokhara', 'Birgunj', 'Hetauda']

In [113]:
cities.append('Dhankuta')

In [114]:
cities


Out[114]:
['kathmandu', 'Biratnagar', 'Pokhara', 'Birgunj', 'Hetauda', 'Dhankuta']

In [115]:
cities.pop()


Out[115]:
'Dhankuta'

In [116]:
cities


Out[116]:
['kathmandu', 'Biratnagar', 'Pokhara', 'Birgunj', 'Hetauda']

In [117]:
cities[0]


Out[117]:
'kathmandu'

In [118]:
cities[4]


Out[118]:
'Hetauda'

In [119]:
cities[3:5]


Out[119]:
['Birgunj', 'Hetauda']

In [120]:
cities[-1]


Out[120]:
'Hetauda'

In [121]:
cities


Out[121]:
['kathmandu', 'Biratnagar', 'Pokhara', 'Birgunj', 'Hetauda']

In [122]:
cities.remove('Pokhara')

In [123]:
cities


Out[123]:
['kathmandu', 'Biratnagar', 'Birgunj', 'Hetauda']

In [124]:
dir(cities)


Out[124]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']

In [125]:
cities


Out[125]:
['kathmandu', 'Biratnagar', 'Birgunj', 'Hetauda']

In [127]:
cities.insert(1, 'Pokhara')

In [128]:
cities


Out[128]:
['kathmandu', 'Pokhara', 'Biratnagar', 'Birgunj', 'Hetauda']

In [129]:
cities.pop(2)


Out[129]:
'Biratnagar'

In [130]:
cities


Out[130]:
['kathmandu', 'Pokhara', 'Birgunj', 'Hetauda']

In [131]:
cities.extend(['Biratnagar', 'Dhankuta', 'Dharan'])

In [132]:
cities


Out[132]:
['kathmandu',
 'Pokhara',
 'Birgunj',
 'Hetauda',
 'Biratnagar',
 'Dhankuta',
 'Dharan']

In [135]:
cities[1] = 'Pokhara City'

In [136]:
cities


Out[136]:
['kathmandu',
 'Pokhara City',
 'Birgunj',
 'Hetauda',
 'Biratnagar',
 'Dhankuta',
 'Dharan']

Tuple



In [133]:
name = ('john doe', 23)

In [134]:
dir(name)


Out[134]:
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'count',
 'index']

In [137]:
name[0] = 'Diwaker'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-137-66fa5ece2a7f> in <module>()
----> 1 name[0] = 'Diwaker'

TypeError: 'tuple' object does not support item assignment

In [142]:
city


Out[142]:
'Hetauda'

In [143]:
city[0] = 'P'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-143-bcabadd3c566> in <module>()
----> 1 city[0] = 'P'

TypeError: 'str' object does not support item assignment

In [ ]:


In [ ]:

Dictionary



In [148]:
phones = {'John Doe': '9287389234923', 'Jane Doe': '9234798234224'}

In [149]:
phones['John Doe']


Out[149]:
'9287389234923'

In [150]:
phones[0]


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-150-e64389312068> in <module>()
----> 1 phones[0]

KeyError: 0

In [151]:
phones.keys()


Out[151]:
dict_keys(['Jane Doe', 'John Doe'])

In [152]:
phones.values()


Out[152]:
dict_values(['9234798234224', '9287389234923'])

In [153]:
phones.items()


Out[153]:
dict_items([('Jane Doe', '9234798234224'), ('John Doe', '9287389234923')])

In [ ]:


In [154]:
for item in phones:
    print(item)


Jane Doe
John Doe

In [155]:
for item in phones:
    print(phones[item])


9234798234224
9287389234923

In [ ]:


In [156]:
key = 'abc'

In [157]:
key


Out[157]:
'abc'

In [158]:
key, value = 'abc', 'xyz'

In [159]:
key


Out[159]:
'abc'

In [160]:
value


Out[160]:
'xyz'

In [168]:
item = ('abc', 'xyz')

In [169]:
key, value = item

In [161]:
key, value = ('abc', 'xyz')

In [162]:
value


Out[162]:
'xyz'

In [167]:
for item in phones.items():
    key, value = item
    print(item)
    print(key)


('Jane Doe', '9234798234224')
Jane Doe
('John Doe', '9287389234923')
John Doe

In [170]:
for key, value in phones.items():
    print(key)
    print(value)


Jane Doe
9234798234224
John Doe
9287389234923

In [176]:
dir(phones)


Out[176]:
['__class__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'items',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values']

In [177]:
phones['User 1'] = '293829348724'

In [178]:
phones


Out[178]:
{'Jane Doe': '9234798234224',
 'John Doe': '9287389234923',
 'User 1': '293829348724'}

In [180]:
phones.update({'user1': 'ashdkajsdk', 'user5': 'asdhjaksdhkasd'})

In [181]:
phones


Out[181]:
{'Jane Doe': '9234798234224',
 'John Doe': '9287389234923',
 'User 1': '293829348724',
 'user1': 'ashdkajsdk',
 'user5': 'asdhjaksdhkasd'}

In [182]:
phones.update({'user1': '92384792384792384'})

In [183]:
phones


Out[183]:
{'Jane Doe': '9234798234224',
 'John Doe': '9287389234923',
 'User 1': '293829348724',
 'user1': '92384792384792384',
 'user5': 'asdhjaksdhkasd'}

In [ ]:


In [ ]:


In [ ]:

Sets


In [171]:
chars = {'a', 'b', 'd', 'b', 'e'}

In [172]:
chars


Out[172]:
{'a', 'b', 'd', 'e'}

In [173]:
chars.union({'f', 'e', 'g'})


Out[173]:
{'a', 'b', 'd', 'e', 'f', 'g'}

In [174]:
chars.intersection({'d', 'e', 'f'})


Out[174]:
{'d', 'e'}

In [175]:
dir(chars)


Out[175]:
['__and__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__iand__',
 '__init__',
 '__ior__',
 '__isub__',
 '__iter__',
 '__ixor__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__or__',
 '__rand__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__ror__',
 '__rsub__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__xor__',
 'add',
 'clear',
 'copy',
 'difference',
 'difference_update',
 'discard',
 'intersection',
 'intersection_update',
 'isdisjoint',
 'issubset',
 'issuperset',
 'pop',
 'remove',
 'symmetric_difference',
 'symmetric_difference_update',
 'union',
 'update']

In [184]:
chars


Out[184]:
{'a', 'b', 'd', 'e'}

In [185]:
chars.add('f')

In [186]:
chars


Out[186]:
{'a', 'b', 'd', 'e', 'f'}

In [187]:
chars.add('e')

In [188]:
chars


Out[188]:
{'a', 'b', 'd', 'e', 'f'}

In [ ]:

Conditionals



In [191]:
# Empty list
[]


Out[191]:
[]

In [192]:
not []


Out[192]:
True

In [194]:
# empty tuple
tuple()


Out[194]:
()

In [195]:
not tuple()


Out[195]:
True

In [196]:
# tuple with single item
(1,)


Out[196]:
(1,)

In [197]:
# Empty dictionary
{}


Out[197]:
{}

In [198]:
# Empty set
set()


Out[198]:
set()

In [ ]:


In [204]:
a = [] and True

In [205]:
a


Out[205]:
[]

In [208]:
if [] and True:
    print('true')
else:
    print('false')


false

In [206]:
b = [1] and True

In [207]:
b


Out[207]:
True

In [200]:
[] or ''


Out[200]:
''

In [202]:
[1] or ''


Out[202]:
[1]

In [201]:
if [] and True:
    print('is here')
else:
    print('false')


false

In [ ]:

Functions



In [209]:
def function_name(arguments):
    # function body
    pass

In [210]:
def sum(a, b):
    return a + b

In [211]:
result = sum(5, 7)

In [212]:
result


Out[212]:
12

In [213]:
def power(val, by=2):
    return val ** by

In [214]:
power(3)


Out[214]:
9

In [215]:
# positional argument
power(3, 3)


Out[215]:
27

In [216]:
# named argument
power(val=5, by=4)


Out[216]:
625

In [217]:
power(by=4, val=5)


Out[217]:
625

In [218]:
power(6, by=5)


Out[218]:
7776

In [219]:
power(by=4, 6)


  File "<ipython-input-219-fc24565bad22>", line 1
    power(by=4, 6)
               ^
SyntaxError: positional argument follows keyword argument

In [ ]:

Fibonacci



In [231]:
def fib_hundred1():
    a, b = 0, 1
    while b < 100:
        print(b)
        a, b = b, a + b

In [232]:
fib_hundred1()


1
1
2
3
5
8
13
21
34
55
89

In [233]:
def fib_hundred2():
    result = []
    a, b = 0, 1
    while b < 100:
        result.append(b)
        a, b = b, a + b
    return result

In [234]:
fib_hundred2()


Out[234]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

In [235]:
def fib_hundred3(num):
    result = []
    a, b = 0, 1
    while b < num:
        result.append(b)
        a, b = b, a + b
    return result

In [236]:
fib_hundred3(1000)


Out[236]:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

In [ ]:

Find first 10 prime numbers


In [ ]:


In [237]:
if 7 % 2 == 0 or 7 % 3 == 0:
    print('7 is divisible by either 2 or 3')
else:
    print('not divisible by any of them')


not divisible by any of them

Hint

  • create a empty set
  • loop thorugh finite value of numbers
    • while loop incremented by 1
  • check if value is prime
    • create a function named is_prime and pass value through it
  • if return value is prime add it to set
  • if length of set is equals or greater than 10 exit loop

is_prime

  • number that is divisible only by 1 or itself

In [248]:
def is_prime(value):
    if value < 1:
        return False
    for i in range(2, value):
        if value % i == 0:
            return False
    return True

In [250]:
is_prime(7)


Out[250]:
True

In [251]:
primes = set()
num = 1
while len(primes) <= 10:
    if is_prime(num):
        primes.add(num)
    num += 1

In [252]:
primes


Out[252]:
{1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29}

In [258]:
%timeit is_prime(1039)


10000 loops, best of 3: 138 µs per loop

In [254]:
import math

def is_prime2(value):
    if value < 1:
        return False
    for i in range(2, int(math.sqrt(value)) + 1):
        if value % i == 0:
            return False
    return True

In [255]:
is_prime2(101)


Out[255]:
True

In [256]:
is_prime(101)


Out[256]:
True

In [259]:
%timeit is_prime2(1039)


100000 loops, best of 3: 4.94 µs per loop

In [260]:



LICENSE         README.md       session2.ipynb

In [ ]:


In [269]:
def sum_in_loop(num, arr):
    arr = arr.split()
    sum = 0
    for each in arr:
        sum += int(each)
    return sum

In [270]:
sum_in_loop(8, '10 20 30 40 5 6 7 8')


Out[270]:
126

In [272]:
' '.join(['10', '20', '30', '40'])


Out[272]:
'10 20 30 40'

In [273]:
test_data = '''
3830210 1299990 -5253330
-9103720 7965172 4618179
-4156713 2632678 215788
936901 -1932287 -4600085
536108 -9117224 8646093
8804982 8442814 -2933518
-1476911 -631763 -7381075
-6160349 -6630815 9162557
'''

In [274]:
test_data


Out[274]:
'\n3830210 1299990 -5253330\n-9103720 7965172 4618179\n-4156713 2632678 215788\n936901 -1932287 -4600085\n536108 -9117224 8646093\n8804982 8442814 -2933518\n-1476911 -631763 -7381075\n-6160349 -6630815 9162557\n'

In [276]:
test_data.split('\n')


Out[276]:
['',
 '3830210 1299990 -5253330',
 '-9103720 7965172 4618179',
 '-4156713 2632678 215788',
 '936901 -1932287 -4600085',
 '536108 -9117224 8646093',
 '8804982 8442814 -2933518',
 '-1476911 -631763 -7381075',
 '-6160349 -6630815 9162557',
 '']

In [277]:
for data in test_data.split('\n'):
    if data.strip():
        a, b, c = data.strip().split()
        min_of_three(a, b, c)


3830210 1299990 -5253330
-9103720 7965172 4618179
-4156713 2632678 215788
936901 -1932287 -4600085
536108 -9117224 8646093
8804982 8442814 -2933518
-1476911 -631763 -7381075
-6160349 -6630815 9162557

In [278]:
print?

In [279]:
[0]*5


Out[279]:
[0, 0, 0, 0, 0]

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: