Python?
Python?
1 Datatypes
• int
• boolean (bool)/(True/False)
• float
• string (str)
• list
• tuple
• set
• dictionary (dict)
1.1 Int
• a = 27
[ ]: 10//3
[ ]: 3
[ ]:
2 String
• String are written between “…”
• String aslo written in ‘…’ (because ’ ’ can be a part of our data)
[ ]: name = "KK"
print(name)
KK
[ ]: name1 = 'kk'
print(name1)
kk
1
[ ]: print(name + name_1) # this is known as string concatenation
KKkk
[ ]: var = "kunal"
var*10
[ ]: 'kunalkunalkunalkunalkunalkunalkunalkunalkunalkunal'
[ ]: age = 21
name_2 = "kunal"
print("my name is "+name_2+ " and my age is ",age) # , is use for seprate the␣
↪data and + for String concatenation
3 Boolean (True/False)
[ ]: print('ankur'>'arora')
# ASCII values
False
[ ]: a = 10
b = 10
a!=b # it means not equal
[ ]: False
[ ]: type(a!=b)
[ ]: bool
4 List
• List are mutable (can be edit)
• Is a datatype in which we can have multiple elements of either same or diffrent datatypes
4.0.1 if in python some words have diffrent colour (which we assign), then those words
are “keyword”
[ ]: lst = [10,20.3,"kk",True]
print(lst)
2
[ ]: type(lst)
[ ]: list
[1]: 12
[ ]: lst1[4]=900
lst1
4.1 Slicing
• Starting index is inclusive
• ending index is exclusive (end index not display)
[ ]: [23, 12]
[6]: # if we not give last index then print till last element
lst1[2:]
[ ]: lst1
[ ]: # skip elements (step size 2 then skip 1 elements) the 3rd position decide how␣
↪many step skip
lst1[0:5:2]
3
[ ]: # skip elements (step size 3 then skip 2 elements)
lst1[0:5:3]
[ ]: [23, 12]
[ ]: lst1
[ ]: lst1.pop()
[ ]: 4
[ ]: lst1
lst1.pop(3)
[ ]: 12
4
[ ]: # removed 3rd index elements
lst1
[ ]: True
10 Set
10.1 In set for Adding element we use add() function instead of append()
10.2 And for deletion we use discard() function
• written between in {}
• data type can be same or diff.
• set does not allow duplicate values
• set is unorderd or unindex
• set is mutable and its elements are immutable
[ ]: s = {10,20,"kk",3.4,True,False}
[ ]: s
[ ]: print("hello")
hello
[ ]: s1 = {23,23,45,23,32}
print(s1)
5
[ ]: s1
[ ]: s1
11
12 Dict
• it is the combination of Key and value pair (key : value)
• IS ALSO THE LIST OF TUPLES ## 3 Functions
• keys()
• values()
• items()
[ ]: d = {'name':'kk','age':21,'location':'pune'}
[ ]: type(d)
[ ]: dict
[ ]: print(d)
[ ]: d['age']
[ ]: 21
[ ]: # Fuctions
d.keys()
[ ]: # Fuction
d.values()
[ ]: # Fuction
d.items()
6
[ ]: dict_items([('name', 'kk'), ('age', 21), ('location', 'pune')])
13 nested
[ ]: # nested list
lst = [1,2,3,[4,5,6,7,8,9,10]]
[ ]: lst
[ ]: lst[3]
[ ]: [4, 5, 6, 7, 8, 9, 10]
[ ]: lst[3][6]
[ ]: 10
[ ]: [7, 8, 9]
[ ]: # nested Tuple
lst1 = [1,2,3,(4,5,6,7,8,9,10)]
[ ]: lst1[3][5]
[ ]: 9
[ ]: t = (1,2,3,(4,5,6,7,8,9,10))
[ ]: lst1 = (1,2,3,[4,5,6,7,8,9,10])
[ ]: lst1[3][5]=200
[ ]: lst1
7
14 len Fuction
14.1 calculate the length of data
[ ]: z = (1,2,3,4,5,6,78,99,0,0,67,747,2)
[ ]: len(z)
[ ]: 13
15
16
17 if & else
• these are keywords
[ ]: a = 17
if a<15:
print("a is less than 15")
else:
print("a is greater than 15")
a is greater than 15
[ ]: a = 12
if a%2==0:
print("a is an even number")
else:
print("a is an odd number")
a is an even number
18
19 elif…
[ ]: # Define one number is greater than others...
a = 10
b = 20
c = 30
if a>b and a>c:
print("a is grater number")
elif b>c and b>c:
print("b is greater number")
else:
8
print("c is greater number")
c is greater number
KKK
KKK
20
hello kk
22
23 LOOPS
• For Loop
• While Loop
• Itreable Datatypes (list,tuples,set,string,dict) in which we can use Loops
9
24
25 For Loop
[ ]: # print one by one elements
# 'x' is new assign variable
l = [1,2,3,4,5,5,6,7]
for x in l:
print(x)
print(l)
1
2
3
4
5
5
6
7
[1, 2, 3, 4, 5, 5, 6, 7]
12
13
1
115
16
45
34 is an even number…!
27 is an odd number
10 is an even number…!
27 is an odd number
10
90 is an even number…!
87 is an odd number
26
[ ]: # for loop in STRING
for i in 'kunal':
print(i)
k
u
n
a
l
[ ]: l1 = [34,27,10,27,90,101,45,87]
l2 = []
l3 = []
[ ]: for i in l1:
if i%2==0:
l2.append(i)
print(l2)
print(l2)
print(l3)
[ ]: # square of numbers
l = [1,2,3,4,5,6,7,8,9,10]
11
for i in l:
print(i*i)
1
4
9
16
25
36
49
64
81
100
[ ]: # set
s = {23,123,34,5,67,45,8}
for i in s:
print(i)
34
67
5
23
8
123
45
[ ]: # dict
# also use all function of dict...??????????????????????
d = {'name':'kunal','age':21}
for i in d:
print(i)
name
age
27
28 while loop
• always use increment in while loop
• it has three keywords :- Pass, continue, break
[ ]: x = 0
while x<10:
print("x is currently :",x)
x = x+1
12
x is currently : 0
x is currently : 1
x is currently : 2
x is currently : 3
x is currently : 4
x is currently : 5
x is currently : 6
x is currently : 7
x is currently : 8
x is currently : 9
[ ]: # also
x = 0
while x<=10:
print("x is currently :",x)
x = x+1
x is currently : 0
x is currently : 1
x is currently : 2
x is currently : 3
x is currently : 4
x is currently : 5
x is currently : 6
x is currently : 7
x is currently : 8
x is currently : 9
x is currently : 10
1 is an odd nnumber
2 is an even number
3 is an odd nnumber
4 is an even number
5 is an odd nnumber
13
6 is an even number
7 is an odd nnumber
8 is an even number
9 is an odd nnumber
10 is an even number
[ ]:
[ ]: l = [1,2,3,4,5,5555555,6,7]
l1 = []
for i in l:
if i%2==0:
l1.append(i)
print(l1)
[2, 4, 6]
28.1 Pass
• its dose nothing at all
• USE:- to check syntax error
[ ]: x = 1
while x<10:
if x%2==0:
pass
else:
print(x)
x = x+1
1
3
5
7
9
28.2 Break
• breaks out of the current cloosest enclosing loop
[ ]: x = 0
while x<5:
print("x is :",x)
x = x+1
14
if x==3:
print("currently oon 3")
break
print("KK")
x is : 0
x is : 1
x is : 2
currently oon 3
KK
29 Input (Fuction)
• USE TYPECAST
[ ]: age = int(input("enter your age: "))
[ ]: pwd = 123
x = 0
while x<5:
otp = int(input("Enter your pwd: "))
x = x+1
if pwd==otp:
print("transaction complete")
break
else:
print("invalid retry")
if x > 4:
print("attempt exceeded")
29.1 continue
• goes to the top of the current clossest enclosing loop
30 operator / function
30.1 1] range()
• teh range function allows to quikly generate set (not data type set) between the specified
values
• ending point will be exclusive
15
[ ]: list(range(1,10))
[ ]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
[ ]: set(range(1,11))
[ ]: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
[ ]: [1, 4, 7]
[ ]: lst
[ ]: [100, 100, 100, 100, 100, 60, 70, 80, 90, 100]
[ ]: lst = [10,20,30,40,50,60,70,80,90,100]
for i in range(0,10,3):
lst[i]=100
[ ]: lst
[ ]: [100, 20, 30, 100, 50, 60, 100, 80, 90, 100]
30.3 3] zip()
[ ]: lst1 = [1,2,3,4,5]
lst2 = ['a','b','c','d','e','f']
list(zip(lst1,lst2))
[ ]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
[ ]: #....
tuple(zip(lst1,lst2))
[ ]: ((1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'))
[ ]: tuple(zip(lst1,lst2,lst1))
16
[ ]: ((1, 'a', 1), (2, 'b', 2), (3, 'c', 3), (4, 'd', 4), (5, 'e', 5))
[ ]: dict(zip(lst2,lst1))
[ ]: set(zip(lst1,lst2))
[ ]: {(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')}
[ ]: print(set(zip(lst1,lst2)))
{(1, 'a'), (3, 'c'), (5, 'e'), (4, 'd'), (2, 'b')}
[ ]: 10
[ ]: lst = [1,2,0,10]
min(lst)
[ ]: 0
[ ]: lst = ['kk','kkk','kkkk']
max(lst)
[ ]: 'kkkk'
31 in operator
[ ]: 'k' in ['x','y','k','z']# its just check given elements
[ ]: True
32 Library
[ ]: from random import randint
randint(0,3)
[ ]: 0
17
33
34
35 List Comprehensions
[ ]: lst = [1,2,3,4,5,6,7,8,9,10]
[x*x for x in lst] # here we written operation before the for loop
# here print operation written in start
[ ]: [False, True, False, True, False, True, False, True, False, True]
[ ]: [2, 4, 6, 8, 10]
lst = [3,5,6,8,9]
[x+2 if x%2==0 else x+3 for x in lst]
36 split()
• output is list
[ ]: s = "hello world.. .."
s.split(" ")
37
[ ]: abs(10-20)
[ ]: 10
18
38 Function & methods
• Functions are a piece of code/innstructions which we use to achieve a specific functionality.
#####
• Why do we need functions…?
• To reduce length of code and code complexity. #####
• Two types of functions:-
• 1. in-built function
• 2. user defined fucntion (UDF) #####
• There are two thing in functions:-
• 1. Function definition
• 2. Function call
39 in-bulit function
[ ]: lst = [1,1,1,2,2,2,2,2,3,3,4,5,6,7,7,7,7,7]
# lst1 = []
# for i in lst:
# if i==2:
# lst1.append(i)
# len(lst1)
k = 0
for i in lst:
if i==2:
k = k+1
print(k)
40 count() function
• Count total number of arguments in a list, tuple,…(arguments given by user)
[ ]: lst.count(2)
[ ]: 5
19
41
[ ]: lst = [1,2,3,4,5,6]
lst1= [7,8,9]
for i in lst1:
lst.append(i)
lst
[ ]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
42 extend() function
• Add more than one elements in a list, tuple,…
[ ]: lst.extend([10,11,12])
[ ]: lst
43 index() function
• Give index number of specified number.
[ ]: lst = [12,243,45,4,5657,68787,989,8978978,8]
lst.index(989)
[ ]: 6
44
20
45.1 Function without arguments.
[ ]: def addition():
a = 30
b = 20
print(a+b)
[ ]: addition()
50
[ ]: def printer():
print("hello","world")
[ ]: printer()
hello world
[ ]: # 2.....
def add(num1,num2):
print(num1+num2)
[ ]: add(2,5)
[ ]: # 3.
def add():
num1 = int(input("enter no 1: "))
num2 = int(input("enter no 2: "))
return(num1+num2)
[ ]: sum = add()
enter no 1: 23
enter no 2: 23
[ ]: print(sum)
46
21
46
47 10/10/23
[ ]: # nasted statement and scope
[ ]: def cal(num1,num2):
if num1%2==0 and num2%2==0:
return num1+num2
elif num1%2!=0 and num2%2!=0:
return abs(num1-num2)
else:
return num1*num2,num1/num2
[ ]: cal(2,2)
[ ]: 4
[ ]: cal(3,5)
[ ]: 2
[ ]: cal(2,3)
[ ]: (6, 0.6666666666666666)
[ ]: 2+2+2
[ ]: 6
[ ]:
[ ]:
lambda-map-filter
[ ]: # MAP..... its give boolean output(true and false)
def square(num1):
return num1*num1
lst = [1,2,3,4,5,6,7,8]
list(map(square,lst))
22
list(map(even,lst))
[37]: [False, True, False, True, False, True, False, True, False, True]
[ ]: list(map(lambda num:num*num,[1,2,3,4,5]))
[ ]: # *args
# we can input more than one arguments
# stores the data in tuple
def add(*args):
print(args)
return sum(args)
[ ]: add(1,2,3,4)
(1, 2, 3, 4)
[ ]: 10
[ ]: def test(*args):
for i in args:
print(i)
[ ]: test("my","kk")
my
kk
my names is kunal
[ ]: # **kwargs
# keyword-arguments
[36]: addition(2,3)
2
3
23
[36]: 5
[ ]: # default arguments
def add(a=10,b=20):
return a+b
[ ]: add()
[ ]: 30
[ ]: add(2,3)
[ ]: 5
[ ]: add(2)
[ ]: 22
[ ]: add(b=2)
[ ]: 12
[ ]: def add1(a=10,b):
return a+b
[ ]: add1(2)
[ ]: 12
[ ]: add1(2,20) # overwite
[ ]: 22
24
^
SyntaxError: positional argument follows keyword argument
debited : 2000
48
49
class sample:
a = 10
b = 40
print(a+b)
50
[1]: print(a)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
25
Cell In[1], line 1
----> 1 print(a)
[8]: print(sample.a)
10
[9]: print(sample.b)
40
[12]: 10
[13]: 40
[16]: 10
[17]: x.b
[17]: 40
print(x.a)
10
[22]: print(x.b)
40
26
[24]: x.a = 100
[25]: print(x.a)
100
[28]: print(sample.a)
200
100
[32]: kk = sample()
kk.a
[32]: 200
[35]: d = demo()
[37]: demo.addition(10,20)
[37]: 30
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[39], line 1
----> 1 d.addition(10,20)
27
def multiplication(a,b):
return a*b
def division(a,b):
return a/b
[46]: 6
[54]: c = calculator()
c.addition(2,3)
[54]: 5
[51]: k = demo() # Here we create object and that same moment called special function
[1]: #18/10/23
[3]: sam.out_breed
28
[3]: 'labrador'
[11]: dog.species
[11]: 'mammal'
[12]: dog.breed
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[12], line 1
----> 1 dog.breed
[14]: sam.breed
[14]: 'lab'
[15]: sam.name
[15]: 'ruby'
29
50.11 1. Create a class named Circle, take the value of pi as 3.14 in a variable.
50.12 2. As soon as the object of the class is created, it should return the area
of circle with default radius as 1
50.13 3. Create a function setRadius(), which takes radius as argument and
when you call that function, it will change the original value of radius as
well and it should return the new area with new radius.
50.14 4. Create a function getCircumference()
[34]: # class circle:
# pi = 3.14
# def __init__(self,radius = 1):
# self.rad = 1
# pi = 3.14
# area = pi*(r*r)
def setRadius(self,new_radius):
self.radius = new_redius
self.area = new_radius*new_radius*self.pi
print(self.area)
def getcircumference(self):
return self.radius*self.pi*2
[19]: k = circle()
3.14
[20]: k.setRadius(2)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[20], line 1
----> 1 k.setRadius(2)
30
NameError: name 'new_redius' is not defined
[29]: k.circumference()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[29], line 1
----> 1 k.circumference()
51 inheritance
is a way of to access elements present in one class, using the object of another class
To create a class that inherits the functionality from another class, send the parent class as a
parameter when creating the child class:
[3]: class animal:
def __init__(self):
print("animal classs created")
def eat(self):
print('eating')
def bark(self):
print('woof')
[4]: a = animal()
[5]: d = dog()
[6]: a.eat()
eating
[7]: d.bark()
31
woof
[8]: d.eat()
eating
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[10], line 1
----> 1 a.bark()
52 polymorphism
same object classes can share same method name (those called from same palce)…access by object
The word “polymorphism” means “many forms”, and in programming it refers to meth-
ods/functions/operators with the same name that can be executed on many objects or classes.
Polymorphism is often used in Class methods, where we can have multiple classes with the same
method name
[13]: class car:
def __init__(self,brand,model):
self.brand = brand
self.model = model
def move(self):
print("Drive !")
class ship:
def __init__(self,brand,name):
self.brand = brand
self.name = name
def move(self):
print("Sail !")
[14]: c = car('bmw','x5')
[15]: s = ship('ruby','R76')
[17]: c.move()
Drive !
32
[18]: s.move()
Sail !
53
54 format function
[2]: name = 'kunal'
age = 27
print("my name is {} and my age is {}".format(name,age))
56
57 special methods
[31]: class book:
def __init__(self,name,author,pages):
print('book is created')
self.name = name
self.author = author
self.pages = pages
def __str__(self):
print("name : {}".format(self.name))
print("author : {}".format(self.author))
33
def __len__(self):
return self.pages
book is created
[33]: print(b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[33], line 1
----> 1 print(b)
[34]: len(b)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[34], line 1
----> 1 len(b)
58
59 Exception Handling
try: (inside this write code)
except: (print)
34
[4]: a = 10
b = '20'
print(a+b)
c = 2
d = 4
print(c+d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[4], line 4
1 a = 10
2 b = '20'
----> 4 print(a+b)
6 c = 2
7 d = 4
[2]: try:
a = 10
b = '20'
print(a+b)
except:
print('you can not add integer with string')
35
while x<3:
try:
otp1 = int(input("enter your otp"))
if otp==otp1:
print("transaction complete")
break
else:
print("invalid retry")
x = x+1
except:
print("plese enter numeric value")
x = x+1
[ ]:
36