PythonNotesV1 0
PythonNotesV1 0
isinstance(2, int)
type() method gives you the type, used for chekcking
isinstance() returns bool there works for checking and can be used as statement in code
In [1]: l = [1,2,3,4,5]
l[3]
s = l[2]
isinstance(s,int)
Out[1]: True
if isinstance(lmn, list):
s = set(lmn)
print(s)
{1, 2, 3}
range(0, 6)
[0, 1, 2, 3, 4, 5]
<class 'range'>
3. bool()
In [46]: #converts non empty string or non zero numeric value to True bool﴾5﴿, bool﴾' '﴿
#converts empty string or zero numeric value to False bool﴾0﴿, bool﴾''﴿
bool(234)
bool(0)#False
bool('') #False
bool(' ')
Out[46]: True
In [5]: s = input()
if bool(s):
print(s)
else:
print('It is empty')
hello
hello
4. Format Specifier
In [6]: # pi_approx = 22 / 7
# print﴾f'The value of pi is approximately {pi_approx:.2f}'﴿
#print﴾'The value of pi is approximately {:.2f}'.format﴾pi_approx﴿﴿
#print﴾f'The value of pi is approximately %.2f'%﴾pi_approx﴿﴿
#print﴾'{0:5d}'.format﴾1﴿﴿
#print﴾'{:5d}'.format﴾111111﴿﴿
# :.2f, %.2f
pi = 3.146957846393
f'{pi:.2f}'
print('{}'.format(pi))
print('{:.3f}'.format(pi))
print('{0:5d}'.format(1))
print('{0:5d}'.format(123))
3.146957846393
3.147
1
123
print('**********************')
l = [1,2,3,4,5,6,7, 0]
if 9 not in l:
print('not found')
if 0 in l:
print('found')
True
**********************
not found
found
In [8]: #example2:
s = '76544666666'
if 6*'6' in s:#6 cannot be repeated more than 5 times continously
print('invalid')
if '9812' not in s:
print('valid')
invalid
valid
True True
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
8. sizeof
In [13]: #__sizeof__﴾﴿
Out[14]: 524
0
1
2
In [17]: #eg2:
y = 'abc'
for i in range(len(y)):
print(i)
0
1
2
|123|456|789|
h
e
l
l
o
10. enumerate(iterable)
string, list, tuple are iterable
In [20]: for i in enumerate('hello'):
print(i)
(0, 'h')
(1, 'e')
(2, 'l')
(3, 'l')
(4, 'o')
0 h
1 e
2 l
3 l
4 o
0
1
2
3
4
In [23]: t = 1,2,3
for index, val in enumerate(t):
print(index, val)
0 1
1 2
2 3
In [24]: l = [1,2,3]
for index, val in enumerate(l):
print(index, val)
0 1
1 2
2 3
Out[27]: 1
In [28]: math.exp(1)
Out[28]: 2.718281828459045
Out[29]: 3.141592653589793
nan error
In [32]: random()
Out[32]: 0.05486655111991212
Out[33]: 130
Out[34]: 'b'
Out[35]: 'a'
In [ ]:
In [37]: prmonth(2021,7)
July 2021
Mo Tu We Th Fr Sa Su
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
In [38]: weekday(2021,7,4)
Out[38]: 6
lst: [5, 2, 3]
min value: 2
max value: 5
sum: 10
after sorting: [2, 3, 5]
absolute value of 3.567: 3.567
3.142858 rounded off to 3 digs: 3.143
memory loc is: 140545729149056
Out[40]: 97
a = 4
print(double(a))
print(a)
8
4
a = 's'
print(double('s'))
print(a)
ss
s
l = [1,23,45,7]
print(f'before: {l}')
double(l)
print(f'after: {l}')
print(l)
In [ ]:
x inside: global
x outside: global
In [ ]: # #Example1:
# def foo﴾﴿:
# # print﴾x﴿ # UnboundLocalError: local variable 'x' referenced before assignment
# x = "local"
# print﴾f'x inside foo = {x}'﴿
# x = "global"
# foo﴾﴿
# print﴾f'x outside foo = {x}'﴿
# #Example 2:
# def foo﴾﴿:
# global x
# print﴾f'x inside foo = {x}'﴿
# x=x+1
# print﴾f'x inside foo = {x}'﴿
# x = 10
# print﴾f'x outside foo = {x}'﴿
# foo﴾﴿
# print﴾f'x outside foo = {x}'﴿
# #Example 3:
# def foo﴾﴿:
# print﴾f'x inside foo = {y}'﴿ # SyntaxError: name 'x' is used prior to global declaration
# global y
# y = "global again"
# y = "global"
# foo﴾﴿
# print﴾f'x outside foo = {y}'﴿
17. iter()
In [46]: patients = ['p01','p02','p03','p04']
doctor = iter(patients)
for i in range(5):
print(next(doctor))
p01
p02
p03
p04
StopIteration Traceback (most recent call last)
<ipythoninput4657e52426bdcb> in <module>
2 doctor = iter(patients)
3 for i in range(5):
> 4 print(next(doctor))
StopIteration:
18. Generator
In [42]: def foo(limit):
x = 0
while(x<limit):
yield x* x
yield x* x * x
x += 1
try:
a = foo(4)
print(next(a), next(a))
print(next(a), next(a))
print(next(a), next(a))
print(next(a), next(a))
print(next(a), next(a))
except Exception as e:
print(e)
0 0
1 1
4 8
9 27
print(next(A))
print(next(A))
0
1
for i in A:
print(i)
0
1
2
3
4
0
1
2
3
4
<class 'generator'>
In [ ]:
Out[49]: [1, 2, 3]
10 50
[20, 30, 40]
Mumbai
22.Tuple
possible ‑Immutable, Ordered, Indexed, Iteration possible, Slicing
"T[im] [Ordered] a [Tuple] from an {Indian} {IT} company and {SLICED} into pieces."
"T[im] [immutable] [Ordered] a [Tuple] from an {Indian}(indexing) {IT}(Iterable) company and {SLICED}(slicing) into pieces."
tuple: Immutable, Ordered, Indexed, Iteration possible, Slicing possible
SORTING NOTPOSSIBLE
In [53]: t = 1,2,3
print(t)
#IMMUTABLE
#t[0] = 5 #TypeError: 'tuple' object does not support item assignment
#INDEXABLE
print(t[1])
#ITERABLE
for i in t:
print(i)
#SLICABLE
print(t[::1])
(1, 2, 3)
2
1
2
3
(3, 2, 1)
In [55]: #'Hashable elements in a tuple' example ==> ITEM ASSIGNEMNT NOT POSSIBLE
t = (1,2,3)
print(t[0])
t[0] = 77 #'tuple' object does not support item assignment
1
TypeError Traceback (most recent call last)
<ipythoninput55eda4d066cf5f> in <module>
2 t = (1,2,3)
3 print(t[0])
> 4 t[0] = 77 #'tuple' object does not support item assignment
2
3
(1, 2, 3)
{1, 2, 3}
TypeError Traceback (most recent call last)
<ipythoninput5908dc1ffe917f> in <module>
1 #unhashable type cannot be elements
> 2 s1={[1,2,3],[4,5,6]}
3 print(s1) #TypeError: unhashable type: 'list'
In [ ]:
# copying a dict
dict2 = dict(dict1)
dict3 = dict1.copy()
[1, 2, 3, 5]
[10, 20, 30, 50]
[(1, 10), (2, 20), (3, 30), (5, 50)]
Out[6]: {11: 123, 1.1: 234, 'a': 234, (1, 2): 567, True: 6789}
Out[7]: {1: 6789, 1.1: 234, 'a': 234, (1, 2): 567}
5 1 5 15
5 1 5 15
5 1 5 15
5 1 5 15
In [ ]:
34
3
2
1
#misq:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist2 = ['hello' for x in fruits]
print(newlist2)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5)]
[(1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]
[(0, 1, 10), (1, 4, 20), (2, 3, 19), (3, 6, 29)]
['apple', 'banana', 'mango']
[0, 1, 2, 3, 4]
['apple', 'orange', 'cherry', 'kiwi', 'mango']
['hello', 'hello', 'hello', 'hello', 'hello']
xhy
hhh
hhx
hhy
hxh
hxx
hxy
hyh
hyx
hyy
xhh
xhx
xhy
xxh
xxx
xxy
xyh
xyx
xyy
yhh
yhx
yhy
yxh
yxx
yxy
yyh
yyx
yyy
In [67]: # 1,2,3
# 4,5,6
# 7,8,9
#row
# 7,8,9
# 4,5,6
# 1,2,3
n = 3
for i in range(n):
for j in range(n):
print(i,j, '' ,ni1,j)
#out[i][j] = mat[n i 1][j]
0 0 2 0
0 1 2 1
0 2 2 2
1 0 1 0
1 1 1 1
1 2 1 2
2 0 0 0
2 1 0 1
2 2 0 2
In [68]: # 1,2,3
# 4,5,6
# 7,8,9
# #column
# 3,2,1
# 6,5,4
# 9,8,7
n = 3
for i in range(n):
for j in range(n):
print(i,j, '' ,nj1,i)
#out[i][j] = mat[n i 1][j]
0 0 2 0
0 1 1 0
0 2 0 0
1 0 2 1
1 1 1 1
1 2 0 1
2 0 2 2
2 1 1 2
2 2 0 2
print(type(zip(msg, size)))
<class 'zip'>
In [73]: print(list(zip(msg, size))) #list of tuples from corresponding elements from 2 lists
[('hello', 5), ('mars', 4), ('we', 2), ('are', 3), ('coming', 6)]
(('hello', 5), ('mars', 4), ('we', 2), ('are', 3), ('coming', 6))
In [76]: print(set(zip(msg, size))) #the out proves the set is in unordered entity
{('we', 2), ('are', 3), ('mars', 4), ('coming', 6), ('hello', 5)}
29. map()
map function takes 2 different types of parameters a) function name b) parameters of that function
b)parameters of that function in the below example is a list ‑‑> the value gets reflected as it interates over each element
In [83]: a = [10,20,30,40,50]
b = [1,2,3,4,5]
def sub(x,y):
return x y
c = map(sub, a,b) #example 1
print(c)
print(list(c))
def incr(x):
return x+1
d = map(incr, a) #example 2
print(list(d))
30. filter()
In [33]: L = [1,2,3,4,5,6]
print(list(filter(lambda i: i>3, L )))
[4, 5, 6]
In [ ]:
In [91]: ##Example1:
words = ['this', 'is', 'false'] # a list of words
s = ''
for word in words:
s += word + ' ' # appends words to string variable s
print(s) # a string with multiple words
this is false
this is false
In [92]: ##Example2:
words = ['this', 'sentence', 'is', 'false']
s = ' '.join(words)
print(s)
1 2 3
4 5 6
7 8 9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12 34 56
[12, 34, 56]
12
34
56
g o o d
1 2 3
True False
0 1 2
1276
1276
In [97]: t = ('1','2','76')
x = ''.join(t)
print(x)
1276
1276
1276
5. Sort a String
In [100… l = ['c','d','a']
x = ''.join(sorted(l))
print(x)
acd
In [101… x = ''.join(sorted(input()))
print(x)
hello
ehllo
['1,2,3,4,45\n', '34,45,6,7,7,8,9,9,0']
In [103… f = open('test.txt')
lines = f.readlines()
lst = []
for line in lines:
row = [int(num) for num in line.strip().split(',')]
lst.append(row)
print(lst)
print(*lst[0], sep=',')
In [ ]:
MiniPacks
1. OOPS
In [106… #Example of Hierarichal Inheritance
class Person: #Parent Class
def __init__(self, a, b):
self.name = a
self.age = b
def display(self):
print(self.name, self.age)
class Student(Person): #Child 1 Class
def __init__(self,a,b,c):
super().__init__(a,b)
self.marks = c
def display(self):
super().display()
print(self.marks)
class Employee(Person): #Child 2 Class
def __init__(self, a,b,c):
super().__init__(a,b)
self.salary = c
def display(self):
super().display()
print(self.salary)
venu 35
160
priyam 56
50000
obj_1 = Foo()
obj_1.a_method()
obj_2 = Bar()
obj_2.a_method()
obj_3 = FooBar()
obj_3.a_method()
0
10 0
2. Star Variable
In [109… def foo(a, b):
print(a, b)
def bar(*a):
print(a)
lst = [3, 4]
foo(1, 2)
foo(*lst)
bar(lst)
bar(*lst)
bar()
bar(1, 2)
bar(1, 2, 3, 4)
bar(1, 2, *lst)
bar(1, 2, lst)
foobar(1, 2, 3, 4, 5)
foobar(1, 2)
foobar(*lst)
foobar(1, 2, *lst)
foobar(1, 2, 3, *l)
1 2
3 4
([3, 4],)
(3, 4)
()
(1, 2)
(1, 2, 3, 4)
(1, 2, 3, 4)
(1, 2, [3, 4])
1 2 (3, 4, 5)
1 2 ()
3 4 ()
1 2 (3, 4)
1 2 (3, 'c', 'd', 'a')
In [ ]: ## 3. Writing to a File
In [ ]: f = open('file.txt', 'w')
while True:
line = input()
if line == '':
break
f.write(line+'\n')
f.close()
In [ ]:
#alternative method
num = input()
if num[len(num)1] in '05':
print('end with either 0 or 5')
print(num[len(num)1])
else:
print('any other number')
345678908
any other number
Week 3
'''Problem 1: Find the factorial of the given number'''
In [113… #n = int﴾input﴾﴿﴿
n = 5
# 5 * 4 * 3 * 2 * 1
# 1 * 2 * 3 * 4 * 5
mul = 1
for i in range(1,6): #using for loop
mul *= i
print(mul)
120
In [117… n = 5
mul = 1
while(n>0): #using while loop
mul = mul * n
n = n1
print(mul)
120
In [121… #method2:
num = abs(int(input('Enter a number: ')))
num_str = str(num)
print(len(num_str))
In [127… #method 2
num = str(abs(int(input())))
print(int(num[::1]))
12345
54321
In [138… #method 2
n = input()
if n.isdigit():
if n[::] == n[::1]:
print('palindrome')
else:
print('not palindrome')
1234321
palindrome
'''Problem 1: Find all prime numbers less than the entered number'''
In [139… #method 1
num = int(input('Enter a number: '))
if(num > 2):
print(2, end = ' ')
for i in range(3, num):
flag = False
for j in range(2, i):
if(i % j == 0):
flag = False
break
else:
flag = True
if(flag):
print(i, end = ' ')
Enter a number: 67
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61
In [151… #method 2
def isPrime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
def primeNums(n):
result = []
for i in range(2,n):
if isPrime(i):
result.append(i)
return result
Enter a number: 67
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61
'''Problem 4: Find the length of longest word from the set of words entered by the user'''
In [153… #method 1
word = input('Enter a word: ')
maxLen = 0
while(word != '1'):
count = 0
for letter in word:
count = count + 1
if(count > maxLen):
maxLen = count
word = input('Enter a word: ')
print('The length of longest word is %s' %maxLen)
In [159… # my code
print('input a word and press enter to input second word')
print('input 1 if you have finished entering words')
def wordLen(word):
return len(word)
word = input()
len_word = []
n = []
while(word != str(1)):
len_word.append(word)
n.append(wordLen(word))
word = input()
print(max(n))
Week 4
In [172… #Birthday Paradox
from random import randint
n = 30
lst = []
for i in range(n):
lst.append(randint(1,365))
lst.sort()
print(lst)
i = 0
flag = False
while(i<(len(lst)1)):
if lst[i] == lst[i+1]:
print('Repeats', lst[i])
flag = True
i = i+1
if not flag:
print('Doesnot Repeat')
[10, 34, 92, 100, 117, 135, 135, 152, 159, 175, 176, 201, 202, 227, 238, 251, 259, 261, 262, 293, 310, 315, 32
2, 323, 328, 345, 347, 356, 361, 361]
Repeats 135
Repeats 361
x.append(min)
lst.remove(min)
print(x)
print(lst)
[2, 6, 8, 28, 29, 34, 36, 36, 37, 42, 45, 57, 61, 64, 69, 78, 78, 79, 80, 81, 86, 86, 90, 91, 91]
[]
Week 5
'''Problem 3: Write
form a triangle a Python code using functions which checks whether the input coordinates
or not'''
In [162… '''Approach 1: Using distance between points'''
def distance(xi, yi, xj, yj):
return((((xj xi) ** 2) + ((yj yi) ** 2)) ** 0.5)
Not a triangle
Slope of the line connecting points (1.0, 2.0) and (3.0, 4.0) = 1.0
Slope of the line connecting points (3.0, 4.0) and (5.0, 6.0) = 1.0
Not a triangle
In [ ]:
In [ ]: