In [1]:
'''hello 
hello its me'''


Out[1]:
'hello \nhello its me'

In [2]:
"""heyy how 
are yuo 
byeee"""


Out[2]:
'heyy how \nare yuo \nbyeee'

In [3]:
1
2
3
4
5
6


Out[3]:
6

In [6]:
None
#is null

In [7]:
100/3


Out[7]:
33.333333333333336

In [8]:
b'01010110101'


Out[8]:
b'01010110101'

In [9]:
2**7


Out[9]:
128

In [11]:
"howdy partner "*4


Out[11]:
'howdy partner howdy partner howdy partner howdy partner '

text here


In [12]:
if not True:
    pass
else:
    print("True Inside else")


True Inside else

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


some string

In [18]:
ord('1')


Out[18]:
49

In [21]:
ord('a')


Out[21]:
97

In [23]:
ord(' ')


Out[23]:
32

In [26]:
ord('?')
#ord bhaneko ordinal value


Out[26]:
63

In [27]:
ord('')


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

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

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


true

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


inside else

In [30]:
0.0==True


Out[30]:
False

In [35]:
1==True
#changed to boolean


Out[35]:
True

In [32]:
3== True


Out[32]:
False

In [36]:
' '== True
#tried to compare boolean and string


Out[36]:
False

In [34]:
''== True


Out[34]:
False

In [38]:
''==''
#compared string to string


Out[38]:
True

In [40]:
'hey'=='hey'
#compared string with string


Out[40]:
True

In [43]:
'a'>'b'
#ordinal value is being compared


Out[43]:
False

In [42]:
'b'>'a'


Out[42]:
True

In [47]:
'a'>'A'
#ordinal value is being compared


Out[47]:
True

In [48]:
2<=2


Out[48]:
True

In [49]:
2<3<4


Out[49]:
True

In [50]:
dir(1)


Out[50]:
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__index__',
 '__init__',
 '__int__',
 '__invert__',
 '__le__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__pos__',
 '__pow__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__sub__',
 '__subclasshook__',
 '__truediv__',
 '__trunc__',
 '__xor__',
 'bit_length',
 'conjugate',
 'denominator',
 'from_bytes',
 'imag',
 'numerator',
 'real',
 'to_bytes']

In [51]:
dir('')


Out[51]:
['__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 [53]:
'ABC'.lower()


Out[53]:
'abc'

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


Out[54]:
'CAPITAL'

In [55]:
'suravi'.capitalize()


Out[55]:
'Suravi'

In [57]:
'kAThmAnDu'.swapcase()


Out[57]:
'KatHMaNdU'

HW CHECKOUT ALL THEM METHODS https://docs.python.org/3/


In [60]:
complex_number=2 + 4j

complex_number-1


In [61]:
complex_number-1


Out[61]:
(1+4j)

In [62]:
complex_number.real


Out[62]:
2.0

In [63]:
complex_number.imag


Out[63]:
4.0

In [64]:
complex_number.conjugate()


Out[64]:
(2-4j)

string slicing and for/while loops


In [85]:
city='Kathmandu'

In [69]:
(city[2:5])


Out[69]:
'thm'

In [68]:
(city[-1])


Out[68]:
'u'

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


Out[70]:
'u'

In [71]:
city[len(city)-8]


Out[71]:
'K'

In [72]:
city[0]


Out[72]:
'K'

In [74]:
city[1:4]
#till 4 th item not including 4 th item


Out[74]:
'ath'

In [84]:
city[1:7:2]
# the 2 means it tkes every second item
#the default step is 1
#0 1 2 3 4 5 6 7 8
#k a t h m a n d u
#  1 2 1 2 1 2 1
 #   soo the second items are ahn


Out[84]:
'ahn'

In [80]:
city[9]


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

IndexError: string index out of range

In [82]:
city[::-1]
#revrse steps


Out[82]:
'udnmhtaK'

In [83]:
city[::]


Out[83]:
'Kathmndu'

In [87]:
city[-5:-8:-1]
#agadi +ve left to right movement else if front ma -ve bhayee right to left


Out[87]:
'mht'

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


Out[88]:
'h'

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


Out[89]:
''

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


K
a
t
h
m
a
n
d
u

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


K
a
t
h
m
a
n
d
u

In [93]:
cities=['kathmandu','biratnagar','pokhara','birgung','hetauda']

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


kathmandu
biratnagar
pokhara
birgung
hetauda

In [95]:
[2,3]+[[3,4],7]


Out[95]:
[2, 3, [3, 4], 7]

In [96]:
cities


Out[96]:
['kathmandu', 'biratnagar', 'pokhara', 'birgung', 'hetauda']

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

In [100]:
cities


Out[100]:
['kathmandu',
 'biratnagar',
 'pokhara',
 'birgung',
 'hetauda',
 'Dhankuta',
 'Dhankuta',
 'Dhankuta']

In [103]:
cities.pop()
# did this 3 times to remove all dhankuta


Out[103]:
'Dhankuta'

In [104]:
cities


Out[104]:
['kathmandu', 'biratnagar', 'pokhara', 'birgung', 'hetauda']

In [105]:
cities[0]


Out[105]:
'kathmandu'

In [106]:
cities[4]


Out[106]:
'hetauda'

In [107]:
cities[3:5]


Out[107]:
['birgung', 'hetauda']

In [108]:
cities[-1]


Out[108]:
'hetauda'

In [109]:
cities.remove('pokhara')

In [110]:
cities


Out[110]:
['kathmandu', 'biratnagar', 'birgung', 'hetauda']

In [111]:
dir (cities)


Out[111]:
['__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 [112]:
cities


Out[112]:
['kathmandu', 'biratnagar', 'birgung', 'hetauda']

In [113]:
cities.insert(1,'pokhara')

In [114]:
cities


Out[114]:
['kathmandu', 'pokhara', 'biratnagar', 'birgung', 'hetauda']

In [115]:
cities.pop(2)


Out[115]:
'biratnagar'

In [117]:
cities


Out[117]:
['kathmandu', 'pokhara', 'birgung', 'hetauda']

In [118]:
cities.extend(['biratnagar','dhankuta','dharan'])

In [119]:
cities


Out[119]:
['kathmandu',
 'pokhara',
 'birgung',
 'hetauda',
 'biratnagar',
 'dhankuta',
 'dharan']

In [123]:
cities[1]='pokara city'

In [124]:
cities


Out[124]:
['kathmandu',
 'pokara city',
 'birgung',
 'hetauda',
 'biratnagar',
 'dhankuta',
 'dharan']

In [ ]:


In [ ]:

tuple


In [ ]:
#tuple is immutable ie cannot be overwritten

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

In [122]:
dir(name)


Out[122]:
['__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 [126]:
city
#global name is being used


Out[126]:
'hetauda'

In [130]:
for b in city:
    print (b)


h
e
t
a
u
d
a

In [131]:
b


Out[131]:
'a'

In [132]:
city[0]="p"
#string is also immutable


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-132-68b6d7e86971> in <module>()
----> 1 city[0]="p"

TypeError: 'str' object does not support item assignment

In [135]:
city='p'+city[1:]
#used to over write city

In [134]:
city


Out[134]:
'petauda'

In [136]:
city= city[:]+'city'

In [137]:
city


Out[137]:
'petaudacity'

Dictionary


In [139]:
phones={'john doe':'9808244323','jane doe':'9841234532'}
#key is immutable vallue can be list or tuple or string anything
# key must be tuple or number ie mmutable

In [140]:
phones['john doe']


Out[140]:
'9808244323'

In [141]:
phones[0]


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

KeyError: 0

In [142]:
phones.keys()


Out[142]:
dict_keys(['john doe', 'jane doe'])

In [143]:
phones.values()


Out[143]:
dict_values(['9808244323', '9841234532'])

In [144]:
phones.items()


Out[144]:
dict_items([('john doe', '9808244323'), ('jane doe', '9841234532')])

In [145]:
dir(phones)


Out[145]:
['__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 [149]:
for items in phones:
    print(items)


john doe
jane doe

In [150]:
key ='abc'

In [151]:
key


Out[151]:
'abc'

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

In [154]:
key


Out[154]:
'abc'

In [155]:
value


Out[155]:
'xyz'

In [158]:
key, value =('abc','xyz')
#the tuple is unpacked soo 0 value of tupple isassgnedto 0 variable
#this process is calledtupple unpacking

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


('john doe', '9808244323')
john doe
('jane doe', '9841234532')
jane doe

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


john doe
9808244323
jane doe
9841234532

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


9808244323
john doe
9841234532
jane doe

In [178]:
phones['user 1']='2342525'

In [179]:
phones


Out[179]:
{'jane doe': '9841234532', 'john doe': '9808244323', 'user 1': '2342525'}

In [180]:
phones.update({'user 1':'32525434','user 5':' dffdfg'})

In [181]:
phones


Out[181]:
{'jane doe': '9841234532',
 'john doe': '9808244323',
 'user 1': '32525434',
 'user 5': ' dffdfg'}

In [184]:
phones.update({'user 1':'3234'})

In [185]:
phones


Out[185]:
{'jane doe': '9841234532',
 'john doe': '9808244323',
 'user 1': '3234',
 'user 5': ' dffdfg'}

In [ ]:


In [183]:
phones


Out[183]:
{'jane doe': '9841234532',
 'john doe': '9808244323',
 'user 1': '32525434',
 'user 5': ' dffdfg'}

In [ ]:


In [ ]:

sets


In [175]:
#this  is mutable

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

In [171]:
chars


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

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


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

In [200]:
chars.intersection({'a','y','z'})


Out[200]:
{'a'}

In [ ]:


In [ ]:


In [186]:
chars


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

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

In [188]:
chars


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

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

In [190]:
chars


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

conditionals


In [193]:
not []


Out[193]:
True

In [194]:
#empty tuple
tuple()


Out[194]:
()

In [192]:
[]
#empty list is always false


Out[192]:
[]

In [195]:
not tuple()


Out[195]:
True

In [196]:
#tuple with single item thenn comma is compulsary.. comma represnt tuple
(1,)


Out[196]:
(1,)

In [197]:
#empty dictionart
{}


Out[197]:
{}

In [198]:
#empty set
set()


Out[198]:
set()

In [201]:
[] and True


Out[201]:
[]

In [206]:
[1] and True


Out[206]:
True

In [202]:
[] or ''


Out[202]:
''

In [205]:
[1] or ''


Out[205]:
[1]

In [ ]:


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


false

In [207]:
a=[] and True

In [208]:
a


Out[208]:
[]

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

In [210]:
b


Out[210]:
True

In [211]:
a= [] or True

In [212]:
a


Out[212]:
True

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


false

function


In [ ]:


In [214]:
def function_name(argument_list):
    #function body
    pass

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

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


12

In [219]:
def power(a, by=2):
    return(a**by)

In [221]:
power(3)


Out[221]:
9

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


Out[222]:
27

In [223]:
#named argument
power(a=4,by=4)


Out[223]:
256

In [224]:
#named argument
power(by=2,a=3)


Out[224]:
9

In [225]:
#positional argument must preceed named argument
power(5, by=4)


Out[225]:
625

In [226]:
power(a=2,3)


  File "<ipython-input-226-057fa2533aa5>", line 1
    power(a=2,3)
             ^
SyntaxError: positional argument follows keyword argument

fibonacci


In [233]:
def fib_hundred():
    a, b = 0,1
    while b < 100:
        print (b)
        a,b = b,a+b# firstly the vlaues of  and a+b are assigned...right hand side is evaluated first

In [232]:
fib_hundred()


1
1
2
3
5
8
13
21
34
55
89

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

In [241]:
fib_hundred()


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

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

In [235]:
fib_hundred()


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

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

In [245]:
fib_hundred3(1000)


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

problem prime numbers


In [255]:
def prime(a):
    if k==0:
        return 0
    else:
        flag=0
        for i in range(2,a-1):
        
            
            if a%i==0:
                flag=1
                break
        if flag==0:
            print(a," is prime")
            k+=1
        
    return prime(a-1)

In [ ]:


In [256]:
prime(10)


7  is prime
5  is prime
3  is prime
2  is prime
1  is prime
Out[256]:
0

In [265]:
count=[]
def prime(a):
   
    
    if len(count)==10:
        return 0
    else:
        flag=0
        
        for i in range(2,a-1):
            r=a%i
            if r==0:
                flag=1
                break
        if flag==0:
            count.append(a)
            
    return prime(a+1)
prime(1)
count


Out[265]:
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]

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

In [ ]:


In [267]:
is_prime(7)


Out[267]:
True

In [268]:
is_prime(-1)


Out[268]:
True

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

In [271]:
primes


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

In [272]:
%timeit is_prime(101)


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

In [275]:
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 [277]:
is_prime(101)


Out[277]:
True

In [276]:
is_prime2(101)


Out[276]:
True

In [279]:
%timeit is_prime2(1039)


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

In [283]:
%timeit is_prime(1039)


1000 loops, best of 3: 545 µs per loop

In [281]:
#% then tab gives magic functions

In [284]:
%ls


 Volume in drive C has no label.
 Volume Serial Number is 26D1-CCFD

 Directory of C:\Users\suravi\Desktop\python\GIT_pythonsession

05/14/2016  02:52 PM    <DIR>          .
05/14/2016  02:52 PM    <DIR>          ..
05/07/2016  04:20 PM               826 .gitignore
05/14/2016  11:05 AM    <DIR>          .ipynb_checkpoints
05/14/2016  11:21 AM            39,869 basic.ipynb
05/14/2016  02:52 PM            74,970 class2.ipynb
05/13/2016  07:56 PM             2,483 guessing game.ipynb
05/14/2016  09:36 AM            17,603 homework1.ipynb
05/07/2016  04:20 PM             1,099 LICENSE
05/07/2016  04:20 PM                29 README.md
05/07/2016  04:22 PM                 0 test.txt
               8 File(s)        136,879 bytes
               3 Dir(s)  63,234,957,312 bytes free

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

In [ ]:


In [289]:
sum_in_loop(8,'10 20 30 40 50')


Out[289]:
150

In [290]:
arr=('1 2')

In [291]:
arr


Out[291]:
'1 2'

In [298]:
testdata="""339944 831807
745251 463196
489147 734664
327883 590339
109708 326509
470950 137453
333311 115685
366034 639922
98291 28103
510344 461861
608501 523527
266627 630744
944654 361267
879707 536550"""

In [ ]:


In [301]:
for data in testdata.split('\n'):
    if data.strip():
        a,b= data.strip().split()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-301-b20ad2d65ef7> in <module>()
      2     if data.strip():
      3         a,b= data.strip().split()
----> 4         min_of_three(a,b,c)
      5 
      6 

NameError: name 'min_of_three' is not defined

In [ ]:
a

In [304]:
values='''-3172834 3879278
-543468 8398588
-822855 1311568
-7941414 -7317188
5804857 -2961189
-3020836 6778537
2484532 9330548
-1940394 8193555
-3409316 -2375400
-9956179 9525886
7673418 -7243462
-604481 4179370
-5577722 9875565
-8666718 -1207908
-6326421 -8808023
-8496866 500745
5071255 959666
-1100667 -5751599
-7728765 957919
-3068788 8076091
7996729 3910375
4854628 481261
3240924 -7085766
-1325184 9831608
538833 -1281363
9357495 -1787748'''

In [314]:
first = []
second = []
for data in values.split('\n'):
    a,b = data.strip().split()
    first.append(a)
    second.append(b)
print(first)


['-3172834', '-543468', '-822855', '-7941414', '5804857', '-3020836', '2484532', '-1940394', '-3409316', '-9956179', '7673418', '-604481', '-5577722', '-8666718', '-6326421', '-8496866', '5071255', '-1100667', '-7728765', '-3068788', '7996729', '4854628', '3240924', '-1325184', '538833', '9357495']

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [308]:
a


Out[308]:
'9357495'

In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]:


In [ ]: