Python Basic Tutorial - 2
Python Basic Tutorial - 2
slides
Python Basic
What is Python?
Python is a popular programming language. It was created in
1991 by Guido van Rossum.
AI
It is used for: ,
DL
Web development
D S,
Software development
Mathematics n er ML,
System scripting r ai C,
Computations and Analysis r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
What can Python do? C T B,
p & A 0 n al
ee te ATL 36 ur
Python can be used on a server to create web applications.
d
a ra M 18 jo
Python can be used alongside software to create workflows.
h
b po n, 00 a.
Python can connect to database systems. It can also read and mo
u
S or ho 91 bh
C yt : 8 su
dify files.
Python can be used to handle big data and perform complex mathe
P ob l:
matics. M ai
M
Python can be used for rapid prototyping, or for production‐rea
dy software development.
Why Python?
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 1/15
12/17/2018 PyBasics slides
It is Dynamically typed means no need to declare the variable t
ypes.
Python works on different platforms (Windows, Mac, Linux, Raspb
erry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with
fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be
executed as soon as it is written. This means that prototyping
can be very quick. AI
L,
Python can be treated in a procedural way, an object‐orientated
D
way or a functional way.
,
DS
n er ML,
ai C,
Python Syntax compared to other programming languages
r
ty l T ed m
Python was designed to for readability, and has some similariti
r o
b o ca dd .c
es to the English language with influence from mathematics.
l
ra hni mbe a i
Python uses new lines to complete a command, as opposed to othe
k
h a ec E gm
r programming languages which often use semicolons or parenthes
@
C T B,
es. p & A 0 n al
ee te ATL 36 ur
Python relies on indentation, using whitespace, to define scop
d
h a ra M 18 jo
e; such as the scope of loops, functions and classes. Other pro
b po n, 00 a.
u
S or ho 91 bh
gramming languages often use curly‐brackets for this purpose.
C yt : 8 su
P ob l:
M ai
M
Program1: Initializing Variable
In [2]: x=10
print(x)
print(type(x))
10
<class 'int'>
Program2: Addition
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 2/15
12/17/2018 PyBasics slides
In [15]: x=10
y=12.45
sum=x+y
print(sum)
22.45
Program3: Accessing Numbers
L,
AI
D
In [17]:
,
x=2 DS
y=3.5
n er ML,
z=3j
r ai C,
r ty l T ed o m
print(type(x)) b o ca dd
l .c
print(type(y)) k ra hni mbe a i
print(type(z)) h
a ec E
@ gm
C T B,
p & A 0 n al
<class 'int'>
d ee te ATL 36 ur
a ra M 18 jo
<class 'float'>
h
u b po n, 00 a.
S or ho 91 bh
<class 'complex'>
C yt : 8 su
P ob l:
M ai
Program4: integers
M
In [18]: x = 1
y = 35656222554887711
z = ‐3255522
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'int'>
<class 'int'>
Program5: Float
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 3/15
12/17/2018 PyBasics slides
Program5: Float
In [21]: x = 1.10
y = 1.0
z = ‐35.59
print(type(x))
print(type(y))
print(type(z)) AI
,
DL
<class 'float'> ,
<class 'float'> DS
<class 'float'> n er ML,
r ai C,
r ty l T ed o m
o ca dd .c
Program6: Float with 'e'(power
k
b
ra hni mbe a i l
gm
of 10) p
h
&
a ec E
C T B,
A 0 n al
@
d ee te ATL 36 ur
In [80]: x = 35e3 ha ra M 018 .jo
b o , 0 a
Su orp hon 91 bh
y = 12E4
C yt : 8 su
z = ‐87.7e100
P ob l:
M ai
print(type(x)) M
print(type(y))
print(type(z))
print(x)
print(y)
print(z)
<class 'float'>
<class 'float'>
<class 'float'>
35000.0
120000.0
‐8.77e+101
Program7.1: Complex Number
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 4/15
12/17/2018 PyBasics slides
Program7.1: Complex Number
Basic
In [69]: x = 3+5j
y = 5j
z = ‐5j
print(type(x)) AI
print(type(y)) ,
print(type(z)) DL
,
DS
#Addition of Two Complex Numbers
n er ML,
print(x+y)
r ai C,
r ty l T ed o m
<class 'complex'>
b o ca dd
l .c
<class 'complex'> ra ni be a i
k h m
<class 'complex'> ha ec E @ gm
C T B,
(3+10j) p & A 0 n al
3.0 d ee te ATL 36 ur
5.0 h a ra M 18 jo
u b po n, 00 a.
(2‐3j) S
o r ho 891 bh
C yt : su
P ob l:
M ai
Program7.2: Complex number
M
using complex()
In [70]: #Creating Complex Number using complex() Finction
z = complex(2, ‐3)
print(z)
(2‐3j)
Program7.3: Complex number
addition using complex()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 5/15
12/17/2018 PyBasics slides
In [71]: #Addition of Two Complex Numbers using complex()
print ( complex(2, 3) + complex(4, 5) )
(6+8j)
Program7.3: Complex number
Division using complex() AI
,
DL
In [72]: print ( complex(2, 3) / complex(4, 5) ) ,
DS
r ,
ne ML
(0.5609756097560976+0.0487804878048781j)
r ai C,
r ty l T ed o m
o ca dd .c
Program7.4: Complex number
k
b
ra hni mbe a i l
gm
Multiplication using complex()
p
h
&
a ec E
C T B,
A 0 n al
@
d ee te ATL 36 ur
In [74]: a ra M 18 jo
print ( complex(1, 3) * complex(4, 1) )
h
u b po n, 00 a.
S or ho 91 bh
(1+13j) C t 8 su
Py ob: l:
M ai
M
Program7.5: Real & Imaginary
value of Complex Numbers
In [75]: #Showing the Real Part of the Complex Number after addition
print(x.real)
#Showing the Imaginary Part of the Complex Number after addition
print(x.imag)
3.0
5.0
Program7.6: Complex Number
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 6/15
12/17/2018 PyBasics slides
Program7.6: Complex Number
Length
In [77]: # length of a complex number or Finding the absolute value of a
Complex Number. That is, Sqrt[ i^2 + j^2]
print( abs(complex(3, 4)) )
5.0
AI
,
DL
,
Program8: Casting(Integer)
er L,
DS
i n M
In [24]: x = int(1) # x will be 1 y T ra C,
t l ed o m
y = int(2.8) # y will be 2 r
b o ca dd
l .c
k ra hni mbe
z = int("3") # z will be 3
a i
h a ec E
@ gm
C T B,
print(x)
p & A 0 n al
print(y)
d ee te ATL 36 ur
print(z) ha ra M 018 .jo
b o , 0 a
Su orp hon 91 bh
1 C yt : 8 su
2 P ob l:
M ai
3 M
Program9: Casting(Float)
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 7/15
12/17/2018 PyBasics slides
In [25]: a = float(1) # x will be 1.0
b = float(2.8) # y will be 2.8
c = float("3") # z will be 3.0
d = float("4.2") # w will be 4.2
print(a)
print(b)
print(c)
print(d) AI
,
1.0
DL
,
2.8 DS
3.0
n er ML,
4.2
r ai C,
r ty l T ed o m
b o ca dd
l .c
ra hni mbe i
Program10:Divmod(Int)
h
k
a ec E
C T B, @ gm
a
p & A 0 n al
ee te ATL 36 ur
The divmod() builtin function returns both quotient and
d
a ra M 18 jo
h
b po n, 00 a.
remainder
u
S or ho 91 bh
C yt : 8 su
In [4]: x=9
P ob l:
M ai
y=3 M
z=divmod(x,y)
print(z)
(3, 0)
Program11: DecToBin
In [34]: x=1223
y=bin(x)
print(y)
0b10011000111
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 8/15
12/17/2018 PyBasics slides
Program12: DecToOct
In [11]: x=1223
y=oct(x)
print(y)
0o2307
AI
,
DL
Program13: DecToHex
r ,
DS
,
i ne ML
In [13]: x=1223 ra C,
y T
t l ed m
y=hex(x) r o
print(y) b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
0x4c7 C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Program14: HexToDec
u
S or ho 91 bh
C yt : 8 su
P ob l:
In [35]: x=0x4c7 M ai
y=int(x)
M
print(y)
1223
Program15: OctToDec
In [37]: x=0o2307
y=int(x)
print(y)
1223
Program16: BinToDec
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 9/15
12/17/2018 PyBasics slides
Program16: BinToDec
In [38]: x=0b10011000111
y=int(x)
print(y)
1223
AI
Program17:Print Decimal using
,
DL
S,
Hex er L,
D
i n M
In [39]: x=0o2307 y T ra C,
t l ed o m
print(x) r
b o ca dd
l .c
k ra hni mbe a i
1223 a ec E gm
h
C T B, @
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Program18: Print Decimal
u
h
b po n, 00 a.
S or ho 91 bh
using Oct
C yt : 8 su
P ob l:
M ai
In [40]: x=0b1101011 M
print(x)
107
Program19: Print Decimal
using Bin
In [41]: x=0b1101011
print(x)
107
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 10/15
12/17/2018 PyBasics slides
Program20: Limiting Value of
Integer
There is no limiting value for integers, the number, irrespective
of range, if defined, Python takes it as well
A I
In [6]: x=10000000000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000 D
L,
print(x) ,
DS
er ML,
1000000000000000000000000000000000000000000000000000000000000
n
ai C,
0000000000000000000000000000000000000000000000
r
r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
Program21: Check variable
k
h a ec E
@ gm
C T B,
al
type d
p & A
ee te ATL 36 ur
0 n
h a ra M 18 jo
u b po n, 00 a.
In [43]: x=1223 S or
h o 891 ubh
C yt :
print(isinstance(x,int)) s
P ob l:
print(isinstance(x,float))
M ai
M
True
False
Program22: Printing Float
Values
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 11/15
12/17/2018 PyBasics slides
In [49]: print(float(10))
print(float("‐13.33"))
print(float("nan"))
print(float("NaN"))
# for inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy")) AI
print(float("infinity")) ,
DL
,
10.0 DS
‐13.33
n er ML,
nan
r ai C,
nan
r ty l T ed o m
inf b o ca dd
l .c
inf k ra hni mbe a i
inf h a ec E
@ gm
C T B,
inf p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
Program23: Rounding Off Float
C yt : 8 su
P ob l:
Value with Fraction points
M ai
M
In [54]: print(round(2.675665323, 2))
print(round(2.675665323, 3))
print(round(2.675665323, 4))
2.68
2.676
2.6757
Program24: Rounding Off Float
Value to nearest Integer
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 12/15
12/17/2018 PyBasics slides
In [5]: print(round(2.27566532))
2
In [59]: print(round(2.37566532))
2
AI
Program25: Boolean ,
DL
,
DS
In [86]: print(type(True))
n er ML,
r ai C,
<class 'bool'>
r ty l T ed o m
b o ca dd
l .c
In [87]: print(type(False)) kr
a ni be i
h m a
h a ec E
@ gm
C T B,
<class 'bool'> p
& A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
Program26: Printing ASCII
S or ho 91 bh
C yt : 8 su
Value P ob l:
M ai
M
In [93]: print(ascii(134))
134
In [6]: print(ascii(0o163))
115
In [95]: print(ascii(0x152))
338
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 13/15
12/17/2018 PyBasics slides
In [97]: print(ascii(0b1000101010111110001))
284145
Excercise
Q.1 Take two Variable x & y and assign some values in them. AI
Convert x to Hexadecimal Number and y to Octadecimal ,
DL
Number and Add them with all possible combination of Addition.
,
DS
Conclude the result with observation.r ,
i ne ML
y ra C,
Q2. Take two variable x & y assign some values there. Add
T
t l ed o m
r
o ca dd
these two. Show the, Result in Binary, Hexadcimal &
b l .c
ra hni mbe a i
Octadecimal Format. k
a ec E gm
h
C T B, @
p & A 0 n al
ee te ATL 36 ur
Q3. Print a Hex number without assigning its value into any
d
h a ra M 18 jo
variable.b o , 00 a.
Su orp hon 91 bh
C yt : 8 su
P ob l:
Q4. Print a Oct number without assigning its value into any
M ai
variable. M
Q5. Print a Bin number without assigning its value into any
variable.
Q.6 What is the type of Hex, Oct and Binary numbers in
Python? Demonstrate.
Q.7 Calculate the Value: ((2.56 X 10^5)+(5.22 X 10^4)5)*10
Q.8 Find the ASCII of 123Decimal and 100101001110Binary.
Add these two and find the Conclusion.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 14/15
12/17/2018 PyBasics slides
Q.9 Define two imaginary numbers and multiply them. Print the
Real value of the result
Q.10 What are the basic number or data type in Python?
Demonstrate each.
Q11. Write a program to execute following steps:
AI
1. Take two variable with value 2 & 3. Form a complex number &
,
store in to 'a' D L
,
2. Take another two variable with value 4 & 5. Form a complex
DS
number & store in to 'b' r L,
n e
3. Find the length or absolute values of 'a' & 'b' and store t
M
i
hem in 'c' & 'd'
y T ra C,
m
rt l ed
4. Form another complex number by using 'c & 'd'
c o
a bo ica edd l.
r hn mb i
a k c E g ma
Ch Te B, l@
p & LA 0 n a
e
e te AT 36 ur
d
a ra M 18 jo
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyBasics.slides.html 15/15
12/17/2018 PyConditional slides
Python Conditional Statement
Python has only IFELSE as Conditional statement
SwitchCase is not available in Python
Python supports the usual logical conditions from mathematics: AI
D L,
Equals: a == b
Not Equals: a != b
,
DS
Less than: a < b
n er ML,
Less than or equal to: a <= b
Greater than: a > b r ai C,
Greater than or equal to: a >= b
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
al
Program1
d
p & A
ee te ATL 36 ur
0 n
h a ra M 18 jo
0 .
In [2]: a = 33 ub po n, 10 ha
S or ho 9 b
b = 200 C yt :
8 su
if b > a:
P ob l:
M ai
print("b is greater than a")
M
b is greater than a
Program2: Care the Indentation
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyConditional.slides.html 1/4
12/17/2018 PyConditional slides
In [3]: a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
File "<ipython‐input‐3‐4276c1871af7>", line 4
print("b is greater than a") # you will get an error
^
IndentationError: expected an indented block AI
,
DL
,
DS
Program3: Elif n er ML,
r ai C,
In [4]: a = 33
r ty l T ed o m
b = 33 b o ca dd
l .c
if b > a: k ra hni mbe a i
a ec E
print("b is greater than a")
h @ gm
C T B,
elif a == b: p & A 0 n al
ee te ATL 36 ur
print("a and b are equal")
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
a and b are equal
C yt : 8 su
P ob l:
M ai
Program4: ifelifelse
M
In [5]: a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
a is greater than b
Program5: ifelse
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyConditional.slides.html 2/4
12/17/2018 PyConditional slides
Program5: ifelse
In [6]: a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
AI
b is not greater than a ,
DL
,
DS
er ML,
Program6: Short hand if r
n
ai C,
r ty l T ed o m
In [7]: o ca dd
if a > b: print("a is greater than b")
b l .c
k ra hni mbe a i
a is greater than b h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Program7: Short hand ifelse
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
In [9]: P ob l:
print("A") if a > b else print("=") if a == b else print("B")
M ai
M
A
Program8: Combining
conditions using OR
In [10]: if a > b or a > c:
print("At least one of the conditions are True")
At least one of the conditions are True
Program9: Combining
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyConditional.slides.html 3/4
12/17/2018 PyConditional slides
Program9: Combining
conditions using AND
In [12]: if a > b and a > 200:
print("At least one of the conditions are True")
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyConditional.slides.html 4/4
12/17/2018 PyLoop slides
Python Loop
In Python Loop, different syntaxes are there with there different
meaning.Let we see the syntaxes with programming.
For Loop
AI
,
DL
For loop example1 ,
DS
e r L,
In [2]: #range(final value) n M
i
for i in range(5): y T ra C,
t l ed o m
print(i) r
b o ca dd
l .c
0 k ra hni mbe a i
h a ec E
@ gm
1 C T B,
p & A 0 n al
2
d ee te ATL 36 ur
3
h a ra M 18 jo
4 u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
For loop example2
M ai
M
In [3]: #range(initial value,final value)
for i in range(1,5):
print(i)
1
2
3
4
For loop example3
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyLoop.slides.html 1/4
12/17/2018 PyLoop slides
In [5]: #range(initial value,final value,step size)
for i in range(1,30,3):
print(i)
1
4
7
10
13 AI
16 ,
19
DL
,
22 DS
25
n er ML,
28
r ai C,
r ty l T ed o m
b o ca dd .c
Application of foor loop in Data Dtructure l
k ra hni mbe a i
h a ec E
@ gm
C T B,
For Loop Example4p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
In [9]: b po n, 00 a.
fruits = ["apple", "banana", "cherry"]
u
S or ho 91 bh
for x in fruits:
C yt : 8 su
print(x)
P ob l:
M ai
apple M
banana
cherry
For Loop Example5
In [8]: fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(fruits[i])
apple
banana
cherry
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyLoop.slides.html 2/4
12/17/2018 PyLoop slides
For Loop Example with control statement(break)6
In [10]: fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
apple
AI
,
DL
For Loop Example with control statement(continue)6 ,
DS
In [11]: n er ML,
fruits = ["apple", "banana", "cherry"]
for x in fruits: r ai C,
if x == "banana": or al
ty T ed o m
b c d d l .c
continue
k ra hni mbe a i
print(x)
h a ec E
@ gm
C T B,
p & A 0 n al
apple
d ee te ATL 36 ur
cherry
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
While Loop
P ob l:
M ai
M
While Loop Example1
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyLoop.slides.html 3/4
12/17/2018 PyLoop slides
In [1]: a=0
while a<10:
print(a)
a+=1
0
1
2
3 AI
4 ,
5
DL
,
6 DS
7
n er ML,
8
r ai C,
9
r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
While Loop example2 k
a ec E gm
h
C T B, @
p & A 0 n al
In [2]: a=0 d ee te ATL 36 ur
while a<10:
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
if a==5:
C yt : 8 su
break
P b :
else: Mo il
Ma
print(a)
a+=1
0
1
2
3
4
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyLoop.slides.html 4/4
12/17/2018 PyString slides
Python String
Some Important Points:
1. Python has a builtin string class named "str"
2. String literals can be enclosed by either double or
I
single quotes, although single quotes are moreA
,
commonly used. DL
3. A double quoted string literal can contain single quotes ,
DS
without any fuss (e.g. "I didn't do it") and likewise single
er ML,
n
ai C,
quoted string can contain double quotes.
r
ty l T ed m
4. A string literal can span multiple lines, but there must
r o
o ca dd .c
be a backslash \ at the end of each line to escape the
b l
k ra hni mbe a i
newline. String literals inside triple quotes, """ or ''', can
h a ec E gm
C T B, @
span multiple lines of text.
p & A 0 n al
ee te ATL 36 ur
5. Python strings are "immutable" which means they
d
h a ra M 18 jo
cannot be changed after they are created
u b po n, 00 a.
S or ho 91 bh
6. Characters in a string can be accessed using the
C yt : 8 su
standard [ ] syntax.
P ob l:
M ai
7. Python uses zerobased indexing, so if s is 'hello' s[1]
M
is 'e'. If the index is out of bounds for the string, Python
raises an error.
Demonstration of String
String capitalize()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 1/18
12/17/2018 PyString slides
In [1]: string = "python is awesome."
capitalized_string = string.capitalize()
print('Old String: ', string)
print('Capitalized String:', capitalized_string)
Old String: python is awesome.
Capitalized String: Python is awesome.
String count() AI
,
DL
In [1]: string = "Python is awesome, isn't it?"
,
DS
substring = "is"
n er ML,
count = string.count(substring) i
print("The count 'is':", count) y T ra C,
t l ed o m
r
b o ca dd
l .c
print("The count 'o':",string.count("o",0,len(string)),'\n')
k ra hni mbe a i
The count 'is': 2 a
h e c E
@ gm
C T B,
The count 'o': 2
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
String endswith()
C yt : 8 su
P ob l:
In [2]: M ai
text = "Python is easy to learn."
M
result = text.endswith('to learn')
print(result)
result = text.endswith('to learn.')
print(result)
result = text.endswith('Python is easy to learn.')
print(result)
False
True
True
String startswith()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 2/18
12/17/2018 PyString slides
In [10]: result = text.startswith('to learn')
print(result)
result = text.startswith('Python')
print(result)
result = text.startswith('python')
print(result)
False
True AI
False ,
DL
D S,
String find(): Returns the index of 0th index of the searhing
er ML,
string within main string n
r ai C,
r ty l T ed o m
In [3]: quote = 'Let it be, let it be, let it be'
b o ca dd
l .c
ra hni mbe
result = quote.find('let it')
k a i
a ec E
print("Substring 'let it':", result)
h @ gm
C T B,
result = quote.find('i')
p & A 0 n al
ee te ATL 36 ur
print("Substring 'i':", result)
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
Substring 'let it': 11
C yt : 8 su
Substring 'i': 4
P ob l:
M ai
String index() M
In [3]: sentence = 'Python programming is fun.'
result = sentence.index('is fun')
print("Substring 'is fun':", result)
result = sentence.index('f')
print("Substring 'f':", result)
print("Substring 'y':",sentence.index("y",0,len(sentence)),'\n')
Substring 'is fun': 19
Substring 'f': 22
Substring 'y': 1
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 3/18
12/17/2018 PyString slides
String islower()
In [5]: s = 'this is good'
print(s.islower())
s = 'th!s is a1so g00d'
print(s.islower())
s = 'this is Not good'
print(s.islower())
AI
True ,
True DL
,
False DS
n er ML,
String isupper() r ai C,
r ty l T ed o m
In [15]: b o ca dd
l .c
string = "THIS IS GOOD!"
k ra hni mbe a i
print(string.isupper());
h a ec E
@ gm
C T B,
string = "THIS IS ALSO G00D!"
p & A 0 n al
ee te ATL 36 ur
print(string.isupper());
d
a ra M 18 jo
string = "THIS IS not GOOD!"
h
u b po n, 00 a.
print(string.isupper());
S or ho 91 bh
C yt : 8 su
True P ob l:
True
M ai
M
False
String lower()
In [6]: string = "THIS SHOULD BE LOWERCASE!"
print(string.lower())
string = "Th!s Sh0uLd B3 L0w3rCas3!"
print(string.lower())
this should be lowercase!
th!s sh0uld b3 l0w3rcas3!
String upper()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 4/18
12/17/2018 PyString slides
In [4]: string = "this should be uppercase!"
print(string.upper())
string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())
THIS SHOULD BE UPPERCASE!
TH!S SH0ULD B3 UPP3RCAS3!
String swipecase() AI
,
DL
In [5]: ,
string = "ThIs ShOuLd Be MiXeD cAsEd." DS
print(string.swapcase())
n er ML,
r ai C,
tHiS sHoUlD bE mIxEd CaSeD.
r ty l T ed o m
b o ca dd
l .c
String stripping k ra hni mbe a i
h a ec E
@ gm
C T B,
In [6]: p & A 0 n al
string="~~~Hello~Everyone~~~"
d ee te ATL 36 ur
a ra M 18 jo
print("Original string with Leading & Trailing Strip: ",string.s
h
b po n, 00 a.
trip("~"))
u
S or ho 91 bh
print("Original string with Trailing Strip:
C yt : 8 su
",string.rstrip("~"))
P ob l:
M ai
print("Original string with Leading Strip: ",string.lstrip("~"))
M
Original string with Leading & Trailing Strip: Hello~Everyon
e
Original string with Trailing Strip: ~~~Hello~Everyone
Original string with Leading Strip: Hello~Everyone~~~
String replace()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 5/18
12/17/2018 PyString slides
In [8]: string = 'Python is a good programming'
print (string.replace('good', 'great'))
string1=string.replace('good', 'great')
print(string1)
Python is a great programming
Python is a great programming
String Split: Return a list by spliting the string at Whitespace AI
,
DL
In [21]: string= 'We are learning Python programming' ,
DS
# splits at space
n er ML,
list1=string.split()
r ai C,
print("Splitted String in form of List: ",string.split())
r ty l T ed o m
print("Splitted string, Test List: ",list1)
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
Splitted String in form of List: ['We', 'are', 'learning',
C T B,
'Python', 'programming']
p & A 0 n al
ee te ATL 36 ur
Splitted string, Test List: ['We', 'are', 'learning', 'Pytho
d
a ra M 18 jo
n', 'programming']
h
u b po n, 00 a.
S or ho 91 bh
C t 8 su
String complex(): Formatting a Complex number
Py ob: l:
M ai
In [22]: M
z1 = complex(2, ‐3)
print(z1)
z2 = complex(1)
print(z2)
z=z1+z2
print("Addition result of complex numbers: ",z)
(2‐3j)
(1+0j)
Addition result of complex numbers: (3‐3j)
String len(): Returns an integer which tells us the length of string
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 6/18
12/17/2018 PyString slides
In [23]: string="We are learning Python programming"
print(len(string))
34
String Concatenation
In [24]: str = 'hello world'
AI
print(str+'\n') ,
print(str*2+'\n') DL
print(str+" Hi"+'\n')
,
DS
e r L,
hello world i n M
y T ra C,
t l ed o m
hello worldhello world or
b c a dd
l .c
k ra hni mbe a i
hello world Hi
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
String Slicing
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
In [19]: string="We are learning Python String"
P ob l:
M ai
print(string[0:6])
M
print(string[:6])
print(string[7:len(string)])
print(string[7:])
learning Python String
String Format
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 7/18
12/17/2018 PyString slides
In [27]: print("default arguments")
print("Hello {}, your balance is {}.".format("XXYY", 1000))
print("positional arguments")
print("Hello {0}, your balance is {1}.".format("XXYY", 1000))
print("keyword arguments")
print("Hello {name}, your balance is {blc}.".format(name="XXYY",
blc=1000)) AI
,
DL
print("mixed arguments")
D S,
print("Hello {0}, your balance is {blc}.".format("XXYY", blc=100
0)) n er ML,
r ai C,
default arguments
r ty l T ed o m
o ca dd
Hello XXYY, your balance is 1000.
b l .c
positional arguments k ra hni mbe a i
h a ec E
Hello XXYY, your balance is 1000. @ gm
C T B,
keyword arguments p & A 0 n al
ee te ATL 36 ur
Hello XXYY, your balance is 1000.
d
h a ra M 18 jo
b po n, 00 a.
mixed arguments
u
S or ho 91 bh
Hello XXYY, your balance is 1000.
C yt : 8 su
P ob l:
M ai
String isalnum checking:
M
The isalnum() method returns True if all characters in the string
are alphanumeric (either alphabets or numbers). If not, it returns
False.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 8/18
12/17/2018 PyString slides
In [20]: name = "XYZ123"
print(name.isalnum())
# contains whitespace
name = "X3YZ 5656"
print(name.isalnum())
name = "X22Y13Z34"
print(name.isalnum()) AI
,
DL
name = "XY~" ,
print(name.isalnum()) DS
n er ML,
True
r ai C,
False
r ty l T ed o m
True b o ca dd
l .c
False k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
String isalpha()ee te ATL 36 ur
d
a ra M 18 jo
h
b po n, 00 a.
The isalpha() method returns True if all characters in the string
u
S or ho 91 bh
C yt : 8 su
are alphabets. If not, it returns False.
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 9/18
12/17/2018 PyString slides
In [29]: name = "XYZ"
print(name.isalpha())
name = "XYZ123"
print(name.isalpha())
# contains whitespace
name = "X3YZ"
print(name.isalpha()) AI
,
DL
name = "X22Y13Z34" ,
print(name.isalpha()) DS
n er ML,
name = "XY~" r ai C,
y T d m
print(name.isalpha()) rt l e o
b o ca dd
l .c
True k ra hni mbe a i
False h a ec E
@ gm
C T B,
False p & A 0 n al
False d ee te ATL 36 ur
h a ra M 18 jo
False b
u p o n, 100 a.
S or ho 9 bh
C yt : 8 su
String isdecimal()
P ob l:
M ai
M
The isdecimal() method returns True if all characters in a string
are decimal characters. If not, it returns False.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 10/18
12/17/2018 PyString slides
In [30]: name = "123"
print(name.isdecimal())
name = "XYZ123"
print(name.isdecimal())
# contains whitespace
name = "X3YZ"
print(name.isdecimal()) AI
,
DL
name = "X22Y13Z34" ,
print(name.isdecimal()) DS
n er ML,
name = "XY~" r ai C,
y T d m
print(name.isdecimal()) rt l e o
b o ca dd
l .c
True k ra hni mbe a i
False h a ec E
@ gm
C T B,
False p & A 0 n al
False d ee te ATL 36 ur
h a ra M 18 jo
False b
u p o n, 100 a.
S or ho 9 bh
C yt : 8 su
String isidentifier()
P ob l:
M ai
M
The isidentifier() method returns True if the string is a valid
identifier in Python. If not, it returns False.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 11/18
12/17/2018 PyString slides
In [10]: str = 'Python'
print(str.isidentifier())
str = 'Py thon'
print(str.isidentifier())
str = '22Python'
print(str.isidentifier())
AI
str = '' ,
DL
print(str.isidentifier()) ,
DS
True
n er ML,
False
r ai C,
False
r ty l T ed o m
False b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
al
Exercise1: d
p & A
ee te ATL 36 ur
a ra M 18 jo
0 n
h
b po n, 00 a.
u
S or ho 91 bh
1. Print your First name & Last Name using User Input
C yt : 8 su
2. Take your Name, Roll, Stream, Year & Semester and
P ob l:
M ai
print the details
M
3. Take any name fror user and search for the following:
a) Starting character of the Name and print it
b) Replace all the vowels of the Name with 'x'
c) Count length of the Name
4. Take any name fror user and search for the following:
a) Find whether name contains any vowel and if so,
print the vowel
b) Find index of the vowels in the Name
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 12/18
12/17/2018 PyString slides
c) Count length of the Name
5. Take any name fror user and check whether the name
is in upper case or not, if not make it uppercase and
print
6. Take a mixed case input from user and swap them
7. Take your Name, Roll, Stream, Year & Semester and
print the details using FORMAT
8. Take a name from user. For example, SachineAI
Tendulkar and show: S. Tendulkar ,
DL
9. Take user name as input and check whether user have
D S,
given proper foratted name.
er ML,
10. Take user input and check whether the input contains
n
r ai C,
all decimal values.
r ty l T ed o m
b o ca dd
l .c
Sting Iteration k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
In [32]: str1="abcdefgh"
d ee te ATL 36 ur
a ra M 18 jo
for i in range(len(str1)):
h
u b po n, 00 a.
print(str1[i])
S or ho 91 bh
C yt : 8 su
a P ob l:
b M ai
M
c
d
e
f
g
h
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 13/18
12/17/2018 PyString slides
In [33]: str1="abcdefgh"
for i in str1:
print(i)
a
b
c
d
e AI
f ,
g
DL
,
h DS
n er ML,
In [34]: str1="abcdefgh" r ai C,
for i in str1: r ty l T ed o m
if i=='d': b o ca dd
l .c
continue ak
ra hni mbe a i
h e c E
@ gm
else: C T B,
p & A 0 n al
print(i)
d ee te ATL 36 ur
h a ra M 18 jo
a
u b po n, 00 a.
b S or ho 91 bh
C yt : 8 su
c P ob l:
e M ai
f
M
g
h
In [35]: str1="abcdefgh"
for i in str1:
if i=='d':
break
else:
print(i)
a
b
c
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 14/18
12/17/2018 PyString slides
Reverse a String
In [11]: str1="abcdefgh"
str2=""
for i in range(len(str1)):
str2+=str1[‐(i+1)]
print("Reversed String(Procedure‐1): ",str1[::‐1])
print("Reversed String(Procedure‐2): ",str2) AI
,
DL
Reversed String(Procedure‐1): hgfedcba ,
Reversed String(Procedure‐2): hgfedcba DS
n er ML,
r ai C,
String Aternate Capitalization ty l T ed m
r o
b o ca dd
l .c
In [37]: str1="abcdefgh" k ra hni mbe a i
str2="" h a ec E
@ gm
C T B,
p
for i in range(len(str1)):
& A 0 n al
if i%2==0:
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
str2+=str1[i].upper()
u
S or ho 91 bh
else:
C yt : 8 su
str2+=str1[i].lower()
P ob l:
M ai
print("Reversed String: ",str2)
M
Reversed String: AbCdEfGh
Fetch First Segment of the String
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 15/18
12/17/2018 PyString slides
In [38]: str1="abcd efgh"
str2=""
str3=""
for i in str1:
if i==' ':
break
else:
str2+=i
print(str2) AI
,
abcd
DL
,
DS
Make Abbriviated String n er ML,
r ai C,
In [41]: r ty l T ed o m
b o ca dd
l .c
str1=input("Enter your Full Name(First Name and Last Name: ")
str2=str1[0]+"."
k ra hni mbe a i
ind=str1.index(" ") h a ec E
@ gm
C T B,
print(ind) p & A 0 n al
ee te ATL 36 ur
str3=str1[ind:]
d
a ra M 18 jo
print("Welcome: ",str2,str3)
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Enter your Full Name(First Name and Last Name: Subhadeep Chak
raborty P ob l:
M ai
9 M
Welcome: S. Chakraborty
Check the Sum of positional value of name
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 16/18
12/17/2018 PyString slides
In [44]: alpha="abcdefghijklmnopqrstuvwxyx"
ind=0
str2=input("Enter your Full Name(First Name and Last Name): ")
str1=str2.replace(" ","")
#Making it Spece‐Free
print(str1)
#Make all the character of Name to lower case
str1=str1.lower()
for i in str1: AI
ind+=alpha.index(i)+1 ,
DL
print("Summation of your Name: ",ind) ,
if ind>40 and ind<50: DS
print("Name too Short..") n er ML,
elif ind>50 and ind<60: r ai C,
print("Name is Moderate..")
r ty l T ed o m
elif ind>60 and ind<80: b o ca dd
l .c
ra hni mbe
print("Name is Medium length..")
k a i
h a ec E
@ gm
else: C T B,
p & A 0 n al
print("Name is Perfect")
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Enter your Full Name(First Name and Last Name): Subhadeep Cha
u
S or ho 91 bh
kraborty
C yt : 8 su
SubhadeepChakraborty
P ob l:
Summation of your Name: 203
M ai
Name is Perfect
M
Print Surname First
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 17/18
12/17/2018 PyString slides
In [45]: str1=input("Enter your Full Name(First Name and Last Name: ")
ind=str1.index(" ")
print(ind)
str2=str1[ind:]
str3=str1[:ind]
print("Welcome: ",str2,str3)
Enter your Full Name(First Name and Last Name: Subhadeep Chak
raborty AI
9 ,
Welcome: Chakraborty Subhadeep
DL
,
DS
n er ML,
ai C,
Exercise2 r
ty l T ed o m
r
b o ca dd
l .c
ra hni mbe i
1. Take First and Last name from user and count how
k a
h a ec E gm
many characters are there in the name
C T B, @
p & A 0 n al
2. Take First and Last name from user and count how
ee te ATL 36 ur
d
a ra M 18 jo
many characters are there in the First and Last Name
h
u b po n, 00 a.
S or ho 91 bh
3. Take First and Last name from user and show the
C t 8 su
abbriviated for of Last name first and then print the
Py ob: l:
First Name
M ai
M
4. Take full name as input from user and print in reverse.
5. Take full name as input from user and Show the sum
up of the value of all alphabate w.r.t position.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyString.slides.html 18/18
12/17/2018 PyList slides
Python List
Demonstration of List in Python
The list type is a container that holds a number of other objects,
in a given order. The list type implements the sequence
protocol, and also allows you to add and remove objects from AI
,
the sequence. DL
,
DS
er ML,
Features of List:
n
r ai C,
r ty l T ed o m
o ca dd .c
The list object consists of two internal parts; one object header,
b l
ra hni mbe a i
and one separately allocated array of object references. The
k
a ec E gm
h
C T B, @
latter is reallocated as necessary. al
p & A 0 n
d ee te ATL 36 ur
a ra M 18 jo
The list has the following performance characteristics:
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 1/20
12/17/2018 PyList slides
1. The list object stores pointers to objects, not the actual o
bjects themselves.
The size of a list in memory depends on the number of object
s in the list, not the size of the objects.
2. The time needed to get or set an individual item is constan
t, no matter what the size of the list is
(also known as “O(1)” behaviour).
3. The time needed to append an item to the list is “amortized
constant”; whenever the list needs to allocate
more memory, it allocates room for a few items more than it AI
actually needs, to avoid having to reallocate L,
on each call (this assumes that the memory allocator is fasD
,
t; for huge lists, the allocation overhead may DS
push the behaviour towards O(n*n)).
n er ML,
4. The time needed to insert an item depends on the size of the
r ai C,
list, or more exactly, how many items that
r ty l T ed o m
are to the right of the inserted item (O(n)). In other word
b o ca dd
l .c
s, inserting items at the end is fast, but
k ra hni mbe a i
inserting items at the beginning can be relatively slow, if
a ec E gm
the list is large.
h
C T B, @
p & A 0 n al
5. The time needed to remove an item is about the same as the t
d ee te ATL 36 ur
ime needed to insert an item at the same
a ra M 18 jo
h
b po n, 00 a.
location; removing items at the end is fast, removing items
u
S or ho 91 bh
at the beginning is slow.
C yt : 8 su
6. The time needed to reverse a list is proportional to the lis
P ob l:
t size (O(n)).
M ai
M
7. The time needed to sort a list varies; the worst case is O(n
log n), but typical cases are often a
lot better than that.
Creating a List
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 2/20
12/17/2018 PyList slides
In [19]: list1=[] #<=Empty List crea
tion
list2=[1,2,1,7,8,9,2,3,4,5,6] #<=List with all i
nterger values
list3=["A","B","C","D","E"] #<=List with all C
haracter values
list4=["ABC","CDE","EFG"] #<=List with all S
tring values
list5=[1.4,3.5,5.7,3.991] #<= List of float
A I
values ,
DL
list6=["A",1,7.75,"B","ABC","CDE"] #<=Mixed List
,
DS
n er ML,
Printing List content/Elements ai ,
t y Tr d C m
r l e o
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 3/20
12/17/2018 PyList slides
In [20]: print("List‐1 contents:")
print(list1)
print("\nList‐2 contents:")
print(list2)
print("\nList‐3 contents:")
print(list3)
print("\nList‐4 contents:")
print(list4)
print("\nList‐5 contents:") AI
print(list5) ,
DL
print("\nList‐6 contents:") ,
print(list6) DS
n er ML,
List‐1 contents:
r ai C,
[]
r ty l T ed o m
b o ca dd
l .c
a i e i
List‐2 contents: kr hn mb a
h a ec E
[1, 2, 1, 7, 8, 9, 2, 3, 4, 5, 6] @ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
List‐3 contents:
d
h a ra M 18 jo
b po n, 00 a.
['A', 'B', 'C', 'D', 'E']
u
S or ho 91 bh
C yt : 8 su
List‐4 contents:
P ob l:
['ABC', 'CDE', 'EFG']
M ai
M
List‐5 contents:
[1.4, 3.5, 5.7, 3.991]
List‐6 contents:
['A', 1, 7.75, 'B', 'ABC', 'CDE']
List Methods
Method Description
append(): Adds an element at the end of the list
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 4/20
12/17/2018 PyList slides
clear(): Removes all the elements from the list
copy(): Returns a copy of the list
count(): Returns the number of elements with the specified
value
extend(): Add the elements of a list (or any iterable), to the end
of the current list AI
D L,
index(): Returns the index of the first element with the specified
S,
value D
n er ML,
ai C,
insert(): Adds an element at the specified position
r
r ty l T ed o m
o ca dd
pop(): Removes the element at the specified position
b l .c
k ra hni mbe a i
h a ec E gm
remove(): Removes the item with the specified value
C T B, @
p & A 0 n al
ee te ATL 36 ur
reverse(): Reverses the order of the list sort(): Sorts the list
d
a ra M 18 jo
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
Taking user input to list
P ob l:
M ai
M
In [21]: x=input("Enter a value: ")
list1.append(x)
x=int(input("Enter a value: "))
list1.append(x)
x=float(input("Enter a value: "))
list1.append(x)
print("Updated List‐1: ")
print(list1)
Enter a value: 1
Enter a value: 4
Enter a value: 5
Updated List‐1:
['1', 4, 5.0]
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 5/20
12/17/2018 PyList slides
Appending a List to another List using extend command
In [22]: list1.extend(list2)
print(list1)
['1', 4, 5.0, 1, 2, 1, 7, 8, 9, 2, 3, 4, 5, 6]
Checking Index of List
AI
,
In [23]: #Checking index of an element DL
#Sysntax: list1[<index value>]
,
DS
print(list1[0]) er ML,
print(list1[‐1])
n
r ai C,
ind=int(input("Enter an index value to check element"))
r ty l T ed o m
if ind<len(list1):
b o ca dd
l .c
ra hni mbe
print(str(ind)+"th element is: ",list1[ind])
k a i
else: h a ec E
@ gm
C T B,
& A 0 n al
print("List index out of bounds....")
p
d ee te ATL 36 ur
1 h a ra M 18 jo
u b po n, 00 a.
6 S or ho 91 bh
C yt : 8 su
Enter an index value to check element3
P ob l:
3th element is: 1
M ai
M
List Slicing
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 6/20
12/17/2018 PyList slides
In [24]: # Fetching multiple elements in a sequence from list
print(":::::::Fetch element from Left ro Right:::::::\n")
print("Printing 0th element to 2nd element: ")
print(list1[0:3])
print("\nPrinting upto 3rd element: ")
print(list1[:4])
print("\nPrinting from 3rd element to end: \n")
print(list1[3:])
print("\n:::::::Fetch element from Right to Left:::::::")
A I
print("\nPrinting ‐1st element: ") ,
DL
,
print(list1[‐1]) DS
r ,
ne ML
print("\nPrinting upto ‐3rd element: ")
print(list1[:‐3]) r ai C,
ty l T ed
print("\nPrinting from 3rd element to end: ")
r o m
print(list1[‐3:]) b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 7/20
12/17/2018 PyList slides
:::::::Fetch element from Left ro Right:::::::
Printing 0th element to 2nd element:
['1', 4, 5.0]
Printing upto 3rd element:
['1', 4, 5.0, 1]
Printing from 3rd element to end:
AI
,
[1, 2, 1, 7, 8, 9, 2, 3, 4, 5, 6] DL
,
DS
:::::::Fetch element from Right to Left:::::::
r ,
i ne ML
Printing ‐1st element: y T ra C,
t l ed o m
6 r
b o ca dd
l .c
k ra hni mbe a i
Printing upto ‐3rd element:
h a ec E
@ gm
C T B,
& A 0 n al
['1', 4, 5.0, 1, 2, 1, 7, 8, 9, 2, 3]
p
d ee te ATL 36 ur
a ra M 18 jo
Printing from 3rd element to end:
h
u b po n, 00 a.
S or ho 91 bh
[4, 5, 6]
C yt : 8 su
P ob l:
Length of a list
M ai
M
In [25]: print("Length of List1: ")
print(len(list1))
lnth=len(list1)
Length of List1:
14
Inserting an element into particular index
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 8/20
12/17/2018 PyList slides
In [26]: #Syntax: list.insert(index,element_value)
list1.insert(5,8)
print(list1)
['1', 4, 5.0, 1, 2, 8, 1, 7, 8, 9, 2, 3, 4, 5, 6]
List count
In [27]: AI
#Count the occurance of any element ,
#Syntax: list.count(element) DL
list1.count(1)
,
DS
e r L,
Out[27]: 2 i n M
y T ra C,
t l ed o m
r
Remove an element bo ca dd l .c
k ra hni mbe a i
In [29]: h a ec E
@ gm
#Removing an element from list
C T B,
p & A 0 n al
#Removes the first matching element.
d ee te ATL 36 ur
a ra M 18 jo
#Syntax: list.remove(element_value)
h
b po n, 00 a.
print("List before removal of element: ",list1)
u
S or ho 91 bh
list1.remove(2)
C yt : 8 su
print("List after removal of element: ",list1)
P ob l:
M ai
M
List before removal of element: ['1', 4, 5.0, 1, 8, 1, 7, 8,
9, 2, 3, 4, 5, 6]
List after removal of element: ['1', 4, 5.0, 1, 8, 1, 7, 8,
9, 3, 4, 5, 6]
List pop
In [30]: #Delete an element using pop
list1.pop(4)
print(list1)
['1', 4, 5.0, 1, 1, 7, 8, 9, 3, 4, 5, 6]
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 9/20
12/17/2018 PyList slides
List reverse
In [31]: #Reversing a List
list4.reverse()
print(list4)
['EFG', 'CDE', 'ABC']
Sorting a list AI
,
DL
In [32]: #Sorting a list ,
DS
list2.sort()
n er ML,
print("Sorted List‐2 is: ",list2) i
y T ra C,
t l ed
Sorted List‐2 is: [1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9] o m
r
b o ca dd
l .c
k ra hni mbe a i
List copy h a ec E
@ gm
C T B,
p & A 0 n al
In [34]: ee te ATL 36 ur
#Make a copy of existing list
d
h a ra M 18 jo
b po n, 00 a.
new_list = list2.copy()
u
S or ho 91 bh
print("new_list is: ",new_list)
C yt : 8 su
P ob l:
new_list is: [1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9]
M ai
M
Clear List
In [38]: #Clear a list content but memory allocation still exists
list2.clear()
print(list2)
[]
List Delete
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 10/20
12/17/2018 PyList slides
In [35]: #Delete the memory allocation of a list
del list2
print(list2)
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
NameError Traceback (most rec
ent call last)
<ipython‐input‐35‐c5ad468effd0> in <module>() AI
1 #Delete the memory allocation of a list L,
2 del list2
D
,
‐‐‐‐> 3 print(list2) DS
n er ML,
NameError: name 'list2' is not defined
r ai C,
r ty l T ed o m
b o ca dd .c
Creating a iist by User Input l
k ra hni mbe a i
h a ec E
@ gm
C T B,
In [2]: list1=[] p & A 0 n al
ee te ATL 36 ur
rng=int(input("Enter length of List: "))
d
a ra M 18 jo
for i in range(rng):
h
u b po n, 00 a.
S or ho 91 bh
x=int(input("Enter value: "))
C yt : 8 su
list1.append(x)
P ob l:
print("Prepared List",list1)
M ai
M
Enter length of List: 4
Enter value: 1
Enter value: 2
Enter value: 3
Enter value: 4
Prepared List [1, 2, 3, 4]
Check Items in list
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 11/20
12/17/2018 PyList slides
In [4]: thislist = ["apple", "banana", "cherry"]
item=input("Enter an item name to search: ")
if item in thislist:
print("Yes, 'apple' is in the fruits list")
else:
print("Item not found")
Enter an item name to search: grape
Item not found AI
,
DL
,
DS
Exercise1 n er ML,
r ai C,
r ty l T ed
1. Create a four lists of Four student database where o m
o ca dd .c
each seperate list contains their Name, Roll, Stream,
b l
ra hni mbe a i
Year.Input should be taken from user.
k
a ec E gm
h
C T B, @
& A 0 n al
eg.‐ list1=["name‐1","name‐2","name‐3",name‐4"]
p
ee te ATL 36 ur
list2=["Roll‐1","Roll‐2","Roll‐3","Roll‐4"]
d
a ra M 18 jo
.........
h
u b po n, 00 a.
S or ho 91 bh
2. Take full name of five students as user input and store
C yt : 8 su
Names and Surnames in two seperate lists.
P ob l:
M ai
3. Find the sum of the list:
M
[1,3,1,5,7,9,4,7,12,45,56,57,79,79,35,10,23]
4. Find the product of the list:
[1,3,1,5,7,9,4,7,12,45,56,57,79,79,35,10,23]
5. Find the largest and smallest element of a list where
the list contains 12 unordered numerical items and the
list is created by user input.
6. Reverse a list where the list is being constructed by
user input.
7. Find the even numbers from the list and build a new list
for it: [1,4,2,6,5,3,13,11,67,45,23,90,34,25,27,29,30]
8. Find the odd numbers from the list and build a new list
for it: [1,4,2,6,5,3,13,11,67,45,23,90,34,25,27,29,30]
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 12/20
12/17/2018 PyList slides
9. A list is made up of mixed items such as it contains
string and number both. Seperate the strings and
numbers and place them two seperate lists.
10. Make a list by user input with minimum length 10.
Delete items one by one and simultaneously show the
updated list with its current length.
11. Let a list be:
["mobile","laptop","desktop","tablet","pager","radar"]..... AI
remove te first character from each element of the list ,
DL
and reform the list. ,
DS
n er ML,
ai C,
Multidimensional List r
r
ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
Mutidimensional List is a list where we can accomodate another
k
a ec E gm
h
C T B, @
lists. al
p & A 0 n
d ee te ATL 36 ur
h a ra M 18 jo
Construction of Multidimensional List
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
In [4]: list1=[] #1‐D List
P ob l:
M ai
M
#Now we will see how multidimensional list can be costructed
list2=[]
#Making a multidimensional list
list1.append(list2)
print(list1)
[[]]
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 13/20
12/17/2018 PyList slides
In [5]: list1=[]
a=[]
b=[]
c=[]
d=[]
for i in range(4):
a1=input("Enter Name: ")
b1=int(input("Enter Roll: "))
c1=input("Enter Stream: ") AI
d1=int(input("Enter Year: ")) ,
DL
a.append(a1) ,
b.append(b1) DS
c.append(c1) n er ML,
d.append(d1) r ai C,
list1.append(a) r ty l T ed o m
list1.append(b) b o ca dd
l .c
list1.append(c) ak ch
ra ni mbe a i
h e E @ gm
list1.append(d) C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
print(list1)
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 14/20
12/17/2018 PyList slides
Enter Name: xxyy
Enter Roll: 12
Enter Stream: ece
Enter Year: 3
Enter Name: abcd
Enter Roll: 23
Enter Stream: eee
Enter Year: 3
Enter Name: ece
Enter Roll: 34
AI
,
Enter Stream: ece DL
Enter Year: 3 ,
DS
Enter Name: tttt
n er ML,
Enter Roll: 45
r ai C,
Enter Stream: ece
r ty l T ed o m
Enter Year: 3
b o ca dd
l .c
k ra hni mbe
[['xxyy', 'abcd', 'ece', 'tttt'], [12, 23, 34, 45], ['ece',
a i
'eee', 'ece', 'ece'], [3, 3, 3, 3]]
h a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Fetching elments from multidimensional list
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 15/20
12/17/2018 PyList slides
In [6]: list1=[]
a=[]
b=[]
c=[]
d=[]
for i in range(4):
a1=input("Enter Name: ")
b1=int(input("Enter Roll: "))
c1=input("Enter Stream: ") AI
d1=int(input("Enter Year: ")) ,
DL
a.append(a1) ,
b.append(b1) DS
c.append(c1) n er ML,
d.append(d1) r ai C,
ty l T ed m
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
r o
b o ca dd
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") l .c
list1.append(a) ak ch
ra ni mbe a i
h e E @ gm
list1.append(b) C T B,
p & A 0 n al
list1.append(c)
d ee te ATL 36 ur
a ra M 18 jo
list1.append(d)
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
print(list1)
P ob l:
M ai
print("Showing Students Data:\n")
M
for i in range(len(list1)):
print("Name:",list1[0][i],"Roll:",list1[1][i],"Stream:",list
1[2][i],"Year:",list1[3][i])
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 16/20
12/17/2018 PyList slides
Enter Name: xxxx
Enter Roll: 12
Enter Stream: ece
Enter Year: 3
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~
Enter Name: aaaa
Enter Roll: 23
Enter Stream: ece
Enter Year: 3
AI
,
DL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~ ,
DS
Enter Name: bbbb
n er ML,
Enter Roll: 34
r ai C,
Enter Stream: eee
r ty l T ed o m
Enter Year: 3
b o ca dd
l .c
k ra hni mbe
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
a i
~~~~~~~~~~~~~~~~~~~~~~~~
h a ec E
@ gm
C T B,
Enter Name: cccc
p & A 0 n al
Enter Roll: 34
d ee te ATL 36 ur
a ra M 18 jo
Enter Stream: eee
h
u b po n, 00 a.
S or ho 91 bh
Enter Year: 3
C yt : 8 su
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
P ob l:
~~~~~~~~~~~~~~~~~~~~~~~~
M ai
[['xxxx', 'aaaa', 'bbbb', 'cccc'], [12, 23, 34, 34], ['ece',
M
'ece', 'eee', 'eee'], [3, 3, 3, 3]]
Showing Students Data:
Name: xxxx Roll: 12 Stream: ece Year: 3
Name: aaaa Roll: 23 Stream: ece Year: 3
Name: bbbb Roll: 34 Stream: eee Year: 3
Name: cccc Roll: 34 Stream: eee Year: 3
Fetching an inner element from multidimensional list
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 17/20
12/17/2018 PyList slides
In [19]: ndlist=[1,2,3,[10,20,30,[100,200,300,[1000,2000,3000,[1234]]]]]
#We have to fetch the value 1234
print(ndlist[3])
print(ndlist[3][3])
print(ndlist[3][3][3])
AI
print(ndlist[3][3][3][3]) ,
DL
,
print(ndlist[3][3][3][3][0]) DS
n er ML,
ai C,
[10, 20, 30, [100, 200, 300, [1000, 2000, 3000, [1234]]]]
r
ty l T ed
[100, 200, 300, [1000, 2000, 3000, [1234]]]
r o m
[1000, 2000, 3000, [1234]] b o ca dd
l .c
[1234] k ra hni mbe a i
1234 h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Flatten a list
h
u b po n, 00 a.
S or ho 91 bh
In [20]: C yt : 8 su
ndimlist=[[1,2],[3,4],[5,6]]
P ob l:
flist = [y for x in ndimlist for y in x]
M ai
print(flist) M
[1, 2, 3, 4, 5, 6]
Finding elemnents in a nested ndimensional List
In [32]: if isinstance(ndlist, list):
print(sum([getLength(i) for i in ndlist]))
13
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 18/20
12/17/2018 PyList slides
In [35]: x = eval(input("Enter a number: "))
print(type(x))
Enter a number: 1.2
<class 'float'>
Exercise2 AI
,
DL
1. You have two lists, namely
D S,
l1=[10,12,16,23,24,28,31,32,38,45,47,50,55,58,60]
l2=[2,3,4,5] n er ML,
r ai C,
ty l T ed
You have to find how many and whicg numbers in l1
r o m
b o ca dd
l .c
are divisible by which number in l2. Make seperate list
ra hni mbe a i
k
of them h a ec E
@ gm
C T B,
& A 0 n al
2. Build a matrix or NDList and print its diagonal
p
ee te ATL 36 ur
elements. d
a ra M 18 jo
h
b po n, 00 a.
3. Make a student database(4 students) for NAME,
u
S or ho 91 bh
ROLL, STREAM. Modify the details as per requirement
C yt : 8 su
P ob l:
and print final list
M ai
M
eg. if anyone say to change the ROLL and STREAM t
hen modify it but if ask to change NAME, Decline it.
4. Remove all the odd numbers from a list.
5. Make a student database(4 students) with following
details:
NAME: Should be of minimum 5 characters
ROLL: Should not be negetive and not exceeding to
65
STREAM: Should not otherwise of ECE & EEE
** If other values are given raise an warning
6. Print the even positional elements where main list is of
length 20
7. You have two lists:
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 19/20
12/17/2018 PyList slides
l1=[1,2,34,5,6,7,8,9]
l2=[10,20,30,40,50,60,70,80,90]
Make a list by taking first and last three items from
each lists.
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyList.slides.html 20/20
12/17/2018 PyDict slides
Python Dictionary
Dictionary is actually a type of Hash Table. dictionaries are
indexed by keys, which can be any immutable type; strings and
numbers can always be keys. Tuples can be used as keys if
they contain only strings, numbers, or tuples; if a tuple contains
AI
any mutable object either directly or indirectly, it cannot be used
D L,
as a key. You can’t use lists as keys, since lists can be modified
,
in place using index assignments, slice assignments, or DS
methods like append() and extend(). n er ML,
r ai C,
ty l T ed o m
It is best to think of a dictionary as a set of key: value pairs, with
r
o ca dd .c
b l
k ra hni mbe
the requirement that the keys are unique (within one dictionary).
a i
a ec E gm
A pair of braces creates an empty dictionary: {}. Placing a
h @
C T B,
al
commaseparated list of key:value pairs within the braces adds
p & A 0 n
d ee te ATL 36 ur
a ra M 18 jo
initial key:value pairs to the dictionary; this is also the way
h
b po n, 00 a.
dictionaries are written on output.
u
S or ho 91 bh
C yt : 8 su
P ob l:
The main operations on a dictionary are storing a value with
M ai
some key and extracting the value given the key. It is also
M
possible to delete a key:value pair with del. If you store using a
key that is already in use, the old value associated with that key
is forgotten. It is an error to extract a value using a nonexistent
key.
Syntax:
dict_name={key_name:value}
Creating Empty Dictionary
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 1/16
12/17/2018 PyDict slides
In [1]: dict1={} # You can also use the mapping
dict as dictionary name: dict={}
Accessing Keys
In [2]: # Accessing Keys & Values
dict1.keys()
AI
Out[2]: dict_keys([]) ,
DL
,
Accessing Values DS
n er ML,
In [3]: dict1.values() r ai C,
r ty l T ed o m
Out[3]: dict_values([]) b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
Creating Dictionary #1
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 2/16
12/17/2018 PyDict slides
In [9]: # Inserting elements into dictionary
# Demonstrative
dict1['one']="Welcome to Python"
dict1[1]="Learn Python"
dict1['two']="Programming Language"
dict1[2]="Machine Learning"
print("Printing Value of key['one']")
print(dict1['one'])
print("\nPrinting Value of key[1]") AI
print(dict1[1]) ,
DL
print("\nPrinting Value of key[2]") ,
print(dict1[2]) DS
r ,
ne ML
print("\nPrinting Value of key['two']")
print(dict1['two']) r ai C,
ty l T ed
print("\nPrinting complete dictionary")
r o m
print(dict1) b o ca dd
l .c
ra hni mbe
print("\n Keys of Dictionary")
k a i
h a ec E
@ gm
print(dict1.keys())
C T B,
p & A 0 n al
print("\n Values of Dictionary")
d ee te ATL 36 ur
a ra M 18 jo
print(dict1.values())
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 3/16
12/17/2018 PyDict slides
Printing Value of key['one']
Welcome to Python
Printing Value of key[1]
Learn Python
Printing Value of key[2]
Machine Learning
Printing Value of key['two']
AI
,
Programming Language DL
,
DS
Printing complete dictionary
n er ML,
{'one': 'Welcome to Python', 1: 'Learn Python', 'two': 'Progr
r ai C,
amming Language', 2: 'Machine Learning'}
r ty l T ed o m
b o ca dd
l .c
Keys of Dictionary ra ni be i
k h m a
dict_keys(['one', 1, 'two', 2])
h a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Values of Dictionary
d
a ra M 18 jo
dict_values(['Welcome to Python', 'Learn Python', 'Programmin
h
u b po n, 00 a.
S or ho 91 bh
g Language', 'Machine Learning'])
C yt : 8 su
P ob l:
Creating Dictionary #2
M ai
M
In [1]: # Designing a Dictionary
dicts = {}
keys = range(4)
print(keys)
values = ["Hi", "I", "am", "John"]
for i in keys:
dicts[i] = values[i]
print(dicts)
range(0, 4)
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
Creating Dictionary #3
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 4/16
12/17/2018 PyDict slides
In [4]: l1=[1,2,3,4,5]
t1=(10,20,30,40)
d={'list_key':l1,'tuple_key':t1}
print(d)
{'list_key': [1, 2, 3, 4, 5], 'tuple_key': (10, 20, 30, 40)}
Creating Dictionary #4
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 5/16
12/17/2018 PyDict slides
In [15]: keylist=[]
valmst=[]
d1={}
kval=int(input("Enter the number of key you want to assign: "))
for i in range(kval):
valuelist=[]
k=input("Enter Key name: ")
keylist.append(k)
kv=int(input("Enter the number of element you want to assig
A I
n: ")) ,
DL
for j in range(kv): ,
val=input("Enter the value: ") DS
valuelist.append(val) n er ML,
i
valmst.append(valuelist) ra C,
d1[keylist[i]]=valmst[i] r ty l T ed o m
print(d1) b o ca dd
l .c
k ra hni mbe a i
h a ec E gm
Enter the number of key you want to assign: 3
@
C T B,
Enter Key name: a
p & A 0 n al
ee te ATL 36 ur
Enter the number of element you want to assign: 2
d
h a ra M 18 jo
b po n, 00 a.
Enter the value: 1
u
S or ho 91 bh
Enter the value: 2
C yt : 8 su
Enter Key name: b
P ob l:
Enter the number of element you want to assign: 2
M ai
M
Enter the value: 3
Enter the value: 4
Enter Key name: c
Enter the number of element you want to assign: 5
Enter the value: 6
Enter the value: 7
Enter the value: 3
Enter the value: 4
Enter the value:
{'a': ['1', '2'], 'b': ['3', '4'], 'c': ['6', '7', '3', '4',
'']}
Creating Dictionary #5
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 6/16
12/17/2018 PyDict slides
In [22]: #Manipulating user data in Dictionary
dict = {}
keys = []
values = []
entry=int(input('Enter how many entry you require: '))
#values = ["Hi", "I", "am", "John"]
for i in range(entry):
key=input('Enter Key: ') AI
value=input('Enter Value for key: ') ,
DL
keys.append(key) ,
values.append(value) DS
dict[keys[i]]=values[i] n er ML,
i
#dicts[i] = values[i] ra C,
print(dict) r ty l T ed o m
b o ca dd
l .c
ra hni mbe
Enter how many entry you require: 3
k a i
Enter Key: a h a ec E
@ gm
C T B,
Enter Value for key: 1
p & A 0 n al
Enter Key: b d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Enter Value for key: 2
u
S or ho 91 bh
Enter Key: c
C yt : 8 su
Enter Value for key: 3
P ob l:
{'a': '1', 'b': '2', 'c': '3'}
M ai
M
Copy a Dictionary
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 7/16
12/17/2018 PyDict slides
In [2]: new_dict=dict.copy()
print("dict: ",dict)
print("New Dict: ",new_dict)
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
TypeError Traceback (most rec
ent call last)
<ipython‐input‐2‐acf77514fc9c> in <module>() AI
‐‐‐‐> 1 new_dict=dict.copy() ,
2 print("dict: ",dict)
DL
,
3 print("New Dict: ",new_dict) DS
n er ML,
ai C,
TypeError: descriptor 'copy' of 'dict' object needs an argume
r
nt
r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
Creating a new dictionary from the given sequence of elements
k
a ec E gm
h
C T B, @
with a value provided by the user
p al
& A 0 n
d ee te ATL 36 ur
In [52]: h a ra M 18 jo
b po n, 00 a.
new_dict1 = dict.fromkeys(keys)
u
S or ho 91 bh
print(new_dict1)
C yt : 8 su
P ob l:
{'a': None, 'b': None, 'c': None}
M ai
M
Returning the value for the specified key if key is in dictionary.
In [53]: print('a: ', new_dict.get('a'))
print('b: ', new_dict.get('b'))
print('d: ', new_dict.get('d'))
a: 1
b: 2
d: None
Display a list of dictionary's (key, value) tuple pairs.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 8/16
12/17/2018 PyDict slides
In [54]: print("Key‐Value pairs are: ",new_dict.items())
Key‐Value pairs are: dict_items([('a', '1'), ('b', '2'),
('c', '3')])
Dictionary setdefault() method...It returns value of a key if
available...If not available it insert that key with value
AI
In [55]: d = new_dict.setdefault('d') ,
print('New Dict = ',new_dict) DL
,
print('d = ',d) DS
n er ML,
New Dict = {'a': '1', 'b': '2', 'c': '3', 'd': None}
r ai C,
d = None
r ty l T ed o m
b o ca dd
l .c
ra hni mbe i
Dictionary popitem(): Removes an arbitrary keyvalue pair
k a
h a ec E
@ gm
C T B,
In [56]: p & A 0 n al
result =new_dict.popitem()
ee te ATL 36 ur
d
a ra M 18 jo
print(result)
h
b po n, 00 a.
print(new_dict)
u
S or ho 91 bh
C yt : 8 su
('d', None) P ob l:
M ai
{'a': '1', 'b': '2', 'c': '3'}
M
Check for a key in Dictionary
Removes any specific item from dictionary
In [57]: item=new_dict.pop('b')
print(item)
print(new_dict)
2
{'a': '1', 'c': '3'}
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 9/16
12/17/2018 PyDict slides
Updating the dictionary with the elements from the another
dictionary object or from an iterable of key/value pairs
In [59]: d = {1: "one", 2: "three"}
d1 = {2: "two"}
# updates the value of key 2
d.update(d1)
print("Dictionary 'd' is: ",d) AI
,
DL
d1 = {3: "three"} ,
DS
# adds element with key 3 n er ML,
d.update(d1) r ai C,
ty l T ed
print("Updated dictionary 'd' is: ",d)
r o m
b o ca dd
l .c
ra hni mbe
Dictionary 'd' is: {1: 'one', 2: 'two'}
k a i
h a ec E gm
Updated dictionary 'd' is: {1: 'one', 2: 'two', 3: 'three'}
@
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Check for a key in Dictionary
h
u b po n, 00 a.
S or ho 91 bh
In [18]: C yt : 8 su
#Check for a key in Dictionary
P ob l:
key_check=input('Enter key to check for existance: ')
M ai
if key_check in dict.keys():
M
print("Key is present and value of the key is:")
print(dict[key])
else:
print("Key isn't present!")
Enter key to check for existance: a
Key is present and value of the key is:
2
Deleting a Key from Dictionary
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 10/16
12/17/2018 PyDict slides
In [13]: #Delete a Key
ch=input('Want to delete a key?(y/n): ')
if ch=='y':
key_del=input('Enter the key to delete: ')
if key in dict:
del dict[key_del]
else:
print("Key not found!")
exit(0) AI
print("Updated dictionary") ,
DL
print(dict) ,
else: DS
exit n er ML,
r ai C,
Want to delete a key?(y/n): y
r ty l T ed o m
Enter the key to delete: 2
b o ca dd
l .c
a i e i
Updated dictionary kr hn mb a
h a ec E
{'1': 'www', '3': 'tttt', '4': 'tttt'} @ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Clear all content of Dictionary
h
u b po n, 00 a.
S or ho 91 bh
In [20]: C yt : 8 su
dict.clear()
P ob l:
print("Dict: ",dict)
M ai
M
Dict: {}
Deleting Dictionary memory allocation
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 11/16
12/17/2018 PyDict slides
In [61]: del dict
print(dict)
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
NameError Traceback (most rec
ent call last)
<ipython‐input‐61‐cf9a1fdf4a67> in <module>()
‐‐‐‐> 1 del dict AI
2 print(dict) ,
DL
,
NameError: name 'dict' is not defined DS
n er ML,
r ai C,
ty l T ed
Exercise1 b
r
o ca dd
l .c
o m
k ra hni mbe a i
a ec E gm
1. Create a Dictionary for keeping Data of Students(15
h @
C T B,
p & A al
nos) of NAME, ROLL, STREAM, YEAR. (The Caps
ee te ATL 36 ur
0 n
d
a ra M 18 jo
indicates the keys of Dictionary)
h
b po n, 00 a.
2. Create a Dictionary like Q.1 and filter out the student
u
S or ho 91 bh
C yt : 8 su
details which falls in the category of ROLL no in a
P ob l:
range 3050.
M ai
M
3. Create a Dictionary with User Defined words and their
meanings. Program should be designed such that new
word with meaning can be added in the dictionary.
4. Create a Dictionary to store,modify,delete items in
Market.
5. Create a Dictionary like Q.1 and arrange in ascending
order.
6. Create a Nested Dictionary for the following
instructions:
a) Main Dictionary holds the Key for the STREAM
b) Each key holds a Sub Dictionary
c) Each Subdictionary holds the details for respectiv
e students with keys: NAME, ROLL, YEAR
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 12/16
12/17/2018 PyDict slides
Write a Python script to print a dictionary where the keys are
numbers between 1 and 15 (both included) and the values are
square of keys.
Sample Dictionary {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8:
64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
In [1]: d=dict()
AI
,
for x in range(1,16): DL
d[x]=x**2 ,
DS
print(d)
n er ML,
ai C,
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81,
r
ty l T ed
10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
r o m
b o ca dd
l .c
k ra hni mbe a i
a ec E gm
Write a Python script to merge two Python dictionaries.
h @
C T B,
p & A 0 n al
In [2]: d ee te ATL 36 ur
d1 = {'a': 100, 'b': 200}
a ra M 18 jo
h
b po n, 00 a.
d2 = {'x': 300, 'y': 200}
u
S or ho 91 bh
d = d1.copy()
C yt : 8 su
d.update(d2)
P ob l:
print(d) M ai
M
{'a': 100, 'b': 200, 'x': 300, 'y': 200}
Write a Python program to iterate over dictionaries using for
loops.
In [3]: d = {'Red': 1, 'Green': 2, 'Blue': 3}
for color_key, value in d.items():
print(color_key, 'corresponds to ', d[color_key])
Red corresponds to 1
Green corresponds to 2
Blue corresponds to 3
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 13/16
12/17/2018 PyDict slides
Write a Python program to sum all the items in a dictionary.
In [4]: my_dict = {'data1':100,'data2':‐54,'data3':247}
print(sum(my_dict.values()))
293
Write a Python program to multiply all the items in a dictionary.
AI
In [8]: d = {'data1':100,'data2':100,'data3':247}
,
DL
result=1 ,
DS
for key in d:
n er ML,
result=result *d[key]
r ai C,
print(result) r ty l T ed o m
b o ca dd
l .c
2470000 k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Write a Python program to combine two dictionary adding values
d
a ra M 18 jo
for common keys.
h
b po n, 00 a.
u
S or ho 91 bh
C t 8 su
d1 = {'a': 100, 'b': 200, 'c':300}
Py ob: l:
M ai
d2 = {'a': 300, 'b': 200, 'd':400}
M
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
In [13]: from collections import Counter
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter(d2)
print(d)
Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
Write a Python program to print a dictionary in table format.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 14/16
12/17/2018 PyDict slides
In [4]: my_dict = {'A1':[1,2,3],'A2':[5,6,7],'A3':[9,10,11]}
for row in zip(*([key] + (value) for key, value in sorted(my_dic
t.items()))):
print(*row)
A1 A2 A3
1 5 9
2 6 10
3 7 11 AI
,
DL
Write a Python program to sort a list alphabetically in a ,
DS
dictionary.
n er ML,
r ai C,
In [16]:
r ty l T ed
num = {'n1': [2, 3, 1], 'n2': [5, 1, 2], 'n3': [3, 2, 4]}
o m
b o ca dd
l .c
sorted_dict = {x: sorted(y) for x, y in num.items()}
print(sorted_dict) kr
a ni be i
h m a
h a ec E
@ gm
C T B,
& A 0 n al
{'n1': [1, 2, 3], 'n2': [1, 2, 5], 'n3': [2, 3, 4]}
p
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Write a Python program to get the key, value and item in a
u
S or ho 91 bh
dictionary.
C yt : 8 su
P ob l:
In [21]:
M ai
dict_num = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}
M
print("key value count")
for count, (key, value) in enumerate(dict_num.items(), 1):
print(key,' ',value,' ', count)
key value count
1 10 1
2 20 2
3 30 3
4 40 4
5 50 5
6 60 6
Write a Python program to match key values in two dictionaries.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 15/16
12/17/2018 PyDict slides
Sample dictionary: {'key1': 1, 'key2': 3, 'key3': 2}, {'key1': 1,
'key2': 2}
Expected output: key1: 1 is present in both x and y
In [22]: x = {'key1': 1, 'key2': 3, 'key3': 2}
y = {'key1': 1, 'key2': 2}
for (key, value) in set(x.items()) & set(y.items()):
print('%s: %s is present in both x and y' % (key, value))
A I
,
key1: 1 is present in both x and y
DL
,
DS
n er ML,
Exercise2 r
ty l T ed
ai C,
o m
r
b o ca dd
l .c
ra hni mbe i
1. Create two dictionary with same key(5 keys should be
k a
h a ec E gm
there). Each key contains a numerical value. Create a
C T B, @
p & A 0 n al
new dictionary where the addition of the values of
ee te ATL 36 ur
d
a ra M 18 jo
similar keys will be stored.
h
u b po n, 00 a.
2. Create two dictionary with same key(5 keys should be
S or ho 91 bh
C t 8 su
there). Each key contains a numerical value. Create a
Py ob: l:
new dictionary where the dissimilar items will be
M ai
M
stored.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyDict.slides.html 16/16
12/17/2018 PyFunction slides
Python Function
In Python, function is a group of related statements that perform
a specific task.
Functions help break our program into smaller and modular
chunks. As our program grows larger and larger, functions make AI
,
it more organized and manageable. DL
,
DS
er ML,
Basic Systax
n
r ai C,
r ty l T ed o m
b o ca dd
l .c
def function_name(parameters):
ra hni mbe a i
k
"""docstring""" h
a ec E
@ gm
C T B,
p & A 0 n al
statement(s) d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Above shown is a function definition which consists of following
components. P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 1/11
12/17/2018 PyFunction slides
Keyword def marks the start of function header.
A function name to uniquely identify it. Function naming follow
s the same rules of writing identifiers in Python.
Parameters (arguments) through which we pass values to a functi
on. They are optional.
A colon (:) to mark the end of function header.
AI
L,
Optional documentation string (docstring) to describe what the
D
function does.
,
DS
er ML,
One or more valid python statements that make up the function b
n
ody. Statements must have same indentation level (usually 4 spa
r ai C,
ces).
r ty l T ed o m
b o ca dd
l .c
An optional return statement to return a value from the functio
k ra hni mbe a i
n. a c E gm
Ch Te B, l@
p & LA 0 n a
e
e te AT 36 ur
d
a ra M 18 jo
Working of a Function
u
h
b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
Program1: defining a Function
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 2/11
12/17/2018 PyFunction slides
Program1: defining a Function
In [8]: def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
AI
,
Program2: Calling a Function
S,
DL
D
r ,
In [9]: def greet(name): i ne ML
"""This function greets to y T ra C,
t l ed o m
the person passed in as r
b o ca dd
l .c
parameter"""
k ra hni mbe a i
h a ec E
@ gm
print("Hello, " + name + ". Good Morning!")
C T B,
name=input("Enter Your Name: ")
p & A 0 n al
greet(name) ee e TL 836 our
d t A
b ha ora , M 01 .j
Enter Your Name: Subhadeep Chakraborty
u rp on 10 ha
S 9 b
Hello, Subhadeep Chakraborty. Good Morning!
Co yth : 8 su
P ob l:
M ai
M
Program3: Using Scope
Variables
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 3/11
12/17/2018 PyFunction slides
In [10]: def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Value inside function: 10 AI
Value outside function: 20 ,
DL
,
DS
er ML,
Program4: Using default n
ai C,
Argument r
r
ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
In this function, the parameter "name" does not have a default
C T B,
& A 0 n al
value and is required (mandatory) during a call.
p
d ee te ATL 36 ur
a ra M 18 jo
On the other hand, the parameter "msg" has a default value of
h
u b po n, 00 a.
S or ho 91 bh
"Good morning!". So, it is optional during a call. If a value is
C yt : 8 su
provided, it will overwrite the default value.
P ob l:
M ai
M
Any number of arguments in a function can have a default
value. But once we have a default argument, all the arguments
to its right must also have default values.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 4/11
12/17/2018 PyFunction slides
In [2]: def greet(name, msg = "Good morning!"):
"""
This function greets to the person with the provided message.
If message is not provided, it defaults to "Good morning!"
"""
print("Hello",name + ', ' + msg)
greet("XXYY") AI
greet("AABB","How do you do?") ,
DL
,
Hello XXYY, Good morning! DS
Hello AABB, How do you do?
n er ML,
r ai C,
r ty l T ed o m
.c
Program5: Arbitrary Argument
b o ca dd
l
k ra hni mbe a i
h a ec E
@ gm
C T B,
In [3]: def greet(*names):
p & A 0 n al
ee te ATL 36 ur
"""This function greets all
d
h a ra M 18 jo
b po n, 00 a.
the person in the names tuple."""
u
S or ho 91 bh
C yt : 8 su
# names is a tuple with arguments
P ob l:
for name in names:
M ai
M
print("Hello",name)
greet("Student‐1","Student‐2","Student‐3","Student‐4")
Hello Student‐1
Hello Student‐2
Hello Student‐3
Hello Student‐4
Program6: Recursion
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 5/11
12/17/2018 PyFunction slides
In [18]: # An example of a recursive function to
# find the factorial of a number
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1 AI
else: ,
DL
return (x * calc_factorial(x‐1)) ,
DS
num = 4 n er ML,
ai C,
print("The factorial of", num, "is", calc_factorial(num))
r
r ty l T ed o m
The factorial of 4 is 24 b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
al
Program7: Function
d
p & A
ee te ATL 36 ur
a ra M 18 jo
0 n
Interconnect
u
h
b po n, 00 a.
S or ho 91 bh
C yt : 8 su
In [21]: P ob l:
def msg1():
M ai
print("Hi!!")
M
msg2()
def msg2():
print("Good Morning!!")
print("Main Function initiated")
msg1()
msg2()
print("Welcome back to Main Program")
Main Function initiated
Hi!!
Good Morning!!
Good Morning!!
Welcome back to Main Program
Program7: Global & Loal
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 6/11
12/17/2018 PyFunction slides
Program7: Global & Loal
Variable
In [17]: x=10
def show():
y=12
return y
print("x is global variable with value= ",x) AI
print("y is local variable with value= ",show()) ,
DL
x is global variable with value= 10
,
DS
y is local variable with value= 12
n er ML,
r ai C,
ty l T ed o m
Exercise1
r
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
& A 0 n al
1. Write a program to show the even numbers in range 0
p
ee te ATL 36 ur
50 using function.
d
h a ra M 18 jo
b po n, 00 a.
2. Print sum of a list using function.
u
S or ho 91 bh
3. Build a Small Calculator Program for
C yt : 8 su
SUM,DIFF,MULTI,DIV function.
P ob l:
M ai
4. Write a Python function to find the Max of three
M
numbers.
5. Write a Python function to multiply all the numbers in a
list.
6. Write a Python program to reverse a string.
7. Write a Python function to calculate the factorial of a
number (a nonnegative integer).
8. Write a Python function that takes a list and returns a
new list with unique elements of the first list.
9. Write a Python function that takes a number as a
parameter and check the number is prime or not.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 7/11
12/17/2018 PyFunction slides
Write a Python program to execute a string containing Python
code.
In [5]: mycode = 'print("hello world")'
code = """
def mutiply(x,y):
return x*y
print('Multiply of 2 and 3 is: ',mutiply(2,3)) AI
""" ,
DL
exec(mycode) ,
exec(code) DS
n er ML,
hello world
r ai C,
Multiply of 2 and 3 is: 6
r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
Write a Python function that checks whether a passed string is
k
a ec E gm
h
C T B, @
palindrome or not.
p al
& A 0 n
d ee te ATL 36 ur
In [7]: h a ra M 18 jo
def isPalindrome(string):
b po n, 00 a.
u
S or ho 91 bh
left_pos = 0
C t 8 su
right_pos = len(string) ‐ 1
Py ob: l:
while right_pos >= left_pos:
M ai
M
if not string[left_pos] == string[right_pos]:
return False
left_pos += 1
right_pos ‐= 1
return True
print(isPalindrome('12321'))
True
Write a Program to print Pattern1:
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 8/11
12/17/2018 PyFunction slides
In [10]: def pat1(n):
# outer loop to handle number of rows
# n in this case
for i in range(0, n):
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(0, i+1): AI
,
DL
# printing stars ,
print("* ",end="") DS
n er ML,
# ending line after each row r ai C,
print("\r") r ty l T ed o m
b o ca dd
l .c
n = 5 k ra hni mbe a i
h a ec E
@ gm
pat1(n) C T B,
p & A 0 n al
* d ee te ATL 36 ur
h a ra M 18 jo
* *
u b po n, 00 a.
1 h
* * * S or ho 89 ub
C t s
* * * * Py b: :
* * * * * M ai
o l
M
Write a program to print Pattern2
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 9/11
12/17/2018 PyFunction slides
In [11]: def pat2(n):
# number of spaces
k = 2*n ‐ 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces AI
# values changing acc. to requirement ,
DL
for j in range(0, k): ,
print(end=" ") DS
n er ML,
# decrementing k after each loop
r ai C,
k = k ‐ 2 r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
# inner loop to handle number of columns
k
h a ec E
@ gm
# values changing acc. to outer loop
C T B,
p & A 0 n al
for j in range(0, i+1):
d ee te ATL 36 ur
a
h r a M 018 jo
b po n, 0 a.
# printing stars
u
S or ho 91 bh
C yt : 8 su
print("* ", end="")
P ob l:
M ai
# ending line after each row
M
print("\r")
n = 5
pat2(n)
*
* *
* * *
* * * *
* * * * *
Write a Program to Print Triangle Pattern
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 10/11
12/17/2018 PyFunction slides
In [13]: def pattri(n):
# number of spaces
k = 2*n ‐ 2
# outer loop to handle number of rows
for i in range(0, n):
# inner loop to handle number spaces AI
# values changing acc. to requirement ,
DL
for j in range(0, k): ,
print(end=" ") DS
n er ML,
# decrementing k after each loop
r ai C,
k = k ‐ 1 r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
# inner loop to handle number of columns
k
h a ec E
@ gm
# values changing acc. to outer loop
C T B,
p & A 0 n al
for j in range(0, i+1):
d ee te ATL 36 ur
a
h r a M 018 jo
b po n, 0 a.
# printing stars
u
S or ho 91 bh
C yt : 8 su
print("* ", end="")
P ob l:
M ai
# ending line after each row
M
print("\r")
n = 5
pattri(n)
*
* *
* * *
* * * *
* * * * *
Exercise2
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFunction.slides.html 11/11
12/17/2018 PyHiTea slides
Important Python Packages
Packages :
time
Datetime
time
calender AI
os ,
math DL
,
random DS
itertool er ML,
array n
r ai C,
r ty l T ed o m
b o ca dd
l .c
ra hni mbe i
time Package h
k
a ec E
@ gm
a
C T B,
p & A 0 n al
ee te ATL 36 ur
time constructor
d
h a ra M 18 jo
u b po n, 00 a.
In [4]: S or ho 91 bh
import time
C yt : 8 su
P ob l:
M ai
print('The current time is:', time.time())
M
The current time is: 1544963250.6578877
Printing time with ctime()
In [3]: import time
print('The current time is :', time.ctime())
newtime = time.time() + 20
print('20 secs from now :', time.ctime(newtime))
The current time is : Sun Dec 16 17:56:54 2018
20 secs from now : Sun Dec 16 17:57:14 2018
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 1/27
12/17/2018 PyHiTea slides
Pausing Execution and provide delay time using sleep()
In [5]: import time
# using ctime() to display present time
print ("Begin Execution : ",end="")
print (time.ctime())
# using sleep() to suspend execution AI
print ('Waiting for 5 sec.') ,
DL
time.sleep(5) ,
DS
# using ctime() to show present time
r L,
ne i M
print ("End Execution : ",end="")
y T ra C,
print (time.ctime()) t l ed o m
r
b o ca dd
l .c
ra hni mbe
Begin Execution : Sun Dec 16 17:58:56 2018
k a i
Waiting for 5 sec. h a ec E
@ gm
C T B,
& A 0 n al
End Execution : Sun Dec 16 17:59:01 2018
p
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Printing Day Details
u
S or ho 91 bh
C yt : 8 su
In [6]: import time P ob l:
M ai
M
print(' Current time:', time.ctime())
t = time.localtime()
print(' Day of month:', t.tm_mday)
print(' Day of week :', t.tm_wday)
print(' Day of year :', t.tm_yday)
Current time: Sun Dec 16 18:02:15 2018
Day of month: 16
Day of week : 6
Day of year : 350
Print Time details
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 2/27
12/17/2018 PyHiTea slides
In [46]: import time
now = time.localtime(time.time())
print(time.asctime(now))
print(time.strftime("%d/%m/%y %H:%M", now))
print(time.strftime("%a %b %d", now))
print(time.strftime("%c", now))
print(time.strftime("%I %p", now))
print(time.strftime("%Y‐%m‐%d %H:%M:%S %Z", now)) AI
,
Sun Dec 16 11:58:49 2018
DL
,
16/12/18 11:58 DS
Sun Dec 16
n er ML,
Sun Dec 16 11:58:49 2018
r ai C,
11 AM
r ty l T ed o m
o ca dd
2018‐12‐16 11:58:49 India Standard Time
b l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
al
Date Time Package
d
p & A
ee te ATL 36 ur
0 n
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 3/27
12/17/2018 PyHiTea slides
In [6]: import time
import datetime
print("Current date and time: " , datetime.datetime.now())
print("Current year: ", datetime.date.today().strftime("%Y"))
print("Month of year: ", datetime.date.today().strftime("%B"))
print("Week number of the year: ", datetime.date.today().strftim
e("%W"))
print("Weekday of the week: ", datetime.date.today().strftime("%
w")) AI
L,
print("Day of year: ", datetime.date.today().strftime("%j"))
D
print("Day of the month : ", ,
datetime.date.today().strftime("%d")) DS
r ,
ne ML
print("Day of week: ", datetime.date.today().strftime("%A"))
r ai C,
ty l T ed
Current date and time: 2018‐12‐15 22:39:49.661165
r o m
Current year: 2018 b o ca dd
l .c
Month of year: December
k ra hni mbe a i
h a ec E
Week number of the year: 50 @ gm
C T B,
Weekday of the week: 6
p & A 0 n al
ee te ATL 36 ur
Day of year: 349
d
h a ra M 18 jo
b po n, 00 a.
Day of the month : 15
u
S or ho 91 bh
Day of week: Saturday
C yt : 8 su
P ob l:
M ai
Write a Python program to subtract five days from current date.
M
In [7]: from datetime import date, timedelta
dt = date.today() ‐ timedelta(5)
print('Current Date :',date.today())
print('5 days before Current Date :',dt)
Current Date : 2018‐12‐15
5 days before Current Date : 2018‐12‐10
Write a Python program to print yesterday, today, tomorrow
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 4/27
12/17/2018 PyHiTea slides
In [8]: import datetime
today = datetime.date.today()
yesterday = today ‐ datetime.timedelta(days = 1)
tomorrow = today + datetime.timedelta(days = 1)
print('Yesterday : ',yesterday)
print('Today : ',today)
print('Tomorrow : ',tomorrow)
Yesterday : 2018‐12‐14 AI
Today : 2018‐12‐15 ,
Tomorrow : 2018‐12‐16
DL
,
DS
er ML,
Write a Python program to convert Year/Month/Day to Day of
n
ai C,
Year r
r ty l T ed o m
b o ca dd
l .c
In [9]: import datetime
k ra hni mbe a i
a ec E
today = datetime.datetime.now()
h @ gm
C T B,
& A 0 n al
day_of_year = (today ‐ datetime.datetime(today.year, 1, 1)).days
p
+ 1 d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
print(day_of_year)
u
S or ho 91 bh
349 C yt : 8 su
P ob l:
M ai
M
Write a Python program to get current time in milliseconds
In [10]: import time
milli_sec = int(round(time.time() * 1000))
print(milli_sec)
1544894163030
Write a Python program to get week number
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 5/27
12/17/2018 PyHiTea slides
In [12]: import datetime
print(datetime.date(2018, 12, 15).isocalendar()[1])
50
Write a Python program to get the number of days of a given
month and year
AI
In [15]: from calendar import monthrange ,
year = 2018 DL
,
month =12 DS
print(monthrange(year,month))
n er ML,
r ai C,
(5, 31)
r ty l T ed o m
b o ca dd
l .c
ra hni mbe i
Write a Python program to get the last day of a specified year
k a
h a ec E gm
and month C T B, @
p & A 0 n al
d ee te ATL 36 ur
In [13]: a ra M 18 jo
import calendar
h
u b po n, 00 a.
year = 2015
S or ho 91 bh
C yt : 8 su
month = 2
P ob l:
print(calendar.monthrange(year, month)[1])
M ai
M
28
Calender Package
Python program to show Month Calender
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 6/27
12/17/2018 PyHiTea slides
In [48]: import calendar
yy = 2018
mm = 12
# display the calendar
print(calendar.month(yy, mm))
December 2018
Mo Tu We Th Fr Sa Su
1 2 AI
3 4 5 6 7 8 9 ,
10 11 12 13 14 15 16
DL
,
17 18 19 20 21 22 23 DS
24 25 26 27 28 29 30
n er ML,
31
r ai C,
r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
Python program to show year Calender
k
a ec E gm
h
C T B, @
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 7/27
12/17/2018 PyHiTea slides
In [20]: import calendar
yy = 2018
# display the calendar
print(calendar.calendar(yy))
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 8/27
12/17/2018 PyHiTea slides
2018
January February Ma
rch
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We
Th Fr Sa Su
1 2 3 4 5 6 7 1 2 3 4
1 2 3 4
8 9 10 11 12 13 14 5 6 7 8 9 10 11 5 6 7
I
8 9 10 11
A
15 16 17 18 19 20 21 12 13 14 15 16 17 18 12 13 14
D L,
15 16 17 18 ,
DS
22 23 24 25 26 27 28 19 20 21 22 23 24 25 19 20 21
r ,
22 23 24 25 i ne ML
y T ra C,
29 30 31 26 27 28 26 27 28
t l ed o m
29 30 31 r
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
April May J
C T B,
une
p & A 0 n al
ee te ATL 36 ur
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We
d
a ra M 18 jo
Th Fr Sa Su
h
u b po n, 00 a.
S or ho 91 bh
1 1 2 3 4 5 6
C yt : 8 su
1 2 3
P ob l:
2 3 4 5 6 7 8 7 8 9 10 11 12 13 4 5 6
M i
7 8 9 10 Ma
9 10 11 12 13 14 15 14 15 16 17 18 19 20 11 12 13
14 15 16 17
16 17 18 19 20 21 22 21 22 23 24 25 26 27 18 19 20
21 22 23 24
23 24 25 26 27 28 29 28 29 30 31 25 26 27
28 29 30
30
July August Sept
ember
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We
Th Fr Sa Su
1 1 2 3 4 5
1 2
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 9/27
12/17/2018 PyHiTea slides
2 3 4 5 6 7 8 6 7 8 9 10 11 12 3 4 5
6 7 8 9
9 10 11 12 13 14 15 13 14 15 16 17 18 19 10 11 12
13 14 15 16
16 17 18 19 20 21 22 20 21 22 23 24 25 26 17 18 19
20 21 22 23
23 24 25 26 27 28 29 27 28 29 30 31 24 25 26
27 28 29 30
30 31
AI
,
DL
October November Dec
ember ,
DS
Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We
r ,
Th Fr Sa Su i ne ML
y T ra C,
1 2 3 4 5 6 7 1 2 3 4
t l ed o m
1 2 r
b o ca dd
l .c
k ra hni mbe
8 9 10 11 12 13 14 5 6 7 8 9 10 11 3 4 5
a i
6 7 8 9 h a ec E
@ gm
C T B,
& A 0 n al
15 16 17 18 19 20 21 12 13 14 15 16 17 18 10 11 12
p
13 14 15 16 ee e TL 836 our
d t A
ha ora , M 01 .j
22 23 24 25 26 27 28 19 20 21 22 23 24 25 17 18 19
b 0 a
Su orp hon 91 bh
20 21 22 23
C yt : 8 su
29 30 31 26 27 28 29 30 24 25 26
P ob l:
27 28 29 30 M ai
31
M
Python program to check leap year
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 10/27
12/17/2018 PyHiTea slides
In [22]: import calendar
# using isleap() to check if year is leap or not
if (calendar.isleap(2018)):
print ("The year is leap")
else :
print ("The year is not leap")
#using leapdays() to print leap days between years
print ("The leap days between 1950 and 2000 are : ",end="")
A I
print (calendar.leapdays(1950, 2000)) ,
DL
,
The year is not leap DS
er L,
The leap days between 1950 and 2000 are : 12
n M
i
y T ra C,
t l ed o m
r c
os Package rabonicabedd ail.
h ak ech Em gm
C T , l @
Get OS Name p & AB 0 na
d ee te ATL 36 ur
h a ra M 18 jo
In [49]: b po n, 00 a.
import os
u
S or ho 91 bh
print(os.name)
C yt : 8 su
P ob l:
nt M ai
M
Get Current Working Directory(CWD)
In [7]: import os
print(os.getcwd())
C:\Users\Subhadeep Chakrabort\Desktop\Basic Python
Rename a file in a Directory
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 11/27
12/17/2018 PyHiTea slides
In [31]: import os
os.renames("D:\\As a Trainer\\GIET\\new.txt","D:\\As a
Trainer\\GIET\\sbc.txt")
Get list of files in Directory
In [9]: import os
list1=os.listdir("D:\\As a AI
L,
Trainer\\OGMA\\Workshop\\Python\\GNIT\\Machine Learning")
D
print(list1) ,
for i in list1: DS
print(i)
n er ML,
r ai C,
['2.mp4', '3.mp4', '5 AI Bots That Will Make Your Life Easier
ty l T ed m
r o
b o ca dd
l .c
2017 ð.mp4', '5.mp4', 'After AI Slide.mp4', 'After Robotics
ra hni mbe i
Slide.mp4', 'Artificial Intelligence.mp4', 'Intro.mp4', 'Thu
k a
a ec E gm
mbs.db', 'Top 10 Hottest Artificial Intelligence Technologies
h @
C T B,
2017.mp4', 'videoplayback_2.mp4']
p & A 0 n al
2.mp4 d ee te ATL 36 ur
a a M 18 jo
3.mp4 bh or ,
u p n 1 00 ha.
5 AI Bots That Will Make Your Life Easier 2017 ð.mp4
S or ho 9 b
8 su
5.mp4 C yt :
P ob l:
After AI Slide.mp4
M ai
M
After Robotics Slide.mp4
Artificial Intelligence.mp4
Intro.mp4
Thumbs.db
Top 10 Hottest Artificial Intelligence Technologies 2017.mp4
videoplayback_2.mp4
math Package
Write a Python program to convert a float to ratio.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 12/27
12/17/2018 PyHiTea slides
In [37]: from fractions import Fraction
value = 4.2
print(Fraction(value).limit_denominator())
21/5
Square Root of a Number
In [54]: AI
import math ,
math.sqrt(5.6) DL
,
DS
Out[54]: 2.3664319132398464
n er ML,
r ai C,
Python get a Ceil and Floor Value
ty l T ed o m
r
b o ca dd
l .c
In [55]: import math k ra hni mbe a i
h a ec E
@ gm
x=float(input("Enter a Fraction: "))
C T B,
p & A 0 n al
print(math.ceil(x))
d ee te ATL 36 ur
a ra M 18 jo
print(math.floor(x))
h
u b po n, 00 a.
S or ho 91 bh
Enter a Fraction: 5.88
C yt : 8 su
6 P ob l:
5 M ai
M
Python program to gt Absolute Value
In [56]: import math
x=float(input("Enter a Fraction: "))
print("Absolute value of the number:",math.fabs(x))
Enter a Fraction: ‐3.5
Absolute value of the number: 3.5
Python program to get remainder when x is divided by y
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 13/27
12/17/2018 PyHiTea slides
In [48]: import math
x=eval(input("Enter a Number: "))
y=eval(input("Enter a Number: "))
print(math.fmod(x, y))
Enter a Number: 2
Enter a Number: 3
2.0
AI
,
Python program to get Sin(x) DL
,
DS
In [10]: import math
n er ML,
x=eval(input("Enter value:"))
r ai C,
print("Sine value: ",math.sin(x))
r ty l T ed o m
print("Cosine Value: ",math.cos(x))
b o ca dd
l .c
ra hni mbe
print("Tangent value: ",math.tan(x))
k a i
h a ec E
@ gm
Enter value:45 C T B,
al
p & A 0 n
ee te ATL 36 ur
Sine value: 0.8509035245341184
d
a ra M 18 jo
Cosine Value: 0.5253219888177297
h
u b po n, 00 a.
Tangent value: 1.6197751905438615
S or ho 91 bh
C yt : 8 su
P ob l:
Python program to get exponential value
M ai
M
In [57]: import math
print(math.e)
print(math.pi)
2.718281828459045
3.141592653589793
Python program to get Factorial of a Number
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 14/27
12/17/2018 PyHiTea slides
In [12]: import math
x=eval(input("Enter value:"))
print(math.factorial(x))
Enter value:3
6
Python program to get first value with the sign of second value
AI
,
In [61]: import math DL
x=eval(input("Enter a Number: "))
,
DS
y=eval(input("Enter a Number: ")) r
n e ML,
math.copysign(x, y)
r ai C,
Enter a Number: ‐2 r ty l T ed o m
b o ca dd
l .c
Enter a Number: 3
k ra hni mbe a i
h a ec E
@ gm
Out[61]: 2.0 C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
random Package
u
S or ho 91 bh
C yt : 8 su
P ob l:
Generate a Randor INT Number
M ai
M
In [14]: import random
print(random.randint(16, 150))
27
Generate a Random FLOAT Number
In [72]: import random
print(random.random() * 100)
54.26646449290525
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 15/27
12/17/2018 PyHiTea slides
Random Choice a List
In [20]: import random
myList = [2, 109, False, 10, "Lorem", 482, "Ipsum"]
random.choice(myList)
Out[20]: 2
Shuffle a List Items AI
,
DL
In [71]: from random import shuffle ,
DS
x = [[i] for i in range(10)]
n er ML,
shuffle(x)
print(x) r ai C,
r ty l T ed o m
b o ca dd
[[7], [6], [1], [8], [3], [5], [9], [2], [4], [0]] l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
Print a range of numbers
p & A 0 n al
d ee te ATL 36 ur
In [89]: h a ra M 18 jo
b po n, 00 a.
import random
u
S or ho 91 bh
for i in range(3):
C yt : 8 su
print(random.randrange(0, 101, 5))
P ob l:
M ai
30 M
70
65
randrange example
In [91]: import random
print(random.randrange(999))
573
Random choice from iterables
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 16/27
12/17/2018 PyHiTea slides
In [93]: import random
# Generate a random string from the list of strings
print(random.choice( ['Python', 'C++', 'Java'] ))
# Generate a random number from the list [‐1, 1, 3.5, 7, 15]
print(random.choice([‐1, 1, 3.5, 9, 15])) AI
,
DL
# Generate a random number from a uniformly distributed tuple
,
DS
r ,
ne ML
print(random.choice((1.1, ‐5, 6, 4, 7)))
r ai C,
ty l T ed
# Generate a random char from a string
r o m
b o ca dd
l .c
ra hni mbe a i
print(random.choice('Learn Python Programming'))
k
h a ec E
@ gm
C T B,
Java p & A 0 n al
15 d ee te ATL 36 ur
h a ra M 18 jo
4
u b po n, 00 a.
P S or ho 91 bh
C yt : 8 su
P ob l:
M ai
Take samples from iterable
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 17/27
12/17/2018 PyHiTea slides
In [94]: from random import sample
# Select any three chars from a string
print(sample('Python',3))
# Randomly select a tuple of three elements from a base tuple
print(sample((21, 12, ‐31, 24, 65, 16.3), 3)) AI
,
DL
# Randomly select a list of three elements from a base list
,
DS
r ,
ne ML
print(sample([11, 12, 13, 14, ‐11, ‐12, ‐13, ‐14], 3))
r ai C,
ty l T ed m
# Randomly select a subset of size three from a given set of num
r o
bers b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
print(sample({110, 120, 130, 140}, 3))
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
# Randomly select a subset of size three from a given set of str
h 0 .
ings ub po n, 10 ha
S or ho 9 b
C yt : 8 su
P ob l:
print(sample({'Python', 'C++', 'Java', 'Go'}, 3))
M ai
M
['o', 't', 'P']
[65, ‐31, 16.3]
[14, ‐11, ‐14]
[140, 110, 130]
['Go', 'Java', 'C++']
array Package
Creating an Array
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 18/27
12/17/2018 PyHiTea slides
In [21]: import array as arr
a = arr.array('d', [1, 3.5, "Hello"])
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
TypeError Traceback (most rec
ent call last)
<ipython‐input‐21‐d8acd55d6aba> in <module>()
1 import array as arr AI
‐‐‐‐> 2 a = arr.array('d', [1, 3.5, "Hello"]) ,
DL
,
TypeError: must be real number, not str DS
n er ML,
In [22]: import array as arr r ai C,
ty l T ed
a = arr.array('d', [1.1, 3.5, 4.5])
r o m
print(a) b o ca dd
l .c
k ra hni mbe a i
h a ec E
array('d', [1.1, 3.5, 4.5]) @ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Fetch elements from array
h
u b po n, 00 a.
S or ho 91 bh
In [99]: C yt : 8 su
import array as arr
P ob l:
a = arr.array('i', [2, 4, 6, 8])
M ai
M
print("First element:", a[0])
print("Second element:", a[1])
print("Second last element:", a[‐1])
First element: 2
Second element: 4
Second last element: 8
Array Slicing
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 19/27
12/17/2018 PyHiTea slides
In [101]: import array as arr
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = arr.array('i', numbers_list)
print(numbers_array[2:5])
print(numbers_array[:‐5])
print(numbers_array[5:])
print(numbers_array[:]) AI
,
array('i', [62, 5, 42])
DL
,
array('i', [2, 5, 62]) DS
array('i', [52, 48, 5])
n er ML,
array('i', [2, 5, 62, 5, 42, 52, 48, 5])
r ai C,
r ty l T ed o m
b o ca dd .c
Add or Change items in Array l
k ra hni mbe a i
h a ec E
@ gm
C T B,
In [106]: import array as arr
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
# changing first element
P ob l:
numbers[0] = 0
M ai
print(numbers) # Output: array('i', [0, 2, 3, 5, 7, 10])
M
# changing 3rd to 5th element
numbers[2:5] = arr.array('i', [4, 6, 8])
print(numbers) # Output: array('i', [0, 2, 4, 6, 8, 10])
array('i', [0, 2, 3, 5, 7, 10])
array('i', [0, 2, 4, 6, 8, 10])
Remove items from Araay
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 20/27
12/17/2018 PyHiTea slides
In [108]: import array as arr
number = arr.array('i', [1, 2, 3, 3, 4])
del number[2] # removing third element
print(number) # Output: array('i', [1, 2, 3, 4])
del number # deleting entire array
print(number) # Error: array is not defined AI
,
array('i', [1, 2, 3, 4])
DL
,
DS
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
r ,
‐‐‐‐‐‐‐‐‐‐‐‐‐‐ i ne ML
y T ra C,
NameError Traceback (most rec
t l ed o m
r
ent call last)
b o ca dd
l .c
k ra hni mbe
<ipython‐input‐108‐a2991b5bede7> in <module>()
a i
7 h a ec E
@ gm
C T B,
& A 0 n al
8 del number # deleting entire array
p
ee te ATL 36 ur
‐‐‐‐> 9 print(number) # Error: array is not defined
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
NameError: name 'number' is not defined
C yt : 8 su
P ob l:
Array Extend M ai
M
In [105]: import array as arr
numbers = arr.array('i', [1, 2, 3])
numbers.append(4)
print(numbers) # Output: array('i', [1, 2, 3, 4])
# extend() appends iterable to the end of the array
numbers.extend([5, 6, 7])
print(numbers)
array('i', [1, 2, 3, 4])
array('i', [1, 2, 3, 4, 5, 6, 7])
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 21/27
12/17/2018 PyHiTea slides
Array Concat
In [107]: import array as arr
odd = arr.array('i', [1, 3, 5])
even = arr.array('i', [2, 4, 6])
numbers = arr.array('i') # creating empty array of integer
I A
numbers = odd + even
DL,
print(numbers)
,
DS
e r L,
array('i', [1, 3, 5, 2, 4, 6]) i n M
y T ra C,
t l ed o m
r
Delete element using pop b o ca dd
l .c
k ra hni mbe a i
In [109]: h a ec E
@ gm
import array as arr
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
numbers = arr.array('i', [10, 11, 12, 12, 13])
h
u b po n, 00 a.
S or ho 91 bh
numbers.remove(12)
C yt : 8 su
print(numbers) # Output: array('i', [10, 11, 12, 13])
P ob l:
M ai
M
print(numbers.pop(2)) # Output: 12
print(numbers) # Output: array('i', [10, 11, 13])
array('i', [10, 11, 12, 13])
12
array('i', [10, 11, 13])
Disadvantages of Array and Better Replacement
Lists are much more flexible than arrays. They can store
elements of different data types including string. Also, lists are
faster than arrays. And, if you need to do mathematical
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 22/27
12/17/2018 PyHiTea slides
computation on arrays and matrices, you are much better off
using something like NumPy library.
Unless you don't really need arrays (array module maybe
needed to interface with C code), don't use them.
itertool Package
AI
,
zip function DL
,
DS
Combining elements of multiple List n er ML,
r ai C,
In [4]: r ty l T ed o m
list(zip([1, 2, 3], ['a', 'b', 'c'],[6,7,8]))
b o ca dd
l .c
k ra hni mbe a i
Out[4]: [(1, 'a', 6), (2, 'b', 7), (3, 'c', 8)]
h a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Counting length of each element in List
d
h a ra M 18 jo
u b po n, 00 a.
In [6]: S or ho 91 bh
list(map(len, ['abc', 'de','fghi']))
C yt : 8 su
P ob l:
Out[6]: [3, 2, 4] M i
Ma
Calculating Sum of respective elements of List
In [7]: list(map(sum, zip([1, 2, 3], [4, 5, 6])))
Out[7]: [5, 7, 9]
Printing Iterator
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 23/27
12/17/2018 PyHiTea slides
In [14]: from itertools import *
for i in chain([1, 2, 3], ['a', 'b', 'c']):
print(i)
1
2
3
a
b AI
c ,
DL
,
Merging Iterator w.r.t element DS
n er ML,
In [16]: r ai C,
from itertools import * y
r t l T ed o m
b o ca dd
l .c
ra hni mbe
for i in zip([1, 2, 3], ['a', 'b', 'c']):
k a i
print(i) h a ec E
@ gm
C T B,
p & A 0 n al
(1, 'a')
d ee te ATL 36 ur
(2, 'b') ha ra M 018 .jo
b o , 0 a
Su orp hon 91 bh
(3, 'c')
C yt : 8 su
P ob l:
Count and iterate the Iterators
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 24/27
12/17/2018 PyHiTea slides
In [21]: from itertools import *
print('Stop at 5:')
for i in islice(count(), 5):
print(i)
print('Start at 5, Stop at 10:')
for i in islice(count(), 5, 10):
print(i) AI
,
DL
print('By tens to 100:') ,
for i in islice(count(), 0, 100, 10): DS
print(i) n er ML,
r ai C,
Stop at 5:
r ty l T ed o m
0 b o ca dd
l .c
1 k ra hni mbe a i
2 h a ec E
@ gm
C T B,
3 p & A 0 n al
4 d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Start at 5, Stop at 10:
u
5 S or ho 91 bh
C yt : 8 su
6 P ob l:
7 M ai
8
M
9
By tens to 100:
0
10
20
30
40
50
60
70
80
90
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 25/27
12/17/2018 PyHiTea slides
Print numbers using count() function
In [23]: from itertools import count
for i in count(7):
if i>14:
break
print(i)
7
AI
8 ,
9 DL
,
10 DS
11
n er ML,
12
r ai C,
13 ty l T ed m
r o
14 b o ca dd
l .c
k ra hni mbe a i
h a ec E gm
Print any sequence using cycle()
C T B, @
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 26/27
12/17/2018 PyHiTea slides
In [25]: from itertools import *
index = 0
for item in cycle(['Python', 'Java', 'Ruby']):
index += 1
if index == 12:
break
print(index, item)
AI
1 Python ,
2 Java
DL
,
3 Ruby DS
4 Python
n er ML,
5 Java
r ai C,
6 Ruby
r ty l T ed o m
7 Python b o ca dd
l .c
8 Java k ra hni mbe a i
9 Ruby h a ec E
@ gm
C T B,
10 Python p & A 0 n al
11 Java d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
In [23]: S or ho 91 bh
import numpy as np
C yt : 8 su
list1=[1,2,3,2.3,4]
P ob l:
M ai
arr=np.array(list1)
M
print(arr)
['1' '2' '3' '2.3' 'abc']
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyHiTea.slides.html 27/27
12/17/2018 PyFile1(txt) slides
File IO Tutorial
In this tutorial we will see how txt file can be accessed using File
IO in Python.
The File should be stored in HDDrive with as extension: .txt
AI
L ,
Python File Mode: D
,
DS
er ML,
r=> Opens a file for reading only. The file pointer is placed at the
n
ai C,
beginning of the file. This is the default mode.
r
r ty l T ed o m
b o ca dd
l .c
rb=> Opens a file for reading only in binary format. The file
ra hni mbe a i
k
h a ec E
@ gm
pointer is placed at the beginning of the file. This is the default
C T B,
mode. p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
r+=> Opens a file for both reading and writing. The file pointer
b po n, 00 a.
u
S or ho 91 bh
placed at the beginning of the file.
C yt : 8 su
P ob l:
rb+=>Opens a file for both reading and writing in binary format.
M ai
M
The file pointer placed at the beginning of the file.
w=> Opens a file for writing only. Overwrites the file if the file
exists.If the file does not exist, creates a new file for writing.
wb=> Opens a file for writing only in binary format. Overwrites
the file if the file exists. If the file does not exist, creates a new
file for writing.
w+=> Opens a file for both writing and reading. Overwrites the
existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 1/11
12/17/2018 PyFile1(txt) slides
wb+=>Opens a file for both writing and reading in binary format.
Overwrites the existing file if the file exists. If the file does not
exist, creates a new file for reading and writing.
a=> Opens a file for appending. The file pointer is at the end of
the file if the file exists. That is, the file is in the append mode. If
the file does not exist, it creates a new file for writing.
ab=> Opens a file for appending in binary format. The file AI
,
DL
pointer is at the end of the file if the file exists. That is, the file is
,
in the append mode. If the file does not exist, it creates a new
DS
file for writing. er ML,
n
r ai C,
a+=> Opens a file for both appending and reading. The file
ty l T ed o m
r
b o ca dd
l .c
pointer is at the end of the file if the file exists. The file opens in
ra hni mbe i
the append mode. If the file does not exist, it creates a new file
k a
h a ec E
@ gm
for reading and writing.
C T B,
al
p & A 0 n
d ee te ATL 36 ur
a ra M 18 jo
ab+=>Opens a file for both appending and reading in binary
h
b po n, 00 a.
format. The file pointer is at the end of the file if the file exists.
u
S or ho 91 bh
C yt : 8 su
The file opens in the append mode. If the file does not exist, it
P ob l:
creates a new file for reading and writing.
M ai
M
To creat a file
In [1]: fh1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File
IO)\\hello.txt","w")
fh1.close()
To open a text file
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 2/11
12/17/2018 PyFile1(txt) slides
In [2]: fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\hello.txt",
"r")
fh.close()
To read a text file
In [3]: fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File AI
IO)\\hello.txt","r") ,
DL
print (fh.read()) ,
fh.close() DS
n er ML,
r ai C,
r ty l T ed o m
.c
To read a list of lines b o ca dd
l
k ra hni mbe a i
h a ec E
@ gm
C T B,
In [4]: & A 0 n al
fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\hello.txt",
p
"r") d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
print(fh.readlines())
u
S or ho 91 bh
[] C yt : 8 su
P ob l:
M ai
M
To write to a file
In [5]: fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File
IO)\\hello.txt","w")
fh.write("Hello World")
fh.close()
To write to a file
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 3/11
12/17/2018 PyFile1(txt) slides
In [7]: fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\hello.txt",
"w")
lines_of_text = ["a line of text", "another line of text", "a th
ird line"]
fh.writelines(lines_of_text)
fh.close()
AI
To append to file DL
,
In [8]: D S,
fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\hello.txt",
"a") n er ML,
i
fh.write("Hello World again") ra C,
fh.close() r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
To close a file p
C T B,
& A
ee te ATL 36 ur
0 n al
d
a ra M 18 jo
In [9]: h
b po n, 00 a.
fh = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\hello.txt",
u
S or ho 91 bh
"r") C yt : 8 su
print(fh.read())
P ob l:
fh.close() M ai
M
a line of textanother line of texta third lineHello World aga
in
Editing a File
Example1
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 4/11
12/17/2018 PyFile1(txt) slides
In [ ]:
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 5/11
12/17/2018 PyFile1(txt) slides
#Creating a .txt file
file1=open("D:\\As a Trainer\\GIET\\Mod‐11(File
IO)\\myfile.txt","w")
#Creating a string
str1 = ["We are learning Python... \n","We are learning File I/O
\n"]
str2 = ["Its good to see you\n"]
str3 = input('Enter a string:')
#Writing string into file
AI
,
file1.write("Hello all.. \n") DL
file1.writelines(str1) ,
DS
file1.writelines(str2)
n er ML,
file1.writelines(str3)
r ai C,
file1.close()
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe
#Open a file for reading content
a i
h a ec E
@ gm
file1=open("D:\\As a Trainer\\GIET\\Mod‐11(File
C T B,
IO)\\myfile.txt","r+")
p & A 0 n al
ee te ATL 36 ur
print("Content of file:\n",file1.read())
d
a ra M 18 jo
print('‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐')
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
#Again opening that file for modification(appending)
P ob l:
file1=open("D:\\As a Trainer\\GIET\\Mod‐11(File
M ai
IO)\\myfile.txt","a")
M
#Creating a string by user input
str4=input('\nEnter String: ')
file1.writelines('\n'+str4)
file1.close()
print('‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐')
#Input of paragraph
para="""\nNow we are learning python File IO\n"""
#Open the file again
file1=open("D:\\As a Trainer\\GIET\\Mod‐11(File
IO)\\myfile.txt","a")
file1.writelines(para)
file1.close()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 6/11
12/17/2018 PyFile1(txt) slides
file1=open("D:\\As a Trainer\\GIET\\Mod‐11(File
IO)\\myfile.txt",'r+')
print("Content of file after adding paragraph:\n",file1.read())
file1.close()
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
t","r+")
#Output of readlines() function
print ("File Content readline(): ",file1.readline(12))
AI
,
file1.seek(0) DL
,
DS
#Read contect with user input
n er ML,
print('\nUsing index input to fetch file content::')
r ai C,
r ty l T ed o m
end_index=int(input('Enter end index of file to print:'))
b o ca dd
l .c
k ra hni mbe
print ("File Content readline(): ",file1.readline(end_index))
a i
file1.seek(0) h a ec E
@ gm
C T B,
p & A 0 n al
file1.close()
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Example2 P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 7/11
12/17/2018 PyFile1(txt) slides
In [ ]: file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
t","w")
L = ["Weare learning Python... \n","We are learning File I/O
\n"]
file1.close()
# Append‐adds at last
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
t","a")#append mode AI
file1.write("Today \n") ,
DL
file1.close() ,
DS
r ,
ne ML
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
t","a+") r ai C,
ty l T ed
print ('Output of Readlines after appending')
r o m
print (file1.readlines()) b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
file1.close() C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
# Write‐Overwrites
h
b po n, 00 a.
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
u
S or ho 91 bh
C yt : 8 su
t","w")#write mode
P ob l:
file1.write("Tomorrow \n")
M
file1.close() ai
M
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
t","r")
print ('Output of Readlines after writing')
print (file1.readlines())
file1.close()
Exercise1
1. WAP to add two number and store the result in a file.
2. WAP to insert program code into file.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 8/11
12/17/2018 PyFile1(txt) slides
3. WAP to write a some data into file and then read the
data and into console window
4. WAP to copy data from one file to another file.
Example3
In [ ]:
AI
#Method for opening a file from a particular location
L,
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
D
t","w")
L1 = ["We are learning Python... \n","We are learning File I/O
D S,
\n"]
n er ML,
L2=input('Enter String: ')
r ai C,
ty l T ed
# \n is placed to indicate EOL (End of Line)
r o m
o ca dd
#Method to write string in file write()
b l .c
file1.write("Hello \n")
k ra hni mbe a i
h a ec E gm
#Method to write string in file writelines()
@
C T B,
p
file1.writelines(L1) & A 0 n al
ee te ATL 36 ur
file1.writelines(L2)
d
h a ra M 18 jo
b po n, 00 a.
#to close a file specifically to change access mode
u
S or ho 91 bh
file1.close()
C yt : 8 su
P ob l:
M ai
M
Example4
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 9/11
12/17/2018 PyFile1(txt) slides
In [ ]: file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
t","r+")
print('‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐Output of Read function is‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐')
print (file1.read())
# seek(n) takes the file handle to the nth bite from the beginni
ng.
file1.seek(15)
print ('‐‐‐‐‐‐‐‐‐‐‐‐‐‐Output of Readline function is‐‐‐‐‐‐‐‐‐‐‐‐
A I
‐‐‐‐‐‐‐') ,
DL
print(file1.readline()) ,
#file1.seek(15) DS
file1.close() n er ML,
r ai C,
r ty l T ed o m
o ca dd .c
Example5
b l
k ra hni mbe a i
h a ec E
@ gm
C T B,
In [ ]: p & A 0 n al
file1 = open("D:\\As a Trainer\\GIET\\Mod‐11(File IO)\\myfile.tx
d ee te ATL 36 ur
t","r+") a
h r a M 018 jo
b po n, 0 a.
position = file1.tell()
u
S or ho 91 bh
print ("Current file position : ", position)
C yt : 8 su
str = file1.read(10);
P ob l:
M ai
print ("Read String is : ", str)
M
position = file1.tell()
print ("Current file position : ", position)
end_index=int(input('Enter end index of file to print:'))
print ("File Content readline(): ",file1.readline(end_index))
file1.seek(0)
file1.close()
Exercise2
1. WAP to check how many whitespace are there in a file.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 10/11
12/17/2018 PyFile1(txt) slides
2. WAP to check how many characters are there in a file.
3. WAP to replace all 'a' character in file by 'x'.
4. WAP to design user option to CREATE, READ, WRITE,
APPEND file.
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile1(txt).slides.html 11/11
12/17/2018 PyFile2(CSV&eExcel) slides
FILE IO
Basic Features of CSV File
1. CSV Stands for COMMA SEPERATED VALUE.
2. CSV file is a delimited text file that uses a comma to
separate values. AI
,
3. A CSV file stores tabular data (numbers and text) in DL
plain text. ,
DS
4. Each line of the file is a data record. er ML,
n
ai C,
5. Each record consists of one or more fields, separated
r
by commas. r ty l T ed o m
o ca dd
6. The use of the comma as a field separator is the
b l .c
k ra hni mbe a i
source of the name for this file format.
h a ec E gm
C T B, @
p & A 0 n al
ee te ATL 36 ur
Package Required:
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
1. csv
C yt : 8 su
2. pandas P ob l:
M ai
M
Part1: Using csv Package
Read a File
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 1/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [6]: import csv
with open("D:\\As a Trainer\\GIET\Mod‐11(File IO)\\csv\\fruits.c
sv", 'r') as f:
reader = csv.reader(f)
rowcount=0
for row in reader:
print(row)
rowcount+=1
print('‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐') AI
print("Total number of Rows: ",rowcount) ,
DL
,
f.close() DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 2/22
12/17/2018 PyFile2(CSV&eExcel) slides
['Sl', 'Name', 'Category', 'Supplier', 'Brand', 'Price Grou
p', 'Color Score', 'Purification', 'Customer Demand']
['1', 'Apple', 'A', 'A.Co.', 'Nutts', 'P1', '0.45', '0.5',
'0.9']
['2', 'Apple', 'A', 'Fruits_Lover', 'Fruits#1', 'P2', '0.57',
'0.76', '0.5']
['3', 'Lemon', 'B', 'Fruits_Lover', 'Fruits#1', 'P2', '0.8',
'0.44', '0.6']
['4', 'Watermelon', 'B', 'A.Co.', 'Fruits#1', 'P1', '0.45',
I
'0.68', '0.5']
A
['5', 'Apple', 'B', 'A.Co.', 'Costa Rica', 'P2', '0.8', '0.9
D L,
4', '0.6'] ,
DS
['6', 'Apple', 'A', 'Fresh_Fruits', 'Nutts', 'P2', '0.65',
r ,
'0.76', '0.6'] i ne ML
y T ra C,
['7', 'Apple', 'A', 'A.Co.', 'Del Monte', 'P1', '0.78', '0.9
t l ed o m
4', '0.9'] r
b o ca dd
l .c
k ra hni mbe
['8', 'Watermelon', 'A', 'A.Co.', 'Nutts', 'P1', '0.57', '0.
a i
5', '0.6'] h a ec E
@ gm
C T B,
& A 0 n al
['9', 'Lemon', 'A', 'Fruits_Lover', 'Nutts', 'P1', '0.78',
p
'0.5', '0.9']
d ee te ATL 36 ur
a ra M 18 jo
['10', 'Watermelon', 'D', 'Fruits_Lover', 'Nutts', 'P3', '0.4
h
u b po n, 00 a.
S or ho 91 bh
5', '0.5', '0.9']
C yt : 8 su
['11', 'Lemon', 'A', 'Fruits_Lover', 'Del Monte', 'P3', '0.5
P ob l:
7', '0.76', '0.7']
M ai
['12', 'Lemon', 'A', 'Quick_Fruit', 'Costa Rica', 'P2', '0.
M
8', '0.5', '0.5']
['13', 'Grapes', 'C', 'Fresh_Fruits', 'Costa Rica', 'P2', '0.
8', '0.44', '0.7']
['14', 'Apple', 'C', 'Fresh_Fruits', 'Del Monte', 'P3', '0.
8', '0.88', '0.6']
['15', 'Apple', 'C', 'A.Co.', 'Fruits#1', 'P3', '0.65', '0.6
8', '0.5']
['16', 'Apple', 'C', 'A.Co.', 'Fruits#1', 'P1', '0.78', '0.7
6', '0.9']
['17', 'Apple', 'B', 'A.Co.', 'Fruits#1', 'P4', '0.57', '0.6
8', '0.9']
['18', 'Grapes', 'B', 'Quick_Fruit', 'Del Monte', 'P3', '0.4
5', '0.44', '0.7']
['19', 'Watermelon', 'D', 'Quick_Fruit', 'Costa Rica', 'P2',
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 3/22
12/17/2018 PyFile2(CSV&eExcel) slides
'0.59', '0.68', '0.6']
['20', 'Apple', 'B', 'Quick_Fruit', 'Del Monte', 'P4', '0.5
9', '0.44', '0.7']
['21', 'Watermelon', 'B', 'Fruits_Lover', 'Nutts', 'P1', '0.4
5', '0.76', '0.5']
['22', 'Watermelon', 'C', 'Fruits_Lover', 'Nutts', 'P1', '0.7
8', '0.68', '0.6']
['23', 'Lemon', 'A', 'Fruits_Lover', 'Nutts', 'P1', '0.59',
'0.5', '0.5']
['24', 'Lemon', 'A', 'Fruits_Lover', 'Nutts', 'P4', '0.57',
AI
,
'0.94', '0.8'] DL
S,
['25', 'Lemon', 'A', 'Fruits_Lover', 'Fruits#1', 'P4', '0.9',
D
'0.88', '0.8'] r ,
ne ML
['26', 'Grapes', 'A', 'Fruits_Lover', 'Costa Rica', 'P2', '0.
i
78', '0.94', '0.8'] y T ra C,
t l ed o m
r
['27', 'Watermelon', 'A', 'Quick_Fruit', 'Costa Rica', 'P3',
b o ca dd
l .c
'0.65', '0.94', '0.8']
k ra hni mbe a i
h a ec E
@ gm
['28', 'Grapes', 'D', 'Quick_Fruit', 'Nutts', 'P2', '0.45',
C T B,
'0.76', '0.5']
p & A 0 n al
ee te ATL 36 ur
['29', 'Apple', 'D', 'Quick_Fruit', 'Fruits#1', 'P3', '0.9',
d
a ra M 18 jo
'0.71', '0.8']
h
u b po n, 00 a.
S or ho 91 bh
['30', 'Apple', 'A', 'Fresh_Fruits', 'Fruits#1', 'P2', '0.7
C yt : 8 su
8', '0.94', '0.8']
P ob l:
['31', 'Apple', 'A', 'Fresh_Fruits', 'Nutts', 'P3', '0.9',
M ai
'0.94', '0.8'] M
['32', 'Apple', 'A', 'Fresh_Fruits', 'Costa Rica', 'P1', '0.6
5', '0.76', '0.8']
['33', 'Lemon', 'A', 'Fresh_Fruits', 'Del Monte', 'P4', '0.
9', '0.68', '0.5']
['34', 'Watermelon', 'C', 'Fresh_Fruits', 'Nutts', 'P1', '0.5
9', '0.88', '0.8']
['35', 'Apple', 'C', 'Quick_Fruit', 'Nutts', 'P4', '0.9', '0.
68', '0.6']
['36', 'Apple', 'D', 'Quick_Fruit', 'Del Monte', 'P3', '0.6
5', '0.76', '0.6']
['37', 'Watermelon', 'D', 'Quick_Fruit', 'Costa Rica', 'P2',
'0.45', '0.94', '0.5']
['38', 'Apple', 'D', 'Quick_Fruit', 'Del Monte', 'P2', '0.9',
'0.44', '0.8']
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 4/22
12/17/2018 PyFile2(CSV&eExcel) slides
['39', 'Apple', 'B', 'Fresh_Fruits', 'Nutts', 'P4', '0.78',
'0.68', '0.8']
['40', 'Grapes', 'B', 'Quick_Fruit', 'Nutts', 'P3', '0.9',
'0.44', '0.9']
['41', 'Grapes', 'B', 'Quick_Fruit', 'Nutts', 'P1', '0.65',
'0.71', '0.6']
['42', 'Grapes', 'B', 'A.Co.', 'Del Monte', 'P1', '0.78', '0.
94', '0.6']
['43', 'Grapes', 'B', 'A.Co.', 'Costa Rica', 'P1', '0.59',
I
'0.44', '0.6']
A
['44', 'Lemon', 'B', 'A.Co.', 'Costa Rica', 'P3', '0.8', '0.
D L,
5', '0.9'] ,
DS
['45', 'Lemon', 'B', 'Quick_Fruit', 'Costa Rica', 'P4', '0.5
r ,
9', '0.94', '0.6'] i ne ML
y T ra C,
['46', 'Lemon', 'D', 'Fruits_Lover', 'Del Monte', 'P4', '0.6
t l ed o m
5', '0.68', '0.5'] r
b o ca dd
l .c
k ra hni mbe
['47', 'Watermelon', 'D', 'Fruits_Lover', 'Del Monte', 'P1',
a i
'0.9', '0.71', '0.7']
h a ec E
@ gm
C T B,
& A 0 n al
['48', 'Grapes', 'D', 'Quick_Fruit', 'Del Monte', 'P3', '0.5
p
ee te ATL 36 ur
9', '0.88', '0.9']
d
a ra M 18 jo
['49', 'Grapes', 'D', 'A.Co.', 'Fruits#1', 'P3', '0.8', '0.7
h
u b po n, 00 a.
S or ho 91 bh
6', '0.6']
C yt : 8 su
['50', 'Watermelon', 'A', 'A.Co.', 'Fruits#1', 'P2', '0.9',
P ob l:
'0.88', '0.5']
M ai
['51', 'Watermelon', 'A', 'A.Co.', 'Costa Rica', 'P2', '0.9',
M
'0.5', '0.5']
['52', 'Grapes', 'A', 'A.Co.', 'Costa Rica', 'P4', '0.7', '0.
71', '0.5']
['53', 'Grapes', 'D', 'Fresh_Fruits', 'Fruits#1', 'P4', '0.
8', '0.68', '0.9']
['54', 'Grapes', 'D', 'Fruits_Lover', 'Fruits#1', 'P4', '0.
7', '0.88', '0.7']
['55', 'Grapes', 'D', 'Fresh_Fruits', 'Del Monte', 'P1', '0.
9', '0.71', '0.7']
['56', 'Lemon', 'C', 'Quick_Fruit', 'Del Monte', 'P4', '0.5
9', '0.71', '0.7']
['57', 'Lemon', 'C', 'A.Co.', 'Del Monte', 'P4', '0.8', '0.7
1', '0.9']
['58', 'Watermelon', 'C', 'A.Co.', 'Nutts', 'P4', '0.9', '0.8
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 5/22
12/17/2018 PyFile2(CSV&eExcel) slides
8', '0.8']
['59', 'Watermelon', 'D', 'Quick_Fruit', 'Fruits#1', 'P2',
'0.7', '0.44', '0.7']
['60', 'Lemon', 'D', 'Quick_Fruit', 'Del Monte', 'P4', '0.7',
'0.88', '0.9']
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
Total number of Rows: 61
AI
Write a File ,
DL
,
In [8]: import csv DS
n er ML,
ai C,
csvData = [['Person', 'Age'], ['Peter', '22'], ['Jasmine',
r
'21'], ['Sam', '24']]
r ty l T ed o m
b o ca dd
l .c
ra hni mbe i
with open("D:\\As a Trainer\\GIET\Mod‐11(File IO)\\csv\\csv1.cs
k a
h
v", 'w') as csvFile:
a ec E
@ gm
C T B,
writer = csv.writer(csvFile)
p & A 0 n al
ee te ATL 36 ur
writer.writerows(csvData)
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
csvFile.close()
C yt : 8 su
P ob l:
M ai
M
Create CSV using dialact a File
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 6/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [15]: import csv
person = [['SN', 'Person', 'DOB'],
['1', 'John', '18/1/1997'],
['2', 'Marie','19/2/1998'],
['3', 'Simon','20/3/1999'],
['4', 'Erik', '21/4/2000'],
['5', 'Ana', '22/5/2001']]
AI
csv.register_dialect('myDialect', ,
DL
quoting=csv.QUOTE_ALL, ,
skipinitialspace=True) DS
n er ML,
ai C,
with open("D:\\As a Trainer\\GIET\Mod‐11(File IO)\\csv\\csvDiala
r
ct.csv", 'w+') as f: r ty l T ed o m
b o ca dd
writer = csv.writer(f, dialect='myDialect') l .c
for row in person: k ra hni mbe a i
h a ec E
@ gm
writer.writerow(row)
C T B,
p & A 0 n al
d ee te ATL 36 ur
f.close() a
h r a M 018 jo
u b po n, 0 a.
S or ho 91 bh
C yt : 8 su
Modify a File
P ob l:
M ai
M
In [16]: import csv
row = ['6', ' Danny', ' New York']
with open("D:\\As a Trainer\\GIET\Mod‐11(File IO)\\csv\\csvDiala
ct.csv", 'a') as csvFile:
writer = csv.writer(csvFile)
writer.writerow(row)
csvFile.close()
Part2: Using 'Pandas' Package
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 7/22
12/17/2018 PyFile2(CSV&eExcel) slides
File Handling and Data Reading
In [1]: import pandas as pd
file=pd.read_csv("D:\\As a Trainer\\GIET\Mod‐11(File IO)\\csv\\f
ruits.csv")
file.head()
AI
Out[1]: ,
DL Price Color
Sl Name Category Supplier S, Brand
D Group Score
r ,
0 1 Apple A A.Co.i ne ML Nutts P1 0.45
r a C,
1 2 Apple A r ty l Fruits_Lover
T d
e o m Fruits#1 P2 0.57
b o ca dd
l .c
2 3 Lemon Bra ni be Fruits_Lover a i Fruits#1 P2 0.80
k
a c E h m m
g
3 4 Watermelon Ch BTe B, A.Co.
l @ Fruits#1 P1 0.45
p & a
e e TLA 60 rn
e
d at MAB 83 ou A.Co. Costa
4 5 Apple a
h or , 1 j P2 0.80
b 00 ha. Rica
u p
S or ho 9 b n 1
C yt : 8 su
In [2]: P ob l:
r,c=file.shape
M ai
print("Number of Rows: ",r)
M
print("Number of Columns: ",c)
Number of Rows: 60
Number of Columns: 9
To Show full CSV file, use file.head(<no. of Rows>)
In [3]: #.head(r)
Fetch Columns:
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 8/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [4]: file.columns
Out[4]: Index(['Sl', 'Name', 'Category', 'Supplier', 'Brand', 'Price
Group',
'Color Score', 'Purification', 'Customer Demand'],
dtype='object')
Convert the Column details to LIST
AI
,
In [5]: file.columns.tolist()[0] DL
,
DS
Out[5]: 'Sl'
n er ML,
r ai C,
Fetch individual Column ty T d o m
r l e
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 9/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [10]: print(file['Sl'])
print(type(file['Sl']))
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 10/22
12/17/2018 PyFile2(CSV&eExcel) slides
0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9 10
AI
,
10 11 DL
11 12 ,
DS
12 13
n er ML,
13 14
r ai C,
14 15
r ty l T ed o m
15 16
b o ca dd
l .c
16 17
k ra hni mbe a i
17 18 h a ec E
@ gm
C T B,
18 19
p & A 0 n al
19 20
d ee te ATL 36 ur
20 21 ha ra M 018 .jo
b o , 0 a
Su orp hon 91 bh
21 22
22 23 C yt :
8 su
23 24
P ob l:
M ai
24 25 M
25 26
26 27
27 28
28 29
29 30
30 31
31 32
32 33
33 34
34 35
35 36
36 37
37 38
38 39
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 11/22
12/17/2018 PyFile2(CSV&eExcel) slides
39 40
40 41
41 42
42 43
43 44
44 45
45 46
46 47
47 48
48 49
AI
,
49 50 DL
50 51 ,
DS
51 52
n er ML,
52 53
r ai C,
53 54
r ty l T ed o m
54 55
b o ca dd
l .c
55 56
k ra hni mbe a i
56 57 h a ec E
@ gm
C T B,
57 58
p & A 0 n al
58 59
d ee te ATL 36 ur
59 60 ha ra M 018 .jo
b o , 0 a
Su orp hon 91 bh
Name: Sl, dtype: int64
C yt : 8 su
<class 'pandas.core.series.Series'>
P ob l:
M ai
M
Convert Pansdas Series to List
In [12]: sllist=file['Sl'].tolist()
print(sllist)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 1
8, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 3
3, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 4
8, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]
Fetch other columns
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 12/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [14]: namelist=file['Name'].tolist()
print(namelist)
['Apple', 'Apple', 'Lemon', 'Watermelon', 'Apple', 'Apple',
'Apple', 'Watermelon', 'Lemon', 'Watermelon', 'Lemon', 'Lemo
n', 'Grapes', 'Apple', 'Apple', 'Apple', 'Apple', 'Grapes',
'Watermelon', 'Apple', 'Watermelon', 'Watermelon', 'Lemon',
'Lemon', 'Lemon', 'Grapes', 'Watermelon', 'Grapes', 'Apple',
AI
'Apple', 'Apple', 'Apple', 'Lemon', 'Watermelon', 'Apple',
'Apple', 'Watermelon', 'Apple', 'Apple', 'Grapes', 'Grapes',
L,
'Grapes', 'Grapes', 'Lemon', 'Lemon', 'Lemon', 'Watermelon',
D
,
DS
'Grapes', 'Grapes', 'Watermelon', 'Watermelon', 'Grapes', 'G
er L,
rapes', 'Grapes', 'Grapes', 'Lemon', 'Lemon', 'Watermelon',
n M
'Watermelon', 'Lemon'] i
y T ra C,
t l ed o m
r
In [16]: b o ca dd
brandlist=file['Price Group'].tolist() l .c
ra hni mbe
colscorelist=file['Color Score'].tolist()
k a i
h a ec E
@ gm
purilist=file['Purification'].tolist()
C T B,
p & A 0 n al
custdemandlist=file['Customer Demand'].tolist()
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
Selecting a Row
C yt : 8 su
P ob l:
In [25]: file.iloc[0] M ai
M
Out[25]: Sl 1
Name Apple
Category A
Supplier A.Co.
Brand Nutts
Price Group P1
Color Score 0.45
Purification 0.5
Customer Demand 0.9
Name: 0, dtype: object
Selecting a Specific Data
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 13/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [26]: file.iloc[1][5]
Out[26]: 'P2'
Visualization of Data
In [17]: import matplotlib.pyplot as plt AI
,
DL
Continuous Plot ,
DS
In [19]: n er ML,
plt.figure(figsize=(20,10))
r ai C,
plt.plot(colscorelist)
r ty l T ed o m
b o ca dd
l .c
Out[19]: [<matplotlib.lines.Line2D at 0x16ca899dd8>]
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
Discrete Plot
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 14/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [35]: plt.figure(figsize=(20,10))
plt.title("PLOT OF COLOR SCORE OF FRUITS",fontsize=15)
plt.plot(colscorelist,"*m")
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.grid()
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
Multiplotub o , 00 a.
S orp hon 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 15/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [34]: plt.figure(figsize=(20,10))
plt.title("PLOT OF COLOR SCORE & CUSTOMER DEMAND OF FRUITS",font
size=15)
plt.plot(colscorelist,"r")
plt.plot(custdemandlist,"b")
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.grid()
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Multiplot and Adding Legand
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 16/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [29]: plt.figure(figsize=(20,10))
plt.title("PLOT OF COLOR SCORE & CUSTOMER DEMAND OF FRUITS",font
size=15)
plt.plot(colscorelist,"r",label="Color Score")
plt.plot(custdemandlist,"b",label="Customer Demand")
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.legend(loc="lower right")
plt.grid() AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
Ploting Barchart
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 17/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [36]: plt.figure(figsize=(20,10))
plt.title("PLOT OF COLOR SCORE OF FRUITS",fontsize=15)
colors='rgbcmyk'
plt.bar(range(len(colscorelist)),colscorelist,color=colors)
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.grid()
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 18/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [40]: plt.figure(figsize=(20,10))
plt.title("PLOT OF CUSTOMER DEMAND OF FRUITS",fontsize=15)
colors='cmyk'
plt.bar(range(len(custdemandlist)),custdemandlist,color=colors)
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.grid()
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Analysis of Data from CSV File
P ob l:
M ai
M
Checking the Purity List for the Determination how many fruits
are uch pure
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 19/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [46]: print("Maximum Purity Magnitude is: ",max(purilist))
print("Maximum Purity Magnitude is: ",min(purilist))
print("Average Purity Magnitude is: ",(max(purilist)+min(purilis
t))/2)
minpure=[]
maxpure=[]
for i in purilist:
if i<(max(purilist)+min(purilist))/2:
minpure.append(i) AI
else: ,
DL
maxpure.append(i)
D S,
print("Maximum Pure Fruit Quantity: ",len(maxpure))
er ML,
print("Minimum Pure Fruit Quantity: ",len(minpure))
n
r ai C,
ty l T ed
Maximum Purity Magnitude is: 0.94
r o m
o ca dd
Maximum Purity Magnitude is: 0.44
b l .c
ra hni mbe
Average Purity Magnitude is: 0.69
k a i
h a ec E
Maximum Pure Fruit Quantity: 34 @ gm
C T B,
Minimum Pure Fruit Quantity: 26
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Plotting Maximum and Minimum Pure Fruit BarChart
u
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 20/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [50]: plt.figure(figsize=(10,8))
plt.title("Minimum Pure Fruit",fontsize=15)
colors='rgb'
plt.bar(range(len(minpure)),minpure,color=colors)
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.grid()
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 21/22
12/17/2018 PyFile2(CSV&eExcel) slides
In [53]: plt.figure(figsize=(10,8))
plt.title("Maximum Pure Fruit",fontsize=15)
colors='cmyk'
plt.bar(range(len(maxpure)),maxpure,color=colors)
plt.ylabel("Magnitude‐>")
plt.xlabel("Quantity‐>")
plt.grid()
AI
,
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyFile2(CSV&eExcel).slides.html 22/22
12/17/2018 PyOPPBegineer slides
Python OOPS
Creating Class and Object
In [18]: class abc:
age = 25
name = "XXYY" AI
,
def display(self): DL
print("Welcome...") ,
DS
n ML
obj=abc() # Object of Class abc
er ,
ai C,
print(obj.age) # Printing Attribute AGE
r
obj.display() r ty l T ed o m
b o ca dd
l .c
25 k ra hni mbe a i
h a ec E
@ gm
Welcome... C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Syntax for Creating a Class
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
About using "self" in Python:
P ob l:
M ai
=> The self‐argument refers to the object itself. Hence the use
M
of the word self. So inside this method, self will refer to th
e specific instance of this object that's being operated on.
=> Self is the name preferred by convention by Pythons to indic
ate the first parameter of instance methods in Python. It is pa
rt of the Python syntax to access members of objects
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 1/9
12/17/2018 PyOPPBegineer slides
In [1]: class human:
#Constructor of Class
def __init__(self,name,age):
self.name = name
self.age = age
p1 = human("John", 36)
print("Printing in Main...") AI
print("Name is: ",p1.name) ,
DL
print("Age is: ",p1.age) ,
DS
Printing in Main...
n er ML,
Name is: John
r ai C,
Age is: 36
r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
Creating Function in Class
k
a ec E gm
h
C T B, @
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 2/9
12/17/2018 PyOPPBegineer slides
In [6]: class human:
#Constructor of Class
def __init__(self,name,age):
self.name = name
self.age = age
def display(self):
print("Executing in Function display()")
print("Welcome: ",self.name)
AI
p1 = human("XXYY", 36) ,
DL
,
print("Printing in Main...") DS
print("Name is: ",p1.name) n er ML,
print("Age is: ",p1.age) r ai C,
p1.display() r ty l T ed o m
b o ca dd
l .c
a i e i
Printing in Main... kr hn mb a
a c E
Name is: XXYY Ch Te , @ gm
l
Age is: 36 ep & LAB 60 na
e te AT 3 ur
Executing in Function display()
d
h a ra M 18 jo
b po n, 00 a.
Welcome: XXYY
u
S or ho 91 bh
C yt : 8 su
Creating Multiple Function in Class
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 3/9
12/17/2018 PyOPPBegineer slides
In [13]: class human:
#Constructor of Class
def __init__(self,name,age):
self.name = name
self.age = age
def display(self):
print("Executing in Function display()")
print("Welcome: ",self.name)
def showname(self,name): AI
L,
print("Executing in Function display()")
D
print("Welcome: ",self.name) ,
DS
p1 = human("XXYY", 36) n er ML,
r ai C,
print("Printing in Main...") r ty l T ed o m
print("Name is: ",p1.name) b o ca dd
l .c
print("Age is: ",p1.age)
k ra hni mbe a i
h a ec E
@ gm
p1.display() C T B,
p & A 0 n al
p1.showname(name) #Accessed only by p1.name
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Printing in Main...
u
S or ho 91 bh
Name is: XXYY
C yt : 8 su
Age is: 36
P ob l:
Executing in Function display()
M ai
Welcome: XXYY
M
Executing in Function display()
Welcome: XXYY
Checking Attributes:
getattr() ‐‐‐> Get the attribute from class
hasattr() ‐‐‐> Check whether class has an attribute given
setattr() ‐‐‐> Set new attribute
delattr() ‐‐‐> Delete an attribute
getattr()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 4/9
12/17/2018 PyOPPBegineer slides
In [21]: class human:
age = 23
name = "Adam"
hmn = human()
print("Demonstrating getattr()")
print('The age is:', getattr(hmn, "age")) #Using getattr method
print('The age is:', human.age) #Using Class name
print('The age is:', hmn.age,"\n") #Using Object na
A I
me ,
DL
,
Demonstrating getattr() DS
The age is: 23
n er ML,
The age is: 23
r ai C,
The age is: 23
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
hasattr() C T B,
al
p & A 0 n
d ee te ATL 36 ur
In [22]: class human:
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
age = 23
C yt : 8 su
name = "Adam"
P ob l:
M ai
hmn = human() M
print("Demonstrating hasattr()")
print('Person has age?:', hasattr(hmn, 'age'))
print('Person has salary?:', hasattr(hmn, 'salary'),"\n")
Demonstrating hasattr()
Person has age?: True
Person has salary?: False
setattr()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 5/9
12/17/2018 PyOPPBegineer slides
In [27]: class human:
age = 23
name = "Adam"
hmn = human()
print("Demonstrating setattr()")
print("Name before setattr(): ",hmn.name)
setattr(hmn, 'name', 'John')
print('After modification:', hmn.name,"\n") AI
,
Demonstrating setattr()
DL
,
Name before setattr(): Adam DS
After modification: John
n er ML,
r ai C,
r ty l T ed o m
b o ca dd .c
delattr() l
k ra hni mbe a i
h a ec E
@ gm
C T B,
In [25]: class human: p & A 0 n al
age = 23 d ee te ATL 36 ur
a ra M 18 jo
name = "Adam"
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
hmn = human()
P ob l:
print("Demonstrating delattr()")
M ai
delattr(human, 'age')
M
print("After Delete attr age: ",hmn.age)
Demonstrating delattr()
‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
‐‐‐‐‐‐‐‐‐‐‐‐‐‐
AttributeError Traceback (most rec
ent call last)
<ipython‐input‐25‐82c4e8aad6d9> in <module>()
6 print("Demonstrating delattr()")
7 delattr(human, 'age')
‐‐‐‐> 8 print("After Delete attr age: ",hmn.age)
AttributeError: 'human' object has no attribute 'age'
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 6/9
12/17/2018 PyOPPBegineer slides
Example of using a Class with main()
In [2]: class myClass():
def method1(self):
print("Method1.....")
def method2(self,someString):
print("Method2....." + someString)
AI
,
DL
def main():
,
DS
# exercise the class methods
n er ML,
c = myClass ()
r ai C,
c.method1()
r ty l T ed o m
c.method2(" Testing is fun")
b o ca dd
l .c
ra hni mbe
#main() # Recursive Main Function
k a i
h a ec E
@ gm
C T B,
if __name__== "__main__":
p & A 0 n al
e
main() de te TL 836 our
A
b ha ora , M 01 .j
0 a
Su orp hon 91 bh
Method1.....
C yt : 8 su
Method2..... Testing is fun
P ob l:
M ai
M
Inheritance
Example1: Simple Inheritance
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 7/9
12/17/2018 PyOPPBegineer slides
In [10]: class myClass():
def method1(self):
print("MyClass Method1....")
class childClass(myClass):
#def method1(self):
#myClass.method1(self);
#print ("childClass Method1")
AI
def method2(self): ,
DL
print("childClass method2") ,
DS
def main(): n er ML,
# exercise the class methods r ai C,
y T d m
c2 = childClass() rt l e o
c2.method1() b o ca dd
l .c
#c2.method2() ak ch
ra ni mbe a i
h e E @ gm
C T B,
p & A 0 n al
if __name__== "__main__":
d ee te ATL 36 ur
main() a
h r a M 018 jo
u b po n, 0 a.
S or ho 91 bh
MyClass Method1....
C yt : 8 su
P ob l:
M ai
Example2: Multiple Inheritance
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 8/9
12/17/2018 PyOPPBegineer slides
In [12]: class Base1(object):
def __init__(self):
self.str1 = "Constructor Base1"
print("Hello Constructor..Base1...")
print("Within Constructor of Base1...")
class Base2(object):
def __init__(self):
self.str2 = "Constructor Base2"
print("Hello Constructor..Base2...") AI
print("Within Constructor of Base2...") L,
D
class Derived(Base1, Base2): ,
def __init__(self): DS
n er ML,
# Calling constructors of Base1
r ai C,
# and Base2 classes r ty l T ed o m
b o ca dd
Base1.__init__(self) l .c
ra hni mbe
Base2.__init__(self)
k a i
h a ec E
@ gm
print("Within Constructor of Derived...")
C T B,
p & A 0 n al
e
d e te ATL 36 ur
a ra M 18 jo
def printStrs(self):
h
b po n, 00 a.
print(self.str1, self.str2)
u
S or ho 91 bh
C yt : 8 su
P ob l:
ob = Derived()
M ai
ob.printStrs()
M
Hello Constructor..Base1...
Within Constructor of Base1...
Hello Constructor..Base2...
Within Constructor of Base2...
Within Constructor of Derived...
Constructor Base1 Constructor Base2
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOPPBegineer.slides.html 9/9
12/17/2018 PyOOPs slides
Python OOPs Tutorial
Object Oriented Teminology
class: Classes are a userdefined data type that is used to
encapsulate data and associated functions together. It also
AI
helps in binding data together into a single unit. ,
DL
D S,
Data Member: A variable or memory location name that holds
er ML,
value to does a specific task within a program.
n
r ai C,
r ty l T ed o m
b o ca dd
l .c
Member Function: They are the functions; usually a block of a
ra hni mbe
code snippet that is written to reuse it.
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Instance variable: A variable that is defined inside a method of a
d 8 o
class. bha ora , M 001 a.j
Su orp hon 91 bh
C yt : 8 su
Function Overloading: This technique is used to assign multiple
P ob l:
M ai
tasks to a single function & the tasks are performed based on
M
the number of argument or the type of argument the function
has.
Operator Overloading: It is the technique of assigning multiple
function/tasks to a particular operator.
Inheritance: It is the process of acquiring the properties of one
class to another, i.e., one class can acquire the properties of
another.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 1/17
12/17/2018 PyOOPs slides
Instantiation: It is the technique of creating an instance of a
class.
Creating a Sample Class
In [1]: #Example‐1
class human:
AI
def __init__(self,name,age): ,
self.name = name DL
,
self.age = age DS
n er ML,
p1 = human("John", 36)
r ai C,
r ty l T ed o m
print("Printing in Main...")
b o ca dd
l .c
ra hni mbe
print("Name is: ",p1.name)
k a i
a ec E
print("Age is: ",p1.age)
h @ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Printing in Main...
d
a ra M 18 jo
Name is: John
h
u b po n, 00 a.
S or ho 91 bh
Age is: 36
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 2/17
12/17/2018 PyOOPs slides
In [2]: #Example‐2
class human:
def __init__(self,name,age):
self.name = name
self.age = age
def display(self):
print("Printing in Function under Class")
print("Name is: ",self.name)
print("Age is: ",self.age) AI
,
DL
p1 = human("John", 36) ,
p1.display() DS
n er ML,
Printing in Function under Class ai ,
Name is: John t y Tr d C m
r l e o
Age is: 36 b o ca dd
l .c
k ra hni mbe a i
In [11]: h a ec E
@ gm
#Example‐2 C T B,
p & A 0 n al
class human: e
d e te ATL 36 ur
a ra M 18 jo
def __init__(self,name,age):
h
b po n, 00 a.
self.name = name
u
S or ho 91 bh
self.age = age
C yt : 8 su
def display(self):
P ob l:
M ai
print("Printing in Function under Class")
M
print("Name is: ",self.name)
print("Age is: ",self.age)
n=input("Enter your name: ")
a=int(input("Enter your age: "))
p1 = human(n,a)
p1.display()
Enter your name: Subhadeep
Enter your age: 29
Printing in Function under Class
Name is: Subhadeep
Age is: 29
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 3/17
12/17/2018 PyOOPs slides
Using Predefined Functons
getattr( obj, name [,default] ) : used to access object's attribute.
hasattr( object, name): used for checking whether the attribute
exists or not.
AI
setattr( obj, name, value ) : set or create an attribute, if doesn't
,
DL
exist. ,
DS
er ML,
delattr( obj, name ) : used to delete an attribute.
n
r ai C,
r ty l T ed o m
Example: o ca dd .c
b l
k ra hni mbe a i
getattr() h a ec E
@ gm
C T B,
p & A 0 n al
setattr() d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
hasattr()
S or ho 91 bh
C yt : 8 su
P ob l:
delattr() M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 4/17
12/17/2018 PyOOPs slides
In [34]: class human:
age = 23
name = "Adam"
hmn = human()
print("Demonstrating getattr()")
print('The age is:', getattr(hmn, "age")) #Using getattr method
print('The age is:', human.age) #Using Class name
print('The age is:', hmn.age,"\n") #Using Object na
A I
me ,
DL
print("Demonstrating hasattr()")
D S,
print('Person has age?:', hasattr(hmn, 'age'))
er ML,
print('Person has salary?:', hasattr(hmn, 'salary'),"\n")
n
# setting name to 'John' r ai C,
ty l T ed
print("Demonstrating setattr()")
r o m
b o ca dd
print("Name before setattr(): ",hmn.name) l .c
ra hni mbe
setattr(hmn, 'name', 'John')
k a i
h a ec E
@ gm
print('After modification:', hmn.name,"\n")
C T B,
p & A 0 n al
print("Demonstrating delattr()")
d ee te ATL 36 ur
a ra M 18 jo
#delattr(human, 'age')
h
b po n, 00 a.
print("After Delete attr age: ",hmn.age)
u
S or ho 91 bh
C yt : 8 su
Demonstrating getattr()
P ob l:
The age is: 23
M ai
The age is: 23
M
The age is: 23
Demonstrating hasattr()
Person has age?: True
Person has salary?: False
Demonstrating setattr()
Name before setattr(): Adam
After modification: John
Demonstrating delattr()
After Delete attr age: 23
Examples of Class
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 5/17
12/17/2018 PyOOPs slides
Examples of Class
In [35]: #Example‐3
class Parrot:
# class attribute
species = "bird"
# instance attribute AI
,
def __init__(self, name, age): DL
self.name = name ,
self.age = age
DS
n er ML,
# instantiate the Parrot class r ai C,
y T d m
blu = Parrot("Blu", 10) rt l e o
b o ca dd
l .c
woo = Parrot("Woo", 15)
k ra hni mbe a i
h a ec E
@ gm
C T B,
# access the class attributes
p & A 0 n al
ee te ATL 36 ur
print("Blu is a {}".format(blu.__class__.species))
d
a ra M 18 jo
print("Woo is also a {}".format(woo.__class__.species))
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
# access the instance attributes
P ob l:
print("{} is {} years old".format( blu.name, blu.age))
M ai
print("{} is {} years old".format( woo.name, woo.age))
M
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 6/17
12/17/2018 PyOOPs slides
In [36]: #Example‐4
class Parrot:
# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age
# instance method AI
def sing(self, song): ,
DL
return "{} sings {}".format(self.name, song)
,
DS
def dance(self): n er ML,
ai C,
return "{} is now dancing".format(self.name)
r
r ty l T ed o m
# instantiate the object b o ca dd
l .c
blu = Parrot("Blu", 10)
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
# call our instance methods
d ee te ATL 36 ur
a ra M 18 jo
print(blu.sing("'Happy'"))
h
b po n, 00 a.
print(blu.dance())
u
S or ho 91 bh
C yt : 8 su
Blu sings 'Happy'
P ob l:
Blu is now dancing
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 7/17
12/17/2018 PyOOPs slides
In [39]: #Example‐5
class Email:
def __init__(self):
self.is_sent = False
def send_email(self):
self.is_sent = True
my_email = Email()
print("Print from Constructor: ",my_email.is_sent) A
I
,
DL
my_email.send_email()
D S,
print("Print from Method: ",my_email.is_sent)
n er ML,
Print from Constructor: False ai ,
Print from Method: True ty Tr d C m
r l e o
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 8/17
12/17/2018 PyOOPs slides
In [40]: #Example‐6
class Dog:
# Class Attribute
species = 'mammal'
# Initializer / Instance Attributes
def __init__(self, name, age):
self.name = name AI
self.age = age ,
DL
,
# instance method DS
def description(self): n er ML,
ai C,
return "{} is {} years old".format(self.name, self.age)
r
r ty l T ed o m
o a d
# instance method ab ic ed l .c
r hn mb a i
def speak(self, sound):
k
h a ec E
@ gm
return "{} says {}".format(self.name, sound)
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
# Instantiate the Dog object
h
b po n, 00 a.
mikey = Dog("Mikey", 6)
u
S or ho 91 bh
C yt : 8 su
P ob l:
# call our instance methods
M ai
print(mikey.description())
M
print(mikey.speak("Gruff Gruff"))
Mikey is 6 years old
Mikey says Gruff Gruff
Inheritance
Single Inheritance
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 9/17
12/17/2018 PyOOPs slides
In [43]: class Person(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name AI
,
DL
# To check if this person is employee ,
def isEmployee(self): DS
return False n er ML,
r ai C,
r ty l T ed o m
b o ca dd
# Inherited or Sub class (Note Person in bracket)
l .c
class Employee(Person):
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
# Here we return true
d ee te ATL 36 ur
a ra M 18 jo
def isEmployee(self):
h
b po n, 00 a.
return True
u
S or ho 91 bh
C yt : 8 su
# Driver code
P ob l:
emp = Person("Subhadeep") # An Object of Person
M ai
print(emp.getName(), emp.isEmployee())
M
emp = Employee("Chakraborty") # An Object of Employee
print(emp.getName(), emp.isEmployee())
Subhadeep False
Chakraborty True
Multiple Inheritance
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 10/17
12/17/2018 PyOOPs slides
In [49]: class Base1(object):
def __init__(self):
self.str1 = "Subhadeep_Base1"
print("Chakraborty")
print("Within Constructor of Base1...")
class Base2(object):
def __init__(self):
self.str2 = "Subhadeep_Base2"
print("Chakraborty") AI
print("Within Constructor of Base2...") L,
D
class Derived(Base1, Base2): ,
def __init__(self): DS
n er ML,
# Calling constructors of Base1
r ai C,
# and Base2 classes r ty l T ed o m
b o ca dd
Base1.__init__(self) l .c
ra hni mbe
Base2.__init__(self)
k a i
h a ec E
@ gm
print("Within Constructor of Derived...")
C T B,
p & A 0 n al
e
d e te ATL 36 ur
a ra M 18 jo
def printStrs(self):
h
b po n, 00 a.
print(self.str1, self.str2)
u
S or ho 91 bh
C yt : 8 su
P ob l:
ob = Derived()
M ai
ob.printStrs()
M
Chakraborty
Within Constructor of Base1...
Chakraborty
Within Constructor of Base2...
Within Constructor of Derived...
Subhadeep_Base1 Subhadeep_Base2
Multilevel Inheritance
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 11/17
12/17/2018 PyOOPs slides
In [55]: class Animal:
def eat(self):
print('Eating...')
class Dog(Animal):
def bark(self):
print('Barking...')
class BabyDog(Dog):
def weep(self):
print('Weeping...') AI
d=BabyDog() ,
DL
d.eat() ,
d.bark() DS
d.weep() n er ML,
r ai C,
Eating...
r ty l T ed o m
Barking... b o ca dd
l .c
Weeping... k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
Using Parent class name
ee te ATL 36 ur
d
a ra M 18 jo
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 12/17
12/17/2018 PyOOPs slides
In [50]: # Python example to show that base
# class members can be accessed in
# derived class using base class name
class Base(object):
# Constructor
def __init__(self, x):
self.x = x
class Derived(Base): AI
,
DL
# Constructor ,
def __init__(self, x, y): DS
Base.x = x n er ML,
self.y = y r ai C,
r ty l T ed o m
def printXY(self): b o ca dd
l .c
ra hni mbe
# print(self.x, self.y) will also work
k a i
h a ec E
@ gm
print(Base.x, self.y)
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
# Driver Code
u
S or ho 91 bh
C yt : 8 su
d = Derived(10, 20)
P ob l:
d.printXY()
M ai
10 20
M
Using super() #1
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 13/17
12/17/2018 PyOOPs slides
In [51]: # Python example to show that base
# class members can be accessed in
# derived class using super()
class Base(object):
# Constructor
def __init__(self, x):
self.x = x
class Derived(Base): AI
,
DL
# Constructor ,
def __init__(self, x, y): DS
n er ML,
ai C,
''' In Python 3.x, "super().__init__(name)"
r
also works''' r ty l T ed o m
b o ca dd
super(Derived, self).__init__(x) l .c
self.y = y k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
def printXY(self):
d ee te ATL 36 ur
a ra M 18 jo
# Note that Base.x won't work here
h
b po n, 00 a.
# because super() is used in constructor
u
S or ho 91 bh
C yt : 8 su
print(self.x, self.y)
P ob l:
M ai
M
# Driver Code
d = Derived(10, 20)
d.printXY()
10 20
Using super()#2
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 14/17
12/17/2018 PyOOPs slides
In [58]: class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm‐blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')
AI
d1 = Dog() ,
DL
,
Dog has four legs. DS
Dog is a warm‐blooded animal.
n er ML,
r ai C,
ty l T ed
Check if a class is subclass of another
r o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 15/17
12/17/2018 PyOOPs slides
In [45]: # Python example to check if a class is
# subclass of another
class Base(object):
pass # Empty Class
class Derived(Base):
pass # Empty Class
AI
# Driver Code ,
DL
print(issubclass(Derived, Base)) ,
print(issubclass(Base, Derived)) DS
n er ML,
b = Base() r ai C,
d = Derived() r ty l T ed o m
b o ca dd
l .c
ra hni mbe
# b is not an instance of Derived
k a i
h a ec E
@ gm
print(isinstance(b, Derived))
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
# But d is an instance of Base
h
b po n, 00 a.
print(isinstance(d, Base))
u
S or ho 91 bh
C yt : 8 su
True P ob l:
False M ai
False
M
True
Implicit Inheritance
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 16/17
12/17/2018 PyOOPs slides
In [59]: class super (object) :
def implicit(self) :
print ("Super‐Class with Implicit function")
class sub(super) :
pass
su = super() AI
sb = sub() ,
DL
,
su.implicit() DS
sb.implicit() n er ML,
r ai C,
ty l T ed
Super‐Class with Implicit function
r o m
o ca dd
Super‐Class with Implicit function
b l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyOOPs.slides.html 17/17
12/17/2018 PyException slides
Python Exception Handling
Exception meand the probable or ineviatble error to be occured
in the course of programming.
Python has many builtin exceptions which forces your program
I
to output an error when something in it goes wrong.A
,
DL
When these exceptions occur, it causes the current process to ,
DS
stop and passes it to the calling process until it is handled. If not
n er ML,
handled, our program will crash. ai ,
t y Tr d C m
o
Python use TryExcept to catch and show the error.
r l
o ca dd e .c
b l
k ra hni mbe a i
try: h a ec E
@ gm
C T B,
# write some code
p & A 0 n al
ee te ATL 36 ur
# that might throw exception
d
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
except ExceptionType:
C yt : 8 su
P ob l:
# Exception handler, alert the user
M ai
M
Much Detailed Syntaxing of
Exception
try:
‐‐body‐‐
except ExceptionType1:
‐‐handler1‐‐
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyException.slides.html 1/6
12/17/2018 PyException slides
except ExceptionTypeN:
‐‐handlerN‐‐
except:
‐‐handlerExcept‐‐
else: AI
,
<process_else> DL
,
DS
n er ML,
finally: ai C,
r
<process_finally>
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
Exception Hierarchyp
C T B,
& A
ee te ATL 36 ur
0 n al
d
a ra M 18 jo
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
Program1: Simple TryExcept
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyException.slides.html 2/6
12/17/2018 PyException slides
In [1]: try:
num1, num2 = eval(input("Enter two numbers, separated by a c
omma : "))
result = num1 / num2
print("Result is", result)
except ZeroDivisionError:
print("Division by zero is error !!")
except SyntaxError:
print("Comma is missing. Enter numbers separated by comma li
A I
ke this 1, 2") ,
DL
except: ,
print("Wrong input") DS
else: n er ML,
print("No exceptions") r ai C,
finally: r ty l T ed o m
b o ca dd .c
print("This is the finally block and willbe executed no matt
l
ra hni mbe
er the error occured or not")
k a i
h a ec E
@ gm
C T B,
& A 0 n al
Enter two numbers, separated by a comma : 2,3
p
ee te ATL 36 ur
Result is 0.6666666666666666
d
h a ra M 18 jo
b po n, 00 a.
No exceptions
u
S or ho 91 bh
This is the finally block and willbe executed no matter the e
C yt : 8 su
rror occured or not
P ob l:
M ai
M
Program2: Raising an Error
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyException.slides.html 3/6
12/17/2018 PyException slides
In [9]: def enterage(age):
if age < 0:
raise ValueError("Only positive integers are allowed")
if age % 2 == 0:
print("age is even")
else:
print("age is odd")
try: AI
num = int(input("Enter your age: ")) ,
DL
enterage(num) ,
except ValueError as e: DS
r ,
ne ML
print("Only positive integers are allowed")
except: r ai C,
ty l T ed
print("something is wrong")
r o m
b o ca dd
l .c
a i e i
Enter your age: ‐3 kr hn mb a
h a ec E
Only positive integers are allowed @ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
Program3: Python User
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Defined Exception
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyException.slides.html 4/6
12/17/2018 PyException slides
In [7]: # define Python user‐defined exceptions
class Error(Exception):
"""Base class for other exceptions"""
pass
class ValueTooSmallError(Error):
"""Raised when the input value is too small"""
pass
AI
class ValueTooLargeError(Error): ,
DL
"""Raised when the input value is too large"""
,
pass DS
n er ML,
# our main program r ai C,
ty l T ed
# user guesses a number until he/she gets it right
r o m
b o ca dd
l .c
ra hni mbe
# you need to guess this number
k a i
h a ec E
@ gm
number = 10 C T B,
p & A 0 n al
d ee te ATL 36 ur
while True:
h a ra M 18 jo
try:
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
i_num = int(input("Enter a number: "))
P ob l:
if i_num < number:
M ai
raise ValueTooSmallError
M
elif i_num > number:
raise ValueTooLargeError
break
except ValueTooSmallError:
print("This value is too small, try again!")
print()
except ValueTooLargeError:
print("This value is too large, try again!")
print()
print("Congratulations! You guessed it correctly.")
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyException.slides.html 5/6
12/17/2018 PyException slides
Enter a number: 2
This value is too small, try again!
Enter a number: 45
This value is too large, try again!
Enter a number: 12
This value is too large, try again!
Enter a number: 10
AI
,
Congratulations! You guessed it correctly. DL
,
DS
er ML,
Program4: Accessing File in
n
r ai C,
ty l T ed
Disk o m
r
b o ca dd
l .c
k ra hni mbe a i
In [3]: try: h a ec E
@ gm
C T B,
& A 0 n al
fh = open("D:\\As a Trainer\\Odissa‐Totsol\\Mod‐12(Exceptio
p
ee te ATL 36 ur
n)\\New.txt", "w")
d
h a ra M 18 jo
b po n, 00 a.
fh.write("This is my test file for exception handling!!")
u
S or ho 91 bh
except IOError:
C yt : 8 su
print ("Error: can\'t find file or read data")
P ob l:
else: M ai
M
print ("Written content in the file successfully")
fh = open("D:\\As a Trainer\\Odissa‐Totsol\\Mod‐12(Exceptio
n)\\New.txt", "r")
print("Content of the File:\n",fh.read())
fh.close()
finally:
print("Operation executed")
Error: can't find file or read data
Operation executed
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyException.slides.html 6/6
12/17/2018 Python_SQL slides
Python SQL Tutorial
SQL Connectivity
In [1]: import mysql.connector
AI
Create Connection ,
DL
,
In [3]: try: DS
r L,
ne
mydb = mysql.connector.connect(
i M
host="localhost",
y T ra C,
user="root", t l ed o m
r
passwd="$$1234[]", b o ca dd
l .c
database="uidpass"
k ra hni mbe a i
h a ec E
@ gm
) C T B,
p & A 0 n al
except:
d ee te ATL 36 ur
a ra M 18 jo
mycursor = mydb.cursor()
h
b po n, 00 a.
mycursor.execute("CREATE DATABASE pysqldatabase")
u
S or ho 91 bh
C yt : 8 su
print(mydb) P ob l:
M ai
M
<mysql.connector.connection_cext.CMySQLConnection object at 0
x0000006BED261D68>
Create & Show Table
In [18]: mycursor.execute("CREATE TABLE customers (id INT AUTO_INCREMENT
PRIMARY KEY, name VARCHAR(255), job VARCHAR(255))")
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/Python_SQL.slides.html 1/4
12/17/2018 Python_SQL slides
In [19]: mycursor = mydb.cursor()
mycursor.execute("SHOW TABLES")
for x in mycursor:
print(x)
('customers',)
Insert Data into Table AI
,
DL
In [30]: name=input("Enter Name: ")
,
DS
job=input("Enter Job: ")
n er ML,
Enter Name: Rakesh r ai C,
Enter Job: Business r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
In [31]: a ec E gm
sql = "INSERT INTO customers (name, job) VALUES (%s, %s)"
h @
C T B,
val = (name, job)
p & A 0 n al
ee te ATL 36 ur
mycursor.execute(sql, val)
d
a ra M 18 jo
mydb.commit()
h
u b po n, 00 a.
S or ho 91 bh
print(mycursor.rowcount, "record inserted.")
C yt : 8 su
P ob l:
1 record inserted.
M ai
M
Select Data from Table
In [32]: mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
(1, 'Subhadeep', 'Corporate Trainer')
(2, 'Subhadeep', 'Corporate Trainer')
(3, 'Rajesh', 'Developer')
(4, 'Rakesh', 'Business')
Fetch particular Record from Table using "where"
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/Python_SQL.slides.html 2/4
12/17/2018 Python_SQL slides
In [33]: sql = "SELECT * FROM customers WHERE job ='Corporate Trainer'"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
(1, 'Subhadeep', 'Corporate Trainer')
(2, 'Subhadeep', 'Corporate Trainer')
AI
,
MySQL ORDER by filtering DL
,
DS
In [38]: er L,
sql = "SELECT * FROM customers ORDER BY name"
i n M
mycursor.execute(sql)
y T ra C,
myresult = mycursor.fetchall() t l ed o m
r
for x in myresult: b o ca dd
l .c
print(x) k ra hni mbe a i
h a ec E
@ gm
C T B,
(3, 'Rajesh', 'Developer')
p & A 0 n al
ee te ATL 36 ur
(1, 'Subhadeep', 'Corporate Trainer')
d
a ra M 18 jo
(2, 'Subhadeep', 'Corporate Trainer')
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Delete Record
P ob l:
M ai
M
In [39]: sql = "DELETE FROM customers WHERE job = 'Business'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) deleted")
0 record(s) deleted
Update Table
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/Python_SQL.slides.html 3/4
12/17/2018 Python_SQL slides
In [37]: sql = "UPDATE customers SET job = 'Corporate' WHERE job = 'Busin
ess'"
mycursor.execute(sql)
mydb.commit()
print(mycursor.rowcount, "record(s) affected")
0 record(s) affected
Limit Table AI
,
DL
In [40]: mycursor.execute("SELECT * FROM customers LIMIT 5")
,
DS
myresult = mycursor.fetchall()
n er ML,
for x in myresult:
r ai C,
print(x)
r ty l T ed o m
b o ca dd
l .c
(1, 'Subhadeep', 'Corporate Trainer')
k ra hni mbe a i
(2, 'Subhadeep', 'Corporate Trainer')
h a ec E
@ gm
C T B,
(3, 'Rajesh', 'Developer')
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Limit and Offset
h
b po n, 00 a.
u
S or ho 91 bh
C yt : 8 su
In [41]: mycursor.execute("SELECT * FROM customers LIMIT 5 OFFSET 2")
P ob l:
M ai
myresult = mycursor.fetchall()
M
for x in myresult:
print(x)
(3, 'Rajesh', 'Developer')
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/Python_SQL.slides.html 4/4
12/17/2018 PyTKBegin slides
TKINTER TUTORIAL
Sample GUI
In [3]: from tkinter import *
window = Tk() AI
,
DL
window.title("MY FIRST GUI") ,
DS
window.mainloop() n er ML,
r ai C,
r ty l T ed o m
Print Text b o ca dd
l .c
k ra hni mbe a i
In [8]: h a ec E
@ gm
from tkinter import *
C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
window = Tk()
h
u b po n, 00 a.
S or ho 91 bh
window.title("MY FIRST GUI")
C yt : 8 su
P ob l:
M ai
lbl = Label(window, text="Hello")
M
#lbl = Label(window, text="Hello", font=("Times New Roman Bold",
50))
lbl.grid(column=0, row=0)
window.mainloop()
Adding Click Button
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 1/16
12/17/2018 PyTKBegin slides
In [10]: from tkinter import *
window = Tk()
window.title("Click GUI")
window.geometry('350x200')
lbl = Label(window, text="Hello") AI
,
DL
lbl.grid(column=0, row=0) ,
DS
r ,
ne ML
btn = Button(window, text="Click Me")
r ai C,
ty l T ed m
#btn = Button(window, text="Click Me", bg="orange", fg="red")
r o
b o ca dd
l .c
ra hni mbe
btn.grid(column=1, row=0)
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
window.mainloop()
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
Add a Button Click GUI
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 2/16
12/17/2018 PyTKBegin slides
In [12]: from tkinter import *
window = Tk()
window.title("ButtobClick GUI")
window.geometry('350x200')
lbl = Label(window, text="Hello") AI
,
DL
lbl.grid(column=0, row=0) ,
DS
def clicked(): n er ML,
r ai C,
ty l T ed
lbl.configure(text="Button was clicked !!")
r o m
b o ca dd
l .c
ra hni mbe a i
btn = Button(window, text="Click Me", command=clicked)
k
h a ec E
@ gm
C T B,
p & A 0 n al
btn.grid(column=1, row=0)
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
window.mainloop()
u
S or ho 91 bh
C yt : 8 su
P b :
Entry ButtonMo il
Ma
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 3/16
12/17/2018 PyTKBegin slides
In [14]: from tkinter import *
window = Tk()
window.title("Entry Button")
window.geometry('350x200')
lbl = Label(window, text="Hello") AI
,
DL
lbl.grid(column=0, row=0) ,
DS
txt = Entry(window,width=20) n er ML,
r ai C,
txt.grid(column=1, row=0) r ty l T ed o m
b o ca dd
l .c
def clicked(): k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
lbl.configure(text="Welcome!!")
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
btn = Button(window, text="Click Me", command=clicked)
u
S or ho 91 bh
C yt : 8 su
P ob l:
btn.grid(column=2, row=0)
M ai
M
window.mainloop()
Adding Entry Button & Get Text after click
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 4/16
12/17/2018 PyTKBegin slides
In [18]: from tkinter import *
window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('350x200')
lbl = Label(window, text="Hello") AI
,
DL
lbl.grid(column=0, row=0) ,
DS
txt = Entry(window,width=10) n er ML,
r ai C,
ty l T ed
#txt = Entry(window,width=10, state='disabled')
r o m
b o ca dd
l .c
ra hni mbe
txt.grid(column=1, row=0)
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
def clicked():
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
res = "Welcome to " + txt.get()
u
S or ho 91 bh
C yt : 8 su
print(txt.get())
P ob l:
lbl.configure(text= res)
M ai
M
btn = Button(window, text="Click Me", command=clicked)
btn.grid(column=2, row=0)
window.mainloop()
Markdown Button GUI
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 5/16
12/17/2018 PyTKBegin slides
In [16]: from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title("Markdown Button GUI")
window.geometry('350x200') AI
,
DL
combo = Combobox(window) ,
DS
r ,
ne ML
combo['values']= (1, 2, 3, 4, 5, "Select")
r ai C,
ty l T ed
combo.current(0) #set the selected item
r o m
b o ca dd
l .c
ra ni mbe
print(combo.get()) ak ch a i
h e E @ gm
C T B,
p & A 0 n al
combo.grid(column=0, row=0)
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
window.mainloop()
u
S or ho 91 bh
C yt : 8 su
1 P ob l:
M ai
M
CheckBox Button GUI
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 6/16
12/17/2018 PyTKBegin slides
In [19]: from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title("CheckBox Button GUI")
window.geometry('350x200') AI
,
DL
chk_state = BooleanVar() ,
DS
r L,
ne
chk_state.set(True) #set check state
i M
y T ra C,
t l ed
chk = Checkbutton(window, text='Choose', var=chk_state)
o m
r
b o ca dd
l .c
ra hni mbe
chk.grid(column=0, row=0)
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
window.mainloop()
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
Creating Radio Button
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 7/16
12/17/2018 PyTKBegin slides
In [24]: from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('350x200') AI
,
DL
rad1 = Radiobutton(window,text='First', value=1)
,
DS
r ,
ne ML
rad2 = Radiobutton(window,text='Second', value=2)
r ai C,
ty l T ed
rad3 = Radiobutton(window,text='Third', value=3)
r o m
b o ca dd
l .c
ra hni mbe
rad1.grid(column=0, row=0)
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
rad2.grid(column=1, row=0)
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
rad3.grid(column=2, row=0)
u
S or ho 91 bh
C yt : 8 su
P ob l:
window.mainloop()
M ai
M
Get radio button value
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 8/16
12/17/2018 PyTKBegin slides
In [25]: from tkinter import *
from tkinter.ttk import *
window = Tk()
window.title("Welcome to LikeGeeks app")
selected = IntVar() AI
,
DL
rad1 = Radiobutton(window,text='First', value=1, variable=select
,
ed) DS
n er ML,
ai C,
rad2 = Radiobutton(window,text='Second', value=2, variable=selec
r
ted) r ty l T ed o m
b o ca dd
l .c
ra hni mbe a i
rad3 = Radiobutton(window,text='Third', value=3, variable=select
k
h a ec E
@ gm
ed) C T B,
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
def clicked():
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
print(selected.get())
P ob l:
M ai
btn = Button(window, text="Click Me", command=clicked)
M
rad1.grid(column=0, row=0)
rad2.grid(column=1, row=0)
rad3.grid(column=2, row=0)
btn.grid(column=3, row=0)
window.mainloop()
3
2
1
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 9/16
12/17/2018 PyTKBegin slides
Add a ScrolledText widget==> Text Pad
In [29]: from tkinter import *
from tkinter import scrolledtext
window = Tk()
window.title("Hello TK")
AI
,
DL
window.geometry('350x200') ,
DS
n er ML,
txt = scrolledtext.ScrolledText(window,width=40,height=10)
r ai C,
r ty l T ed o m
#txt.insert(INSERT,'You text goes here')
b o ca dd
l .c
txt.delete(1.0,END) ra ni be i
k h m a
h a ec E
@ gm
C T B,
txt.grid(column=0,row=0)
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
window.mainloop()
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
Create a MessageBox
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 10/16
12/17/2018 PyTKBegin slides
In [3]: from tkinter import *
from tkinter import messagebox
window = Tk()
window.title("TK MSG WIDGET")
window.geometry('350x200') AI
,
DL
def clicked(): ,
DS
r ,
ne ML
messagebox.showinfo('Message title', 'Welcome to TK Message
Box') r ai C,
r ty l T ed o m
b o ca dd .c
messagebox.showwarning('Message title', 'Warning!!') #shows war
l
ning message k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
messagebox.showerror('Message title', 'Opening Error!!') #sho
d ee te ATL 36 ur
a ra M 18 jo
ws error message
h
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
res = messagebox.askquestion('Message title','Question Box')
P ob l:
M ai
res = messagebox.askyesno('Message title','Yes/No')
M
res = messagebox.askyesnocancel('Message title','Yes/No or Cance
l')
res = messagebox.askokcancel('Message title','OK')
res = messagebox.askretrycancel('Message title','Retry?')
btn = Button(window,text='Click here', command=clicked)
btn.grid(column=0,row=0)
window.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 11/16
12/17/2018 PyTKBegin slides
Add a Spin Box
In [6]: from tkinter import *
window = Tk()
window.title("Welcome to LikeGeeks app")
window.geometry('350x200') AI
,
DL
spin = Spinbox(window, from_=0, to=100, width=5)
,
DS
#spin = Spinbox(window, values=(3, 8, 11), width=5)
r ,
ne L M
r ai C,
#print(spin.get())
r ty l T ed o m
b o ca dd
l .c
ra hni mbe
spin.grid(column=0,row=0)
k a i
h a ec E
@ gm
C T B,
p
window.mainloop() & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
Add a Progress Bar
u
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 12/16
12/17/2018 PyTKBegin slides
In [1]: from tkinter import *
from tkinter.ttk import Progressbar
from tkinter import ttk
import time
window = Tk() AI
,
DL
window.title("Progress Bar Widget") ,
DS
window.geometry('350x200') n er ML,
r ai C,
style = ttk.Style() r ty l T ed o m
b o ca dd
l .c
ra hni mbe
style.theme_use('default')
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
style.configure("black.Horizontal.TProgressbar", background='bla
d ee te ATL 36 ur
ck')
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
bar = Progressbar(window, length=200, style='black.Horizontal.TP
P ob l:
rogressbar')
M ai
bar['value'] = 10
M
bar.grid(column=0, row=0)
window.mainloop()
Add a File Menu
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 13/16
12/17/2018 PyTKBegin slides
In [4]: from tkinter import *
from tkinter import Menu
window = Tk()
window.title("File Menu")
menu = Menu(window) AI
,
DL
new_item = Menu(menu) ,
DS
new_item.add_command(label='New') n er ML,
r ai C,
#.add_separator() r ty l T ed o m
b o ca dd
l .c
ra hni mbe
#new_item.add_command(label='Edit')
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
menu.add_cascade(label='File', menu=new_item)
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
window.config(menu=menu)
u
S or ho 91 bh
C yt : 8 su
P ob l:
window.mainloop()
M ai
M
Add a Notebook widget
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 14/16
12/17/2018 PyTKBegin slides
In [5]: from tkinter import ttk
window = Tk()
window.title("Welcome to LikeGeeks app")
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control) AI
,
DL
tab_control.add(tab1, text='First') ,
DS
r ,
ne ML
tab_control.pack(expand=1, fill='both')
r ai C,
window.mainloop() r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 15/16
12/17/2018 PyTKBegin slides
In [7]: from tkinter import *
from tkinter import ttk
window = Tk()
window.title("Welcome to LikeGeeks app")
tab_control = ttk.Notebook(window) AI
,
DL
tab1 = ttk.Frame(tab_control) ,
DS
tab2 = ttk.Frame(tab_control) n er ML,
r ai C,
ty l T ed
tab_control.add(tab1, text='First')
r o m
b o ca dd
l .c
ra hni mbe
tab_control.add(tab2, text='Second')
k a i
h a ec E
@ gm
C T B,
p & A 0 n al
lbl1 = Label(tab1, text= 'label1')
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
lbl1.grid(column=0, row=0)
u
S or ho 91 bh
C yt : 8 su
P ob l:
lbl2 = Label(tab2, text= 'label2')
M ai
M
lbl2.grid(column=0, row=0)
tab_control.pack(expand=1, fill='both')
window.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PyTKBegin.slides.html 16/16
12/17/2018 GUI1 slides
In [ ]: #GUI ‐1
In [1]: from tkinter import *
master = Tk()
Label(master, text="First Name").grid(row=0)
Label(master, text="Last Name").grid(row=1)
e1 = Entry(master)
AI
,
e2 = Entry(master) DL
,
DS
e1.grid(row=0, column=1)
n er ML,
e2.grid(row=1, column=1)
r ai C,
r ty l T ed o m
mainloop( )
b o ca dd
l .c
k ra hni mbe a i
In [2]: from tkinter import *
h a ec E
@ gm
C T B,
p & A 0 n al
master = Tk()
d ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
w=Label(master,text="Hello World!")
u
S or ho 91 bh
w.pack()
C yt : 8 su
master.mainloop()
P ob l:
M ai
M
Botton
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI1.slides.html 1/5
12/17/2018 GUI1 slides
In [12]: from tkinter import *
top = Tk()
def helloCallBack():
tkMessageBox.showinfo( "Hello Python", "Hello World")
Button(top, text ="Hello", command = helloCallBack)
A I
,
DL
,
top.mainloop() DS
n er ML,
In [13]: r ai C,
from tkinter import *
r ty l T ed o m
root=Tk()
b o ca dd
l .c
k ra hni mbe
label=Label(root,text="How are you?")
a i
label.pack() h a ec E
@ gm
C T B,
root.mainloop()
p & A 0 n al
d ee te ATL 36 ur
In [17]: h a ra M 18 jo
b po n, 00 a.
from tkinter import *
u
S or ho 91 bh
C yt : 8 su
root = Tk()
P ob l:
M ai
M
listbox = Listbox(root)
listbox.pack()
for i in rangeA(20):
listbox.insert(END, str(i))
root.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI1.slides.html 2/5
12/17/2018 GUI1 slides
In [22]: from tkinter import *
root = Tk()
listbox = Listbox(root)
listbox.pack(fill=BOTH, expand=1)
for i in range(20):
listbox.insert(END, str(i)) AI
,
DL
root.mainloop() ,
DS
In [23]: n er ML,
from tkinter import *
r ai C,
r ty l T ed o m
root = Tk()
b o ca dd
l .c
k ra hni mbe a i
listbox = Listbox(root)
h a ec E
@ gm
C T B,
listbox.pack(fill=X, expand=1)
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
for i in range(20):
h
u b po n, 00 a.
S or ho 91 bh
listbox.insert(END, str(i))
C yt : 8 su
P ob l:
root.mainloop()
M ai
M
In [24]: from tkinter import *
root = Tk()
listbox = Listbox(root)
listbox.pack(fill=Y, expand=1)
for i in range(20):
listbox.insert(END, str(i))
root.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI1.slides.html 3/5
12/17/2018 GUI1 slides
In [26]: from tkinter import *
root = Tk()
w = Label(root, text="Red", bg="red", fg="white")
w.pack()
w = Label(root, text="Green", bg="green", fg="black")
w.pack()
w = Label(root, text="Blue", bg="blue", fg="white")
A I
w.pack() ,
DL
,
root.mainloop() DS
n er ML,
In [27]: r ai C,
from tkinter import *
r ty l T ed o m
b o ca dd
l .c
root = Tk()
k ra hni mbe a i
h a ec E
@ gm
C T B,
& A 0 n al
w = Label(root, text="Red", bg="red", fg="white")
p
w.pack(fill=X)
d ee te ATL 36 ur
a ra M 18 jo
w = Label(root, text="Green", bg="green", fg="black")
h
u b po n, 00 a.
S or ho 91 bh
w.pack(fill=X)
C yt : 8 su
w = Label(root, text="Blue", bg="blue", fg="white")
P ob l:
w.pack(fill=X)
M ai
M
root.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI1.slides.html 4/5
12/17/2018 GUI1 slides
In [28]: from tkinter import *
root = Tk()
w = Label(root, text="Red", bg="red", fg="white")
w.pack(fill=Y)
w = Label(root, text="Green", bg="green", fg="black")
w.pack(fill=Y)
w = Label(root, text="Blue", bg="blue", fg="white")
A I
w.pack(fill=Y) ,
DL
,
root.mainloop() DS
n er ML,
In [29]: r ai C,
from tkinter import *
r ty l T ed o m
b o ca dd
l .c
root = Tk()
k ra hni mbe a i
h a ec E
@ gm
C T B,
& A 0 n al
w = Label(root, text="Red", bg="red", fg="white")
p
ee te ATL 36 ur
w.pack(side=LEFT)
d
a ra M 18 jo
w = Label(root, text="Green", bg="green", fg="black")
h
u b po n, 00 a.
S or ho 91 bh
w.pack(side=LEFT)
C yt : 8 su
w = Label(root, text="Blue", bg="blue", fg="white")
P ob l:
w.pack(side=LEFT)
M ai
M
root.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI1.slides.html 5/5
12/17/2018 GUI2 slides
In [ ]: #GUI ‐1
In [1]: from tkinter import *
def show_entry_fields():
print("First Name: %s\nLast Name: %s" % (e1.get(),
e2.get()))
master = Tk()
AI
,
Label(master, text="First Name").grid(row=0) DL
Label(master, text="Last Name").grid(row=1) S,
D
r ,
e1 = Entry(master) i ne ML
e2 = Entry(master) y T ra C,
t l ed o m
r
b o ca dd
l .c
e1.grid(row=0, column=1)
k ra hni mbe a i
e2.grid(row=1, column=1)
h a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
Button(master, text='Quit', command=master.quit).grid(row=3, col
d
a ra M 18 jo
umn=0, sticky=W, pady=4)
h
u b po n, 00 a.
S or ho 91 bh
Button(master, text='Show',
C yt : 8 su
command=show_entry_fields).grid(row=3, column=1, sticky=W,
pady=4)
P ob l:
M ai
M
mainloop( )
First Name: ss
Last Name: ww
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI2.slides.html 1/1
12/17/2018 GUI3 slides
In [ ]: #GUI ‐1
In [1]: from tkinter import *
def show_entry_fields():
print("First Name: %s\nLast Name: %s" % (e1.get(),
e2.get()))
e1.delete(0,END)
e2.delete(0,END)
AI
,
DL
master = Tk() ,
DS
Label(master, text="First Name").grid(row=0)
r , e L
in M
Label(master, text="Last Name").grid(row=1)
y T ra C,
t l ed o m
e1 = Entry(master) r
b o ca dd
l .c
e2 = Entry(master) ra ni be i
k h m a
e1.insert(10,"Subhadeep")
h a ec E
@ gm
C T B,
e2.insert(10,"Chakraborty")
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
e1.grid(row=0, column=1)
h
u b po n, 00 a.
S or ho 91 bh
e2.grid(row=1, column=1)
C yt : 8 su
P ob l:
Button(master, text='Quit', command=master.quit).grid(row=3, col
M ai
umn=0, sticky=W, pady=4)
M
Button(master, text='Show',
command=show_entry_fields).grid(row=3, column=1, sticky=W,
pady=4)
mainloop( )
First Name: Subhadeep
Last Name: Chakraborty
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI3.slides.html 1/1
12/17/2018 GUI4 slides
In [ ]: #GUI ‐1
In [2]: from tkinter import *
fields = 'Last Name', 'First Name', 'Job', 'Country'
def fetch(entries):
for entry in entries:
field = entry[0]
text = entry[1].get()
AI
,
print('%s: "%s"' % (field, text)) DL
,
DS
def makeform(root, fields):
n er ML,
entries = []
r ai C,
for field in fields: y
r t l T ed o m
row = Frame(root)
b o ca dd
l .c
k ra hni mbe
lab = Label(row, width=15, text=field, anchor='w')
a i
ent = Entry(row)
h a ec E
@ gm
C T B,
& A 0 n al
row.pack(side=TOP, fill=X, padx=5, pady=5)
p
ee te ATL 36 ur
lab.pack(side=LEFT)
d
a ra M 18 jo
ent.pack(side=RIGHT, expand=YES, fill=X)
h
u b po n, 00 a.
S or ho 91 bh
entries.append((field, ent))
C yt : 8 su
return entries
P ob l:
M ai
if __name__ == '__main__':
M
root = Tk()
ents = makeform(root, fields)
root.bind('<Return>', (lambda event, e=ents: fetch(e)))
b1 = Button(root, text='Show',command=(lambda e=ents:
fetch(e)))
b1.pack(side=LEFT, padx=5, pady=5)
b2 = Button(root, text='Quit', command=root.quit)
b2.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/GUI4.slides.html 1/1
12/17/2018 PandasComplete slides
In [2]: #Study of Pandas & Matplotlib Library
In [ ]: import pandas as pd # Data Importing
import matplotlib.pyplot as plt # Plotting
print("$$$$$$$$$$$$$$$$$$$$$ Pandas Library for Data Analysis
$$$$$$$$$$$$$$$$$$$$$")
In [5]: #Pandas Basics AI
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pandas Basics ~~~~
,
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") DL
,
DS
t = ('AA', '2012‐02‐01', 100, 10.2) #Creating Tuple
print(type(t))
n er ML,
ai C,
ts = pd.Series(t) #Converting Tuple to
r
Series
r ty l T ed o m
o ca dd
print("Printing Series, Converted from Tuple:")
b l .c
print(ts) k ra hni mbe a i
print(type(ts)) h
a ec E
@ gm
C T B,
p & A 0 n al
ee te ATL 36 ur
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Pandas Basics ~~~~~~~~
d
a ra M 18 jo
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
h
u b po n, 00 a.
S or ho 91 bh
<class 'tuple'>
C yt : 8 su
Printing Series, Converted from Tuple:
P ob l:
0 AA
M ai
1 2012‐02‐01 M
2 100
3 10.2
dtype: object
<class 'pandas.core.series.Series'>
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 1/14
12/17/2018 PandasComplete slides
In [12]: d = {'name' : 'ABCD', 'date' : '2018‐07‐11', 'shares' : 100, 'pr
ice' : 10200} #Creating Dictionary
ds = pd.Series(d)
#Converting Dictionary to Series
print("Printing Series, Converted from Dictionary:")
print(ds)
print("Printing Datatype of Series:")
print(ds.dtype)
AI
Printing Series, Converted from Dictionary: ,
name ABCD
DL
,
date 2018‐07‐11 DS
shares 100
n er ML,
price 10200
r ai C,
dtype: object
r ty l T ed o m
Printing Datatype of Series:
b o ca dd
l .c
object k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 2/14
12/17/2018 PandasComplete slides
In [22]: f = ['Mobile', '2018‐07‐24', 100, 32000]
#Creating List
fs = pd.Series(f, index = ['name', 'date', 'shares','price'])
#Converting List to Series
print("Printing Series, Converted from List:")
print(fs)
print("Printing Datatype of Series:")
print(fs.dtype)
print("printing with index:") AI
print(fs[0]) ,
DL
,
Printing Series, Converted from List: DS
name Mobile
n er ML,
date 2018‐07‐24
r ai C,
shares 100
r ty l T ed o m
price 32000 bo ca dd l .c
dtype: object k ra hni mbe a i
h a ec E
Printing Datatype of Series: @ gm
C T B,
object p & A 0 n al
ee te ATL 36 ur
printing with index:
d
h a ra M 18 jo
Mobile b
u p o n, 100 a.
S or ho 9 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 3/14
12/17/2018 PandasComplete slides
In [2]: df1 = pd.DataFrame({
'x': [12, 20, 28, 18, 29, 33, 24, 45, 45, 52, 51, 52, 55,
53, 55, 61, 64, 69, 72],
'y': [39, 36, 30, 52, 54, 46, 55, 59, 66,34,56 ,63, 58, 23,
14, 8, 19, 7, 24]
})
print(df1)
plt.plot(df1)
AI
x y ,
0 12 39
DL
,
1 20 36 DS
2 28 30
n er ML,
3 18 52
r ai C,
4 29 54
r ty l T ed o m
5 33 46 b o ca dd
l .c
6 24 55 k ra hni mbe a i
7 45 59 h a ec E
@ gm
C T B,
8 45 66 p & A 0 n al
9 52 34 d
ee te ATL 36 ur
h a ra M 18 jo
b po n, 00 a.
10 51 56
u
S or ho 91 bh
11 52 63
C yt : 8 su
12 55 58 P b l:
o
13 53 23 M ai
14 55 14
M
15 61 8
16 64 19
17 69 7
18 72 24
Out[2]: [<matplotlib.lines.Line2D at 0xcaba3ca4e0>,
<matplotlib.lines.Line2D at 0xcaba3ca6d8>]
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 4/14
12/17/2018 PandasComplete slides
AI
,
DL
In [3]:
,
df = pd.DataFrame({'Col‐1': [1, 2, 3, 4], DS
er L,
'Col‐2': ['ab', 'bc', 'cd', 'da'],
n M
ai ,
'Category': pd.Categorical(['a', 'b', 'c',
'd']) t y Tr d C m
r l e o
o ca dd .c
}, index=pd.Index(range(4), name='idxxxxx'))
b l
k ra hni mbe a i
In [4]: h a ec E
@ gm
print("Printing Data Frame:")
C T B,
p & A 0 n al
print(df)
d ee te ATL 36 ur
a ra M 18 jo
print("\nCreating Data types of the Frame:")
h
b po n, 00 a.
print(df.dtypes)
u
S or ho 91 bh
C yt : 8 su
Printing Data Frame:
P ob l:
Col‐1 Col‐2 Category
M ai
M
idxxxxx
0 1 ab a
1 2 bc b
2 3 cd c
3 4 da d
Creating Data types of the Frame:
Col‐1 int64
Col‐2 object
Category category
dtype: object
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 5/14
12/17/2018 PandasComplete slides
In [26]: print("Assigning New Coloumn:")
df['owner'] = 'Unknown'
print(df)
df['owner'] = ['A','B','C','D']
print(df)
Assigning New Coloumn:
Col‐1 Col‐2 Date Category owner
idx AI
0 1 ab 2018‐12‐31 a Unknown ,
1 2 bc 2019‐12‐31 b Unknown
DL
,
DS
2 3 cd 2020‐12‐31 c Unknown
er L,
3 4 da 2021‐12‐31 d Unknown
n M
ai ,
Col‐1 Col‐2 Date Category owner
y Tr d C
idx
t m
r l e o
o ca dd
0 1 ab 2018‐12‐31 a A
b l .c
ra hni mbe
1 2 bc 2019‐12‐31 b B
k a i
h a ec E
2 3 cd 2020‐12‐31 c C @ gm
C T B,
& A 0 n al
3 4 da 2021‐12‐31 d D
p
d ee te ATL 36 ur
h a ra M 18 jo
In [27]: b po n, 00 a.
print("Adding and Renewing Index Values:")
u
S or ho 91 bh
df.index = ['one', 'two', 'three','four']
C yt : 8 su
print(df) P b l:
o
M ai
M
Adding and Renewing Index Values:
Col‐1 Col‐2 Date Category owner
one 1 ab 2018‐12‐31 a A
two 2 bc 2019‐12‐31 b B
three 3 cd 2020‐12‐31 c C
four 4 da 2021‐12‐31 d D
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 6/14
12/17/2018 PandasComplete slides
In [28]: print("Setting Index with any of Coloumn Name:")
df = df.set_index(['Col‐2'])
print(df)
Setting Index with any of Coloumn Name:
Col‐1 Date Category owner
Col‐2
ab 1 2018‐12‐31 a A
bc 2 2019‐12‐31 b B AI
cd 3 2020‐12‐31 c C ,
da 4 2021‐12‐31 d D
DL
,
DS
n er ML,
r ai C,
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
h a ec E
@ gm
C T B,
p & A 0 n al
d ee te ATL 36 ur
h a ra M 18 jo
u b po n, 00 a.
S or ho 91 bh
C yt : 8 su
P ob l:
M ai
M
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 7/14
12/17/2018 PandasComplete slides
In [29]: print("Accessing Data By Coloumn Index:")
print(df['Col‐1'])
print("Accessing Data By Row Index:")
print(df.ix['ab'])
print("Accessing All Rows:")
print(df.ix[:, 'Col‐1'])
print("Access a Specific Element:")
print(df.ix[0, 'Col‐1'])
AI
Accessing Data By Coloumn Index: ,
Col‐2
DL
,
ab 1 DS
bc 2
n er ML,
cd 3
r ai C,
da 4
r ty l T ed o m
Name: Col‐1, dtype: int64 b o ca dd
l .c
ra hni mbe
Accessing Data By Row Index:
k a i
h a ec E
Col‐1 1 @ gm
C T B,
Date 2018‐12‐31 00:00:00
p & A 0 n al
ee te ATL 36 ur
Category a
d
h a ra M 18 jo
b po n, 00 a.
owner A
u
S or ho 91 bh
Name: ab, dtype: object
C yt : 8 su
Accessing All Rows:
P ob l:
Col‐2 M ai
ab 1
M
bc 2
cd 3
da 4
Name: Col‐1, dtype: int64
Access a Specific Element:
1
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 8/14
12/17/2018 PandasComplete slides
C:\Users\Subhadeep Chakrabort\Anaconda3\lib\site‐packages\ipy
kernel_launcher.py:4: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas‐docs/stable/indexing.html#ix‐
indexer‐is‐deprecated
after removing the cwd from sys.path.
AI
,
DL
C:\Users\Subhadeep Chakrabort\Anaconda3\lib\site‐packages\ipy
kernel_launcher.py:6: DeprecationWarning: ,
DS
.ix is deprecated. Please use
n er ML,
.loc for label based indexing or i
.iloc for positional indexing y T ra C,
t l ed o m
r
b o ca dd
l .c
k ra hni mbe
See the documentation here:
a i
h a ec E
@ gm
http://pandas.pydata.org/pandas‐docs/stable/indexing.html#ix‐
C T B,
indexer‐is‐deprecated
p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
C:\Users\Subhadeep Chakrabort\Anaconda3\lib\site‐packages\ipy
h
u b po n, 00 a.
S or ho 91 bh
kernel_launcher.py:8: DeprecationWarning:
C yt : 8 su
.ix is deprecated. Please use
P ob l:
.loc for label based indexing or
M ai
.iloc for positional indexing
M
See the documentation here:
http://pandas.pydata.org/pandas‐docs/stable/indexing.html#ix‐
indexer‐is‐deprecated
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 9/14
12/17/2018 PandasComplete slides
In [6]: #Reading File
print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Read File ~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~")
people = pd.read_csv('C:/Users/Subhadeep Chakrabort/Desktop/Pyth
on/Pandas/people.csv',encoding='utf‐8') #Reading .csv file
print("Printing Detailed Table: ")
x,y=people.shape
print(people.head(x))
#people['Name'] AI
#print(type(people['Name'])) ,
DL
agelist=people['Age'].tolist() ,
namelist=people['Age'].tolist() DS
#print(agelist) n er ML,
plt.plot(agelist) r ai C,
plt.gca() r ty l T ed o m
plt.grid() b o ca dd
l .c
plt.show() k ra hni mbe a i
h a ec E
@ gm
C T B,
& A 0 n al
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Read File ~~~~~~~~~~~~~~~~~~~
p
ee te ATL 36 ur
~~~~~~~~~~~~~~~~~~
d
h a ra M 18 jo
b po n, 00 a.
Printing Detailed Table:
u
S or ho 91 bh
Name Age ID Location Status
C yt : 8 su
0 ABC 23 ABC111 Kolkata NaN
P ob l:
1 DEF 26 DEF010 Delhi NaN
M ai
M
2 GHI 12 GHI223 Mumbai 12.0
3 JKL 29 JKL199 Pune 12.0
4 MNO 33 MNO243 Bangalore NaN
5 PQR 22 PQR443 Hyderabad NaN
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 10/14
12/17/2018 PandasComplete slides
AI
,
DL
In [7]:
,
print("Printing Selected coloumn: ") DS
er L,
pc = people['Age'] #
n M
Selecting coloumn i
y T ra C,
print(pc) t l ed o m
r
o ca dd
#print("Printing Selected coloumn: ")
b l .c
ra hni mbe i
pc1 = people['ID'] #
k a
Selecting coloumn h
a ec E
@ gm
C T B,
print(pc1) p & A 0 n al
d ee te ATL 36 ur
a ra M 18 jo
Printing Selected coloumn:
h
u b po n, 00 a.
S or ho 91 bh
0 23
8 su
1 26 C yt :
P ob l:
2 12 M ai
3 29 M
4 33
5 22
Name: Age, dtype: int64
0 ABC111
1 DEF010
2 GHI223
3 JKL199
4 MNO243
5 PQR443
Name: ID, dtype: object
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 11/14
12/17/2018 PandasComplete slides
In [8]: print("Printing Selected row: ")
pr=people.ix[1]
print(pr)
Printing Selected row:
C:\Users\Subhadeep Chakrabort\Anaconda3\lib\site‐packages\ipy
kernel_launcher.py:2: DeprecationWarning:
.ix is deprecated. Please use
AI
.loc for label based indexing or ,
.iloc for positional indexing DL
,
DS
See the documentation here:
n er ML,
http://pandas.pydata.org/pandas‐docs/stable/indexing.html#ix‐
r ai C,
indexer‐is‐deprecated
r ty l T ed o m
b o ca dd
l .c
k ra hni mbe a i
Name DEF a c E gm
h
C T B, e @
Age 26
p & A 0 n al
ID DEF010
ee te ATL 36 ur
d
a ra M 18 jo
Location Delhi
h
b po n, 00 a.
Status NaN
u
S or ho 91 bh
C yt : 8 su
Name: 1, dtype: object
P ob l:
M ai
In [9]: print("Technique‐1 to filter out Data: ")
M
print("Printing data for those who is above 26 years age:")
after26 = people[people['Age'] > 26]
print(after26)
Technique‐1 to filter out Data:
Printing data for those who is above 26 years age:
Name Age ID Location Status
3 JKL 29 JKL199 Pune 12.0
4 MNO 33 MNO243 Bangalore NaN
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 12/14
12/17/2018 PandasComplete slides
In [10]: print("Technique‐2 to filter out Data(sorting): ")
p=people
agebetw24to32 = p[ (p['Age']>=24) & (p['Age']<32) ]
agebetw24to32.head()
Technique‐2 to filter out Data(sorting):
Out[10]:
Name Age ID Location Status AI
,
1 DEF 26 DEF010 Delhi NaN DL
,
3 JKL 29 12.0 DS
JKL199 Pune
n er ML,
ai C,
In [11]: print("Check for NULL VALUE:") #If coloumn consists
r
ty l T ed
'NaN' or left blank, eligible for NULL
r o m
pn1 = people b o ca dd
l .c
k ra hni mbe a i
pn2 = people a ec E gm
h
C T B, @
pn1['Status'].isnull().head() #Check for Null
p & A 0 n al
d ee te ATL 36 ur
Check for NULL VALUE:
a ra M 18 jo
h
b po n, 00 a.
u
S or ho 91 bh
Out[11]: 0 True
C yt : 8 su
1 True
P b :
2 False Mo il
3 False Ma
4 True
Name: Status, dtype: bool
In [12]: pn2['Status'].notnull().head()
Out[12]: 0 False
1 False
2 True
3 True
4 False
Name: Status, dtype: bool
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 13/14
12/17/2018 PandasComplete slides
In [15]: people.Name
Out[15]: 0 ABC
1 DEF
2 GHI
3 JKL
4 MNO
5 PQR
Name: Name, dtype: object AI
,
In [20]:
DL
namelist=people['Name'].tolist() ,
print(namelist) DS
n er ML,
ai C,
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR']
r
r ty l T ed o m
In [21]: b
print(namelist.index('GHI'))
o ca dd
l .c
k ra hni mbe a i
2 h a ec E
@ gm
C T B,
p & A 0 n al
In [22]: d ee te ATL 36 ur
a ra M 18 jo
print(people.ix[namelist.index('GHI')])
h
u b po n, 00 a.
S or ho 91 bh
Name GHI
C yt : 8 su
Age 12
P ob l:
ID GHI223
M ai
M
Location Mumbai
Status 12
Name: 2, dtype: object
C:\Users\Subhadeep Chakrabort\Anaconda3\lib\site‐packages\ipy
kernel_launcher.py:1: DeprecationWarning:
.ix is deprecated. Please use
.loc for label based indexing or
.iloc for positional indexing
See the documentation here:
http://pandas.pydata.org/pandas‐docs/stable/indexing.html#ix‐
indexer‐is‐deprecated
"""Entry point for launching an IPython kernel.
file:///C:/Users/Subhadeep%20Chakrabort/Downloads/PandasComplete.slides.html 14/14