1636384053415python Mastery - E.BOOK
1636384053415python Mastery - E.BOOK
PYTHON
PROGRAMMING
MASTERY COURSE
MARKETED BY
DGTALGRAM
PYTHON
LECTURE 1
Today’s Agenda
An Introduction to Python
• Necessity Of Programming
• Important Features
Why Do We Need Programming ?
It is inspired by another
programming language called
ABC
Why was Python
created ?
It is a non-profit
organization devoted to the
growth and enhancement of
Python language
Their website is
http://www.python.org
What Python can do ?
GUI Application
Web Application
Data Analysis
Machine Learning
Raspberry Pi
Game Development
GUI In Python
It has grown in
popularity due to it’s
excellent libraries like
Numpy , Pandas etc
Machine Learning
In Python
Machine learning is
about making
predictions with data
The Raspberry Pi is a
low cost, credit-card
sized computer that
plugs into a computer
monitor or TV, and uses
a standard keyboard
and mouse.
It can do almost
everything a normal
desktop can do
Raspberry Pi
In Python
The coding on a
Raspberry Pi can be
performed using Python
Game Development
In Python
We can write
whole games in Python
using PyGame.
Popular games
developed in Python
are:
Bridge Commander
Civilization IV
Battlefield 2
Eve Online
Freedom Force
Why should
I learn Python ?
Simple
Dynamically Typed
Robust
Supports multiple programming paradigms
Compiled as well as Interpreted
Cross Platform
Extensible
Embedded
Extensive Library
Simple
IN C
#include <stdio.h>
int main(){
printf("Hello Bhopal!");
return 0;
}
IN JAVA
public class HelloWorld{
public static void main( String[] args ) {
System.out.println( "Hello Bhopal!" );
}
}
IN PYTHON
print('Hello Bhopal!')
Swap 2 Nos
IN C
int a=10,b=20,temp;
temp=a;
a=b;
b=temp;
IN JAVA
int a=10,b=20,temp;
temp=a;
a=b;
b=temp;
IN PYTHON
a,b=10,20
a,b=b,a
Add 2 Nos
IN C
#include <stdio.h>
int main(){
int a=10,b=20;
printf(“Sum is %d”,a+b);
return 0;
}
IN JAVA
public class HelloWorld{
public static void main( String[] args ) {
int a=10,b=20;
System.out.println( “Sum is “+(a+b));
}
}
IN PYTHON
a,b=10,20;
print(“Sum is”a+b)
Dynamically Typed
Dynamically Typed
IN C IN Python
int a;
a=10
a=10;
a=“Bhopal”; a=“Bhopal”
Robust
int arr[5];
int i;
for(i=0;i<=9;i++)
{
arr[i]=i+1;
}
Robust
• Version History
• In Python 2
print “Hello Bhopal”
• In Python 3
print(“Hello Bhopal”)
• In Python 2
5/2 →2
5/2.0→2.5
• In Python 3
5/2→ 2.5
Almost all the high level languages such as C, C++ translate the
source code into executable machine code with the help of
Compilers
C/C++
Source Code
Turbo
Compiler
Machine
Code Windows Linux
Difference Between Machine Code
And ByteCode
Bytecode
Source Code
Compiler
Byte Code
JVM JVM JVM
MacOS
Windows Ubuntu
Benefits And Drawbacks
Of ByteCode
But if you have windows 64 bit then scroll down and select
python 3.6.5 from the list
Downloading And
Installing Python
Open the downloads folder and run the file python-3.6.5.exe (if you
are on 32 bit) or python-3.6.5-amd64 (if you are on 64bit) by right
clicking it and selecting run as administrator
Downloading And
Installing Python
A. print
B. print()
C. Print()
D. Print
Correct Answer: A
QUIZ- Test Your Skills
A. print
B. print()
C. Print()
D. Print
Correct Answer: B
QUIZ- Test Your Skills
A. False
B. True
Correct Answer: B
QUIZ- Test Your Skills
A. Compiled Language
B. Interpreted Language
C. Both
D. None Of The Above
Correct Answer: C
QUIZ- Test Your Skills
A. True
B. False
Correct Answer: A
QUIZ- Test Your Skills
A. True
B. False
Correct Answer: B
QUIZ- Test Your Skills
A. Machine Code
B. Secret Code
C. Source Code
D. Byte Code
Correct Answer: D
QUIZ- Test Your Skills
8. What is CPython ?
A. A Python Library
B. Name Of Python Framework
C. A Python language Implementation
D. None Of The Above
Correct Answer: C
QUIZ- Test Your Skills
A. PVM
B. VM
C. JVM
D. Bytecode Converter
Correct Answer: A
QUIZ- Test Your Skills
A. True
B. False
Correct Answer: B
QUIZ- Test Your Skills
A. 31-Jan-2019
B. 1-Jan-2020
C. 31-Dec-2018
D. 31-Dec-2019
Correct Answer: B
QUIZ- Test Your Skills
A. CPython , PyPy, C
B. PyPy, C, CPython
C. CPython , C, PyPy
D. C,PyPy,CPython
Correct Answer: D
QUIZ- Test Your Skills
A. CPython
B. PyPy
C. Jython
D. IronPython
Correct Answer: B
QUIZ- Test Your Skills
A. 2.0
B. 2.5
C. 2
D. None Of The Above
Correct Answer: B
QUIZ- Test Your Skills
A. Python Rocks
B. Python
C. Syntax Error
D. None Of The Above
Correct Answer: C
QUIZ- Test Your Skills
A. PyCharm
B. Cutie Pie
C. Spyder
D. Visual Studio Code
Correct Answer: B
QUIZ- Test Your Skills
Correct Answer: A
QUIZ- Test Your Skills
A. True
B. False
Correct Answer: B
Today’s Agenda
• Interactive Mode
• Script Mode
Two Ways Of Interacting
With Python
• print(“Hello Bhopal”)
Open notepad and type the code as shown in the next slide in
the file.
The Script Mode
print("Hello User")
print("Python Rocks")
The Script Mode
Remember the file can have any name but the extension must
compulsorily be .py
python firstcode.py
• Introduction TO IDLE
• Built In Functions
1.
print("Hello User",end="\t")
print("Python Rocks")
2.
print("Hello User",end="\b")
print("Python Rocks")
Functions Defined
In Modules
Just type the commands, hit enter and it will display the
result.
Using IDLE
Using IDLE’s Editor Window
• Syntax Error
• Runtime Error
Syntax Error
• What is an identifier ?
• Identifier is the name given to entities like class, functions,
variables , modules and any other object in Python.
Data Types
• Numeric Types
• Numeric Types
• Boolean Type
• Sequence Types
• Set Types
• Mapping Type
• None Type
complex bytes
bytearray
tuple
range
Some Very Important Points
Another important
observation we can
make is that in Python
all the data types are
implementted as
classes and all
variables are object
Some Very Important Points
a=10
b=256
c=-4
print(a)
print(b)
print(c)
Output:
10
256
-4
Numeric Types In Python
3. As octal number(base 8)
3. Example:
a=25
Numeric Types In Python
Syntax : bin(a)
Some Examples:
1. Converting decimal base to binary
Some Examples:
Syntax : oct(a)
Some Examples:
1. Converting decimal base to octal
Some Examples:
Syntax : hex(a)
Some Examples:
1. Converting decimal base to hexadecimal
Some Examples:
• For example:
NONE!
Both will give error.
Correct way is to use either triple single quotes or triple
double quotes or escape sequence character \
msg=' ' 'Let\'s learn "Python" ' ' '
OR
msg='Let\'s learn "Python" '
Some Important Points
About Strings
Some Important Points
About Strings
Some Important Points
About Strings
• Concatenating Strings
• Type Conversion
String Concatenation
• Example: • Example:
s1=“Good”
s1=“Good”
s2=“Morning”
s2=“Morning” s3=s1+” “+s2
s3=s1+s2 print(s3)
print(s3)
• Output:
• Output: Good Morning
GoodMorning
The Slicing Operator
• Example: • Example:
s=“Industry” s=“Welcome”
print(s[2:6]) print(s[3:6])
• Output: • Output:
dust com
The Slicing Operator
• Example: • Example:
s=“Mumbai” s=“Mumbai”
print(s[0:3]) print(s[0:10])
• Output: • Output:
Mum Mumbai
The Slicing Operator
• Example: • Example:
s=“Python” s=“Python”
print(s[2:2]) print(s[6:10])
• Output: • Output:
The Slicing Operator
• Example: • Example:
s=“welcome” s=“welcome”
print(s[1:]) print(s[:3])
• Output: • Output:
elcome wel
The Slicing Operator
• Example: • Example:
s=“welcome” s=“welcome”
print(s[:]) print(s[])
• Output: • Output:
welcome Syntax Error
The Slicing Operator
• Example: • Example:
s=“welcome” s=“welcome”
print(s[-4:-1]) print(s[-1:-4])
• Output: • Output:
com
Using Step Value
s[begin:end:step]
• Output: • Output:
dust ds
• Can also be
written as :
s=“Industry”
print(s[2:6:1])
• Output:
dust
Three Very Useful Functions
Of String Data Type
• len()
• lower()
• upper()
Three Very Useful Functions
Of String Data Type
• Syntax: s.upper()
Comparing Strings
Suppose we have str1 as " Indore " and str2 as " India" and
we write print(str1>str2) , then Python will print True.
Following is the explanation
Now the first two characters from str1 and str2 ( I and I ) are
compared.
Because they are also equal, the third two characters ( d and d ) are
compared.
Since they also are equal , the fourth pair (o and i) is compared and
there we get a mismatch .
• Syntax: int(value)
int(2.3)
Output: int() cannot
convert complex
2 type to int type
int(3+4j)
Output:
TypeError: Can’t convert complex to int
int(False)
Output:
0
int(True)
Output:
1
int( ) Examples
Output:
ValueError: Invalid literal for int()
The float( ) Function
• Syntax: float(value)
float(25)
Output: float() cannot
convert complex
25.0 type to float type
float(3+4j)
Output:
TypeError: Can’t convert complex to float
float(False)
Output:
0.0
float(True)
Output:
1.0
float( ) Examples
float(“25”)
float(“twenty”)
Output: Output:
25.0 ValueError:Could not convert
float(“2.5”) string to float
Output:
2.5
float(“1010”) float() cannot
Output: accept binary
values as string . It
1010.0 only accept strings
float (“0b1010”) with base 10 only
Output:
ValueError:Could not convert string to float
The complex( ) Function
• Syntax: complex(value)
complex(25)
Output:
(25+0j)
complex(2.5)
Output:
(2.5+0j)
complex(True)
Output:
(1+0j)
complex(False)
Output:
0j
complex( ) Examples
complex(“25”)
complex(“twenty”)
Output: Output:
(25+0j) ValueError: complex() arg is
complex(“2.5”) a malformed string
Output:
(2.5+0j)
complex(“1010”) complex() cannot
Output: accept binary
values as string . It
(1010+0j) only accept strings
complex (“0b1010”) with base 10 only
Output:
ValueError: complex() arg is a malformed string
The bool ( ) Function
• Syntax: bool(value)
bool(1)
Output:
True
bool(5)
Output:
True
bool(0)
Output:
False
bool(0.0)
Output:
False
bool( ) Examples
bool(0.1)
Output:
True
bool(0b101)
Output:
True
bool(0b0000) bool() returns True
Output: if any of the real or
imaginary part is
False non zero . If both
bool(2+3j) are zero it returns
False
Output:
True
bool( ) Examples
bool(0+1j) bool(“twenty”)
Output: Output:
True True
bool(0+0j) bool(' ')
Output: Output:
True
False
bool('')
Output: bool() returns
False for empty
False Strings otherwise it
bool('A') returns True
Output:
True
PYTHON
LECTURE 8
Today’s Agenda
• The is Operator
Understanding Python
Variables
a=10
a=20
a=30
1. Garbage Block
3. Reference Counting
The Garbage Block
• So in our example
a=10
a=20
a=30
• ADVANTAGE:
• DISADVANTAGE:
a=42
b=42
• Answer: Only 1
• By using is operator
The id( ) Function
• Example: • Example:
a= -5 a=256
b=-5 b=256
print(a is b) print(a is b)
• Output: • Output:
True True
An Important Twist !
• Example: • Example:
a= -6 a=257
b=-6 b=257
print(a is b) print(a is b)
• Output: • Output:
False False
Beyond this range Python creates new objects even for the same
value
Another Important Twist !
• Example: • Example:
a= “Bhopal” a=False
b=“Bhopal” b=False
print(a is b) print(a is b)
• Output: • Output:
True True
Yet Another Important Twist !
• Example: • Example:
a= 1.0 a=(2+3j)
b=1.0 b=(4+5j)
print(a is b) print(a is b)
• Output: • Output:
False False
• For example:
This line gets
a=10 commented out
#a=a+1 and is not
print(a) executed
Output:
10
Official Way Of
Multi Line Comments
#a=a+1
#b=b+5
#c=c+10
• We can find it at
https://www.python.org/dev/peps/pep-0008/
Why Is PEP Needed ?
• For example:
PI=3.14
MAX_MARKS=100
• Example: • Example:
a=“Good”
a=“Good”
b=10
b=“Morning” print(a+b)
print(a+b)
• Output:
• Output:
GoodMorning
TypeError
The print( ) Function
• Example: • Example:
a=“Good”
a=“Good”
b=10
b=“Morning” print(a,b)
print(a,b)
• Output:
• Output: Good 10
Good Morning
• Example: • Example:
a=“Good”
a=10
b=10
b=20 print(a,b)
print(a,b)
• Output:
• Output:
10 20
Good 10
The print( ) Function
• Example:
name=“Sachin”
print(“My name is“, name)
• Output:
My name is Sachin
The print( ) Function
• Example:
age=32
print(“My age is“, age)
• Output:
My age is 32
The print( ) Function
• Example:
name=“Sachin”
age=32
print(“My name is“, name,”and my age is”,age)
• Output:
My name is Sachin and my age is 32
How Is Space
Getting Generated?
• So the statement :
• print(“Good”,”Morning”)
• Example: • Example:
hh=10
a=10
mm=30
b=20 ss=45
print(a,b,sep=“#”)
print(hh,mm,ss,sep=“:”)
• Output:
• Output:
10:30:45
10#20
PYTHON
LECTURE 10
QUIZ 2- Test Your Skills
A. 31 characters
B. 63 characters
C. 79 characters
D. none of the mentioned
Correct Answer: D
QUIZ 2- Test Your Skills
A. Class
B. List
C. Str
D. Tuple
Correct Answer: A
QUIZ 2- Test Your Skills
A. hel
B. he
C. Lo
D. olleh
Correct Answer: B
QUIZ- Test Your Skills
A. int
B. float
C. bool
D. dict
Correct Answer: A
QUIZ- Test Your Skills
Correct Answer: C
QUIZ- Test Your Skills
A. k = 2 + 3j
B. k = complex(2)
C. k = 2 + 3I
D. k = 2 + 3J
Correct Answer: C
QUIZ- Test Your Skills
A. k = 0b101
B. k= 0x4f5
C. k = 19023
D. k = 0o3964
Correct Answer: D
QUIZ- Test Your Skills
A. False
B. True
C. SyntaxError
D. 0
Correct Answer: B
QUIZ- Test Your Skills
A. List
B. Tuple
C. Both
D. None
Correct Answer: A
QUIZ- Test Your Skills
A. Yes
B. No
Correct Answer: A
QUIZ- Test Your Skills
A. Yes
B. No
Correct Answer: B
QUIZ- Test Your Skills
A. Yes
B. No
Correct Answer:B
QUIZ- Test Your Skills
A. include math
B. import math
C. #include<math.h>
D. using math
Correct Answer: B
QUIZ- Test Your Skills
A. chr
B. char
C. str
D. None Of The Above
Correct Answer: D
QUIZ- Test Your Skills
Correct Answer: C
Today’s Agenda
• Operators In Python
• Types Of Operators
• Arithmetic Operators
• Arithmetic Operators
• Relational or Comparison Operators
• Logical Operators
• Assignment Operator
• Bitwise Operators
• Identity Operators
• Membership Operators
Arithmetic Operators
In Python
+
(Arithmetic Addition)
-
(Subtraction)
*
(Arithmetic Multiplication)
/
(Float Division)
%
(Modulo Division)
//
(Floor Division)
**
(Power or Exponentiation)
The 5 Basic Arithmetic
Operators
mymath.py
a=10
b=4
print("sum of",a,"and",b,"is",a+b)
print("diff of",a,"and",b,"is",a-b)
print("prod of",a,"and",b,"is",a*b)
print("div of",a,"and",b,"is",a/b)
print("rem of",a,“and",b,"is",a%b)
The 5 Basic Arithmetic
Operators
The Output:
Two Special
Operators // and **
• Example: • Example:
a=10.0
a=10
b=4
b=4 print(a//b)
print(a//b)
• Output:
• Output: 2.0
2
• Example: • Example:
a=97
a=97
b=10.0
b=10 print(a//b)
print(a//b)
• Output:
• Output: 9.0
9
The Floor Division Operator
• Example: • Example:
a=19
a=-10
b=-2
b=4 print(a//b)
print(a//b)
• Output:
• Output: -10
-3
The Floor Division Operator
• Example: • Example:
a=-19
a=-10
b=-2
b=-4 print(a//b)
print(a//b)
• Output:
• Output: 9
2
An Important Point
• Example: • Example:
a=10
a=10
b=0.0
b=0 print(a/b)
print(a/b)
• Output:
• Output: ZeroDivisionError
ZeroDivisionError
Division By 0
• Example: • Example:
a=10
a=10
b=0.0
b=0 print(a//b)
print(a//b)
• Output:
• Output: ZeroDivisionError
ZeroDivisionError
Division By 0
• Example: • Example:
a=10
a=10
b=0.0
b=0 print(a%b)
print(a%b)
• Output:
• Output: ZeroDivisionError
ZeroDivisionError
The power (**)Operator
• For example:
a=10
b=3
print(a**b)
• Output:
1000
Double Role Of The
Operator +
• For example:
a=10
a=“Good”
b=5 b=“Evening”
print(a+b) print(a+b)
Output: Output:
GoodEvening
15
Double Role Of The
Operator +
• Example: • Example:
a=“Good”
a=“Good”
b=“10”
b=10 print(a+b)
print(a+b)
• Output:
• Output: Good10
TypeError
Double Role Of The
Operator *
• For example:
a=10 a=“Sachin”
b=5 b=3
print(a*b) print(a*b)
Output: Output:
50 SachinSachinSachin
The * Operator
• Example: • Example:
a=“Sachin”
a=5
b=3.0
b=4.0 print(a*b)
print(a*b)
• Output:
• Output: Type Error :
20.0 Can’t multiply
by non int
The * Operator
• Example: • Example:
a=“Sachin”
a=“Sachin”
b=“Kapoor”
b=3 print(a*b)
print(b*a)
• Output:
• Output: Type Error :
SachinSachinSachin Can’t multiply
by non int
PYTHON
LECTURE 11
Today’s Agenda
• Operators In Python
• Relational Operators
myrelop.py
a=10
b=4
print("a=",a,"b=",b)
print("a > b",a>b)
print("a < b",a<b)
print("a==b",a==b)
print("a!=b",a!=b)
print("a>=b",a>=b)
print("a<=b",a<=b)
The 6 Basic Relational
Operators
The Output:
Relational Operators
With Strings
myrelop2.py
a="Ramesh"
b="Rajesh"
print("a=",a,"b=",b)
print("a > b",a>b)
print("a < b",a<b)
print("a==b",a==b)
print("a!=b",a!=b)
print("a>=b",a>=b)
print("a<=b",a<=b)
Relational Operators
With Strings
The Output:
Relational Operators
With Strings
Example:
ord(‘A’)
65
ord(‘m’)
109
ord(‘j’)
106
Relational Operators
With Strings
myrelop4.py
a= "BHOPAL"
b= "bhopal"
print("a=",a,"b=",b)
print("a > b",a>b)
print("a < b",a<b)
print("a==b",a==b)
print("a!=b",a!=b)
print("a>=b",a>=b)
print("a<=b",a<=b)
Relational Operators
With Strings
The Output:
Will This Code Run ?
• Example: • Example:
print(5<6>7)
print(7>6>5)
• Output:
• Output:
False
True
Cascading Of
Relational Operators
• Example: • Example:
print(5<6<7)
print(5>6>7)
• Output:
• Output:
True
False
Special Behavior Of
== And !=
• Example: • Example:
print(10==20)
print(10==10)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(10==True)
print(10==“10”)
• Output:
• Output:
False
False
Special Behavior Of
== And !=
• Example: • Example:
print(“A”==“A”)
print(1==True)
• Output:
• Output:
True
True
Special Behavior Of
== And !=
• Example: • Example:
print(“A”==65)
print(“A”==“65”)
• Output:
• Output:
False
False
Special Behavior Of
== And !=
• Example: • Example:
print(15==15.01)
print(15==15.0)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(0 != False)
print(15!=“15”)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(False != 0.0)
print(False!=True)
• Output:
• Output:
False
True
Special Behavior Of
== And !=
• Example: • Example:
print(2+5j!= 2)
print(2+5j==2+5j)
• Output:
• Output:
True
True
PYTHON
LECTURE 12
Today’s Agenda
• Operators In Python
• Logical Operators
Operator Meaning
• Example: • Example:
5 and 0
5 and 6
• Output:
• Output:
0
6
Logical Operators
On Non Boolean Types
• Example: • Example:
6 and 0
0 and 10
• Output:
• Output:
0
0
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Sachin’ and 0
‘Sachin’ and 10
• Output:
• Output:
0
10
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Indore’ and ‘Bhopal’ ‘Bhopal’ and ‘Indore’
• Output: • Output:
Bhopal Indore
Logical Operators
On Non Boolean Types
• Example: • Example:
0 and 10/0 10/0 and 0
• Output: • Output:
0 ZeroDivisionEror
Logical Operators
On Non Boolean Types
• Example: • Example:
5 or 0
5 or 6
• Output:
• Output:
5
5
Logical Operators
On Non Boolean Types
• Example: • Example:
6 or 0
0 or 10
• Output:
• Output:
6
10
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Sachin’ or 0
‘Sachin’ or 10
• Output:
• Output:
Sachin
Sachin
Logical Operators
On Non Boolean Types
• Example: • Example:
‘Indore’ or ‘Bhopal’ ‘Bhopal’ or ‘Indore’
• Output: • Output:
Indore Bhopal
Logical Operators
On Non Boolean Types
• Example: • Example:
0 or 10/0 10/0 or 0
• Output: • Output:
ZeroDivisionError ZeroDivisionEror
Logical Operators
On Non Boolean Types
• Example: • Example:
not 5 not 0
• Output: • Output:
False True
Logical Operators
On Non Boolean Types
• Example: • Example:
not ‘Sachin’ not ‘’
• Output: • Output:
False True
PYTHON
LECTURE 13
Today’s Agenda
• Operators In Python
• Introduction To Bitwise Operators
Operator Meaning
| Bitwise OR
^ Bitwise XOR
0&1 0
1&0 0
1&1 1
Examples Of & Operator
Explanation: Explanation:
Binary of 2 : 0010 Binary of 7 : 0111
Binary of 3: 0011 Binary of 9: 1001
Bitwise & : 0010 Bitwise & : 0001
Final Result: 2 Final Result: 1
Examples Of & Operator
a=15 a=8
b=1 b=10
c=a & b c=a & b
print(c) print(c)
Output:
Output:
8
1
Explanation: Explanation:
Binary of 15 : 1111 Binary of 8 : 1000
Binary of 1: 0001 Binary of 10: 1010
Bitwise & : 0001 Bitwise & : 1000
Final Result: 1 Final Result: 8
Examples Of & Operator
a=True a=True
b=False b=True
c=a & b c=a & b
print(c) print(c)
Output:
Output:
True
False
Explanation: Explanation:
Binary of True(1) : 0001 Binary of True(1) : 0001
Binary of False(0): 0000 Binary of True(1): 0001
Bitwise & : 0000 Bitwise & : 0001
Final Result: False Final Result: True
Bitwise OR Operator
Or operator Result
0|0 0
0|1 1
1|0 1
1|1 1
Examples Of | Operator
a=2 a=7
b=3 b=9
c=a | b c=a | b
print(c) print(c)
Output:
Output:
15
3
Explanation: Explanation:
Binary of 2 : 0010 Binary of 7 : 0111
Binary of 3: 0011 Binary of 9: 1001
Bitwise | : 0011 Bitwise | : 1111
Final Result: 3 Final Result: 15
Examples Of | Operator
a=True a=True
b=False b=True
c=a|b c=a|b
print(c) print(c)
Output:
Output:
True
True
Explanation: Explanation:
Binary of 1 : 0001 Binary of 1 : 0001
Binary of 0: 0000 Binary of 1: 0001
Bitwise | : 0001 Bitwise | : 0001
Final Result: True Final Result: True
Bitwise XOR Operator
0^1 1
1^0 1
1^1 0
Examples Of ^Operator
a=2 a=7
b=3 b=9
c=a^b c=a^b
print(c) print(c)
Output:
Output:
14
1
Explanation: Explanation:
Binary of 2 : 0010 Binary of 7 : 0111
Binary of 3: 0011 Binary of 9: 1001
Bitwise ^ : 0001 Bitwise ^ : 1110
Final Result: 1 Final Result: 14
Examples Of ^ Operator
a=True a=True
b=False b=True
c=a^b c=a^b
print(c) print(c)
Output:
Output:
False
True
Explanation: Explanation:
Binary of 1 : 0001 Binary of 1 : 0001
Binary of 0: 0000 Binary of 1: 0001
Bitwise ^ : 0001 Bitwise ^ : 0000
Final Result: True Final Result: False
Bitwise
One’s Complement Operator
Example:
a=2
b=~a
print( b )
Output:
-3
Explanation
Binary for 2 is 00000010. Its one’s complement is 11111101.
This is binary for -3.
Bitwise
Left Shift Operator
1. Denoted by <<
2. Shifts the bits of the number towards left by the specified
number of places.
3. Adds 0 to the empty least-significant places
Example:
a=10
b=a<<1
print( b )
Output:
20
Explanation
Binary of 2 : 0010
Left Shift by 1: 00100
Result : 20
New bit
Examples Of
Left Shift Operator
a=15 a=7
b=3 b=2
c=a<<b c=a<<b
print(c) print(c)
Output:
Output:
28
120
Explanation: Explanation:
Binary of 15 : 1111 Binary of 7 : 0111
Left Shift by 3: 1111000 Left Shift by 2: 11100
Final Result: 120 Final Result: 28
Examples Of
Left Shift Operator
a=True a=False
b=a<<1 b=a<<1
print(b) print(b)
Output: Output:
0
2
Explanation: Explanation:
Binary of 1 : 0001 Binary of 0 : 0000
Left Shift By 1 : 0010 Left Shift By 1 : 0000
Final Result: 2 Final Result: 0
Bitwise
Right Shift Operator
1. Denoted by >>
2. Shifts the bits of the number towards right by the specified
number of places.
3. Adds 0 to the empty most-significant places
Example:
a=10
b=a>>1
print( b )
Output:
5
Explanation
Binary of 10 : 1010
Right Shift by 1: 0101
Result : 5
New bit
Examples Of
Right Shift Operator
a=15 a=7
b=3 b=2
c=a>>b c=a>>b
print(c) print(c)
Output:
Output:
1
1
Explanation: Explanation:
Binary of 15 : 1111 Binary of 7 : 0111
Right Shift by 3: 0001 Right Shift by 2: 0001
Final Result: 1 Final Result: 1
Examples Of
Right Shift Operator
a=True a=False
b=a>>1 b=a>>1
print(b) print(b)
Output: Output:
0
0
Explanation: Explanation:
Binary of 1 : 0001 Binary of 0 : 0000
Right Shift By 1 : 0000 Right Shift By 1 : 0000
Final Result: 0 Final Result: 0
PYTHON
LECTURE 14
Today’s Agenda
• Operators In Python
• Assignment Operators
• Compound Operators
• Identity Operators
• Membership Operators
Assignment Operators
In Python
For example:
a=10
Assignment Operators
In Python
a,b,c=10,20
print(a,b,c)
Output:
ValueError : Not enough values to unpack
a,b,c=10,20,30,40
print(a,b,c)
Output:
ValueError : Too many values to unpack
Compound Assignment
Operators
+= x+=5 x=x+5
-= x-=5 x=x-5
*= x*=5 x=x*5
/= x/=5 x=x/5
%= x%=5 x=x%5
//= x//=5 x=x//5
**= x**=5 x=x**5
&= x&=5 x=x&5
!= x!=5 x=x!5
^= x^=5 x=x^5
>>= x>>=5 x=x>>5
<<= x<<=5 x=x<<5
Guess The Output
a=10
Conclusion:
print(++a) Python does not has any
increment operator like ++.
Output:
10 Rather it is solved as
+(+x) i.e +(+10) which is 10
a=10
Conclusion:
print(--a) Python does not has any
decrement operator like --.
Output:
10 Rather it is solved as
-(-x) i.e -(-10) which is 10
a=10
Try to figure out yourself
print(+++++a) the reason for these outputs
Output:
10
a=10
print(-----a)
Output:
-10
Identity Operators
a=2 a=2
b=3 b=2
c=a is b c=a is b
print(c) print(c)
Output:
Output:
True
False
Explanation: Explanation:
Since a and b are pointing Since a and b are pointing
to 2 different objects, so to same objects, so
the operator is returns the operator is returns
False True
Examples Of is Operator
a=2 a=2
b=type(a) is int b=type(a) is float
print(b) print(b)
Output: Output:
False
True
Explanation: Explanation:
type(a) is int evaluates type(a) is float evaluates
to True because 2 is to False because 2 is not a
indeed an integer number. float number.
Examples Of is not Operator
a=“Delhi” a=“Delhi”
b=“Delhi” b=“delhi”
c=a is not b c=a is not b
print(c) print(c)
Output:
Output:
True
False
Explanation: Explanation:
Since a and b are pointing Since a and b are pointing
to the same object, so to 2 differentobjects, so
the operator is not returns the operator is not returns
False True
Membership Operators
in
not in
Membership Operators
a=“Welcome” a=“Welcome”
b=“om” b=“mom”
print(b in a) print(b in a)
Output:
Output:
False
True
Examples Of not in Operator
primes=[2,3,5,7,11]
primes=[2,3,5,7,11]
x=5
x=4 print(x not in primes)
print(x not in primes)
Output: Output:
False
True
PYTHON
LECTURE 15
Today’s Agenda
Syntax:
input([prompt])
Output:
Example 2
(Using input( ) With Message)
Output:
Example 3
(Using input( ) With Message)
Output:
Accepting Integer Input
a=input("enter a number\n")
b=a+1
print(b)
Output:
Accepting Integer Input
a=input("enter a number\n")
b=int(a)+1
print(b)
OR
a=int(input("enter a number\n")
b=a+1
print(b)
Accepting Float And Bool
Example:
s=input("enter your percentage\n")
per=float(s)
print(per)
OR
s=input(“Delete the file ?(yes-True,no-False)")
ans=bool(s)
print(ans)
Exercise
Code:
import math
radius=float(input("Enter radius:"))
area=math.pi*math.pow(radius,2)
circum=math.tau*radius
print("Area is",area)
print("Circumference is",circum)
Second Way To Import
A Module
Syntax:
import modname as newname
Code
import platform as p
print(p.system())
Second Way Of Writing Previous
Code Using math Module
Code:
import math as m
radius=float(input("Enter radius:"))
area=m.pi*m.pow(radius,2)
circum=m.tau*radius
print("Area is",area)
print("Circumference is",circum)
Third Way To Import
A Module
Syntax:
from modname import name1[, name2[, ... nameN]]
Code
from sys import getsizeof
a=10
b=“hello”
print(getsizeof(a))
print(getsizeof(b))
Third Way Of Writing Previous
Code Using math Module
Code:
from math import pi,tau,pow
radius=float(input("Enter radius:"))
area=pi*pow(radius,2)
circum=tau*radius
print("Area is",area)
print("Circumference is",circum)
Fourth Way To Import
A Module
Syntax:
from modname import *
Code
from sys import *
a=10
b=“hello”
print(getsizeof(a))
print(getsizeof(b))
Fourth Way Of Writing Previous
Code Using math Module
Code:
from math import *
radius=float(input("Enter radius:"))
area=pi*pow(radius,2)
circum=tau*radius
print("Area is",area)
print("Circumference is",circum)
How To List
All Members Of A Module
Code:
s=input("Enter 2 numbers:")
a,b=s.split()
print("First number is",a);
print("Second number is",b)
c=int(a)+int(b)
print("Their sum is",c)
Accepting Multiple
Values Separated With ,
Code:
s=input("Enter 2 numbers separated with comma:")
a,b=s.split(",")
print("First number is",a);
print("Second number is",b)
c=int(a)+int(b)
print("Their sum is",c)
Accepting Different Values
In One Line
Code:
s=input("Enter roll no,name and per:")
roll,name,per=s.split()
print("Roll no is",roll)
print("Name is",name)
print("Per is",per)
PYTHON
LECTURE 16
Today’s Agenda
Syntax:
eval(expression)
• Example: • Example:
x = eval(‘2+3*6’)
x = eval(’2+3’)
print(x)
print(x)
• Output:
• Output:
5
20
Examples
• Example: • Example:
from math import sqrt
eval(‘print(15)’)
x = eval(‘sqrt(4)’)
print(x)
• Output: • Output:
15 2.0
Using eval( ) For
Type Conversion
Example:
Same Example
x = eval(‘2.5’) Without eval( ):
print(x) x = ‘2.5’
print(type(x)) print(x)
print(type(x))
Output: Output:
2.5 2.5
<class ‘float’> <class ‘str’>
Using eval( ) With input( )
Code:
age = eval(input("Enter your age "))
age=age+10
print("After 10 years , you will be ",age, "years old")
Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Guess The Output
• Example:
a=eval(input("Type something:"))
print(a)
print(type(a))
• Output:
Command Line Arguments
For example:
python demo.py 10 20 30
The name of the program is passed as the first argument which is stored
at the 0th index in argv
Example
Output:
Accessing Individual Values
Code:
from sys import argv
print(argv[0])
print(argv[1])
Output:
Guess The Output
Output:
cmdarg.py
IndexError: list index out of range
Obtaining Number Of
Arguments Passed
Code:
from sys import argv
n=len(argv)
print("You have passed",n-1,"arguments")
Output:
Using Slicing Operator
Output:
Guess The Output
Output:
[]
Guess The Output
Code: addnos.py
from sys import argv
print(“First num is“,argv[1])
print(“Sec num is“,argv[2])
print(“Their sum is”,argv[1]+argv[2])
Code:
from sys import argv
a=eval(argv[1])
b=eval(argv[2])
print("Nos are",a,"and",b)
print("Their sum is",a+b)
Guess The Output
Code:
from sys import argv
print(“Hello”,argv[1])
Output:
Hello Sachin Kapoor
Guess The Output
Code:
from sys import argv
print(“Hello”,argv[1])
Syntax:
print(“format specifier” %(variable list))
Example:
a=10
print(“value of a is %d “ %(a))
Example:
a=10
msg=“Welcome”
c=1.5
print(“values are %d , %s,%f“ %(a,msg,c))
Output:
Values are 10, Welcome, 1,500000 Number of format
specifiers must
exactly match
with the number
of vlaues in the
parenthesis
Key Points About
Format Specifiers
a=10
print(“%s” %a)
Output:
10
a=10
print(“%f” %a)
Output:
10.000000
Examples
a=10.6 a=10.6
print(“%f” %a) print(“%d” %a)
Output:
Output:
10
10.600000
a=10.6 a=10.6
print(“%s” %a)
print(“%.2f” %a) Output:
Output: 10.6
10.60
Examples
a=True a=True
print(“%s” %a) print(“%f” %a)
Output:
Output:
1.000000
True
a=True
print(“%d” %a)
Output:
1
Examples
a=“Bhopal” a=“Bhopal”
print(“%s” %a) print(“%f” %a)
Output:
Output:
TypeError
Bhopal
a=“Bhopal”
print(“%d” %a)
Output:
TypeError: number required , not str
Using The Function format()
Syntax:
print(“string with { }”.format(values))
Example
name=“Sachin”
age=36
print(“My name is {0} and my age is {1}”.format(name,age))
Output:
My name is Sachin and my age is 36
Examples
name=“Sachin”
age=36
print(“My name is {1} and my age is{0}”.format(age,name))
Output:
My name is Sachin and my age is 36
Using The Function format()
Example
name=“Sachin”
age=36
print(“My name is {n} and my age is
{a}”.format(n=name,a=age))
Output:
My name is Sachin and my age is 36
PYTHON
LECTURE 17
Today’s Agenda
• Concept of Indentation
Syntax:
if (expression):
statement1
statement2
.
.
statement..n
A code block starts with indentation and ends with the first unindented line.
The colon after if( ) condition is important and is a part of the syntax. However parenthesis
with condition is optional
Exercise
Solution 1:
a=eval(input("Enter a number:"))
if(a%2==0):
If the body of if( )
print("No is even") statement
if(a%2!=0): contains only one
statement , then
print("No is odd") we can write it just
after if( )
statement also
Solution 2:
if(a%2==0):print("No is even")
if(a%2!=0): print("No is odd")
What About Multiple Lines ?
OR
Solution 1:
if(a%2==0):
print("No is even")
print(“Hello”)
if(a%2!=0):
print("No is odd")
print(“Hi”)
Solution 2:
if(a%2==0): print("No is even");print(“Hello”)
if(a%2!=0): print("No is odd");print(“Hi”)
The if –else Statement
Syntax:
if (expression):
statement 1
statement 2
else:
statement 3
statement 4
a=eval(input("Enter a number:"))
if(a%2==0):
print("No is even")
else:
print("No is odd")
Exercise
Solution 2:
s=input("Enter a character:")
ch=s[0]
if ch>="A" and ch<="Z":
print("You entered a capital letter")
else:
print("You entered a small letter")
Guess The Output
Code:
s=input("Enter a character:")
ch=s[0]
if 65<=ch<=90:
print("You entered a capital letter")
else:
print("You entered a small letter")
Output:
TypeError: <= not supported between int and str
Why Did The Exception Occur ?
s=input("Enter a character:")
ch=s[0]
if 65<=ord(ch)<=90:
print("You entered a capital letter")
else:
print("You entered a small letter")
The if –elif-else Statement
Syntax:
if (expression):
statement 1
statement 2
elif (expression):
statement 3
statement 4
else:
statement 5
statement 6
s=input("Enter a character:")
ch=s[0]
if "A" <=ch <="Z":
print("You entered a capital letter")
elif "a" <=ch <="z":
print("You entered a small letter")
elif "0" <=ch <="9":
print("You entered a digit")
else:
print("You entered some symbol")
The nested if Statement
Syntax:
if (expression):
if (expression):
statement 1
statement 2
else:
statement 3
statement 4
statement 5
statement 6
Exercise
a,b,c=input("Enter 3 int").split()
a=int(a)
b=int(b)
c=int(c)
if a>b:
if a>c:
print("{0} is greatest".format(a))
else:
print("{0} is greatest".format(c))
else:
if b>c:
print("{0} is greatest".format(b))
else:
print("{0} is greatest".format(c))
Exercise
For example:
2017 is not a leap year
2012 is a leap year
1900 is a not leap year
2000 is a leap year
PYTHON
LECTURE 18
Today’s Agenda
• Iterative Statements
• Types of loop supported by Python
Syntax:
while condition:
<indented statement 1>
<indented statement 2>
...
<indented statement n>
<non-indented statement 1>
<non-indented statement 2>
Some Important Points:
First the condition is evaluated. If the condition is true then statements in the while block
is executed.
After executing statements in the while block the condition is checked again and if it is still
true, then the statements inside the while block is executed again.
The statements inside the while block will keep executing until the condition is true.
When the condition becomes false loop terminates and program control comes out of the
while loop to begin the execution of statement following it.
Examples
• Example 1: • Example 2:
i=1
i=1
total=0
while i<=10: while i<=10:
print(i) print(i)
i=i+1 total+=i
print("done!") i=i+1
print("sum is
• Output: {0}".format(total))
• Output:
Guess The Output
i=1 i=1
while i<=10:
while i<=10:
print(i)
print(i) total+=i
i=i+1 i=i+1
print("done!") print("sum is
{0}".format(total))
• Output:
• Output:
Another Form Of
“while” Loop
Syntax:
while condition:
<indented statement 1>
<indented statement 2>
...
<indented statement n>
else:
<indented statement 1>
<indented statement 2>
Some Important Points:
Many programmer’s have a doubt that If the statements of the additional else part
were placed right after the while loop without an else, they would have been
executed anyway, wouldn't they.
• Example 1: • Example 2:
i=1
i=1 while i<=10:
while i<=10: print(i)
if(i==5): i=i+1
break else:
print("bye")
print(i)
i=i+1
else: Output:
print("bye")
Output:
Exercise
This should continue until the user guesses the number correctly
or quits . If the user wants to quit in between he will have to type
0 or negative number
How To Generate
Random Number ?
import random
a=random.randint(1,20)
print("Random number is",a)
Output:
Solution
import random
secretno=random.randint(1,100)
guess=secretno+1
while guess!=secretno:
guess=int(input("Guess the secret number:"))
if(guess<=0):
print("So Sorry! That you are quitting!")
break;
elif(guess>secretno):
print("Your guess is too large. Try again!")
elif(guess<secretno):
print("Your guess is too small. Try again!")
else:
print("Congratulations! You guessed it right!")
Output
Output
The “continue” Statement
i=0
while i<10:
i=i+1
if(i%2!=0):
continue
print(i)
Output:
Exercise
Sample Output:
Exercise
Sample Output:
The “pass” Statement
Example:
Example
i=0
while i<10:
i=i+1
if(i%2!=0):
pass
else:
print(i)
Output:
PYTHON
LECTURE 19
Today’s Agenda
Numeric Ranges
This kind of for loop is a simplification of the previous kind. Starting
with a start value and counting up to an end value, like
for i = 1 to 100
Python doesn't use this either.
The for Loop
This kind of for loop is known in most Unix and Linux shells
and it is the one which is implemented in Python.
Syntax Of for Loop
In Python
Syntax:
for some_var in some_collection:
# loop body
<indented statement 1>
<indented statement 2>
...
<indented statement n>
<non-indented statement 1>
<non-indented statement 2>
Some Important Points:
The for loop in Python can iterate over string , list, tuple ,
set,frozenset, bytes,bytearray and dictionary
The first item in the collection is assigned to the loop variable.
Then the block is executed.
Then again the next item of collection is assigned to the loop
variable, and the statement(s) block is executed
This goes on until the entire collection is exhausted.
Examples
• Example 1: • Example 2:
word="Sachin" fruits=["Apple","Banana",
for ch in word: "Guava","Orange"]
for fruit in fruits:
print(ch) print(fruit)
Output: • Output:
Exercise
Sample Output:
QUIZ- Test Your Skills
A. schn
B. Error
C. sachin
D. Exception
Correct Answer: B
QUIZ- Test Your Skills
A. hi 2 hi 4
B. Syntax Error
C. 24
D. Infinite loop
Correct Answer: A
QUIZ- Test Your Skills
A. hi 2 hi 4
B. Syntax Error
C. 24
D. Infinite loop
Correct Answer: C
QUIZ- Test Your Skills
A. hi 2 hi 4
B. Syntax Error
C. 24
D. No output
Correct Answer: D
QUIZ- Test Your Skills
x = 123
for i in x:
print(i)
A. 123
B. 1
2
3
C. TypeError
D. Infinite loop
Correct Answer: C
QUIZ- Test Your Skills
Correct Answer: A
QUIZ- Test Your Skills
i=1
while True:
if i%2 == 0:
break
print(i,end=“ “)
i += 2
A. 1
B. 1 2
C. Infinite loop
D. Syntax Error
Correct Answer: C
QUIZ- Test Your Skills
A. abcdef
B. iiiiii
C. Error
D. No output
Correct Answer: D
QUIZ- Test Your Skills
A. abcdef
B. Infinite loop
C. Error
D. No output
Correct Answer: B
QUIZ- Test Your Skills
A. aaaaaa
B. a
C. Error
D. No output
Correct Answer: B
QUIZ- Test Your Skills
A. aBCD
B. ABCD
C. abcd
D. Syntax Error
Correct Answer: C
QUIZ- Test Your Skills
A. aBCD
B. ABCD
C. abcd
D. Syntax Error
Correct Answer: B
QUIZ- Test Your Skills
A. my,name,is,sachin,
B. m,y, ,n,a,m,e, ,i,s, ,s,a,c,h,i,n
C. Syntax Error
D. No output
Correct Answer: B
QUIZ- Test Your Skills
A. my,name,is,sachin,
B. m,y,n,a,m,e,i,s,s,a,c,h,i,n
C. Syntax Error
D. No output
Correct Answer: A
QUIZ- Test Your Skills
A. my,name,is,sachin,
B. m,y,n,a,m,e,i,s,s,a,c,h,i,n
C. Syntax Error
D. No output
Correct Answer: C
QUIZ- Test Your Skills
True = False
while True:
print(True)
break
A. True
B. False
C. No output(Blank Screen)
D. None of the above
Correct Answer: D
QUIZ- Test Your Skills
A. Infinite loop
B. 24
C. 23
D. None of the above
Correct Answer: B
The range Function
Syntax:
range(n)
Example:
a=range(10) As we can see that when we display
the variable a , we get to see the description
print(a) of the range object and not the values.
Output:
To see the values , we must convert
range object to list
The range Function
With One Parameter
Syntax:
range(m,n)
Example:
a=range(1,10) Here again when we display
the variable a , we get to see the description
print(a) of the range object and not the values.
Output: So we must use the function list( ) to get
the values
The range Function
With Two Parameter
Example:
a=range(-10,3) Since 3 falls on right of -10 ,
so we are getting range of numbers from
b=list(a) -10 to 3
print(b)
Output:
Guess The Output
a=range(-10,-3) a=range(-3,-3)
b=list(a) b=list(a)
print(b)
print(b)
Output: Output:
a=range(-3,-10)
b=list(a)
print(b)
Output:
The range Function
With Three Parameter
Syntax:
range(m,n,s)
Finally, the range() function can also take the third
parameter . This is for the step value.
Example:
a=range(1,10,2)
b=list(a) Since step value is 2 , so we got nos
print(b) from 1 to 9 with a difference of 2
Output:
Guess The Output
a=range(5,10,0)
It raised a
b=list(a) ValueError because
print(b) the interval cannot
be zero if we need
Output: to go from one
number to another.
Guess The Output
a=range(12,2)
b=list(a) As usual , since the
start value is
print(b) greater than end
value so we get an
Output:
empty list
Using range( ) With for Loop
Syntax:
for <var_name> in range(end)
indented statement 1
indented statement 2
.
.
indented statement n
Example
Code:
for i in range(11):
print(i)
Output:
Using 2 Parameter
range( ) With for Loop
Syntax:
for <var_name> in range(start,end)
indented statement 1
indented statement 2
.
.
indented statement n
Example
Code:
for i in range(1,11):
print(i)
Output:
Exercise
Sample Output:
Solution
num=int(input("Enter an int:"))
total=0
for i in range(1,num+1):
total=total+i
print("sum of nos from 1 to {} is {}".format(num,total))
Exercise
Sample Output:
Using 3 Parameter
range( ) With for Loop
Syntax:
for <var_name> in range(start,end,step)
indented statement 1
indented statement 2
.
.
indented statement n
Example
Code:
for i in range(1,11,2):
print(i)
Output:
Example
Code:
for i in range(100,0,-10):
print(i)
Output:
Using for With else
Just like while , the for loop can also have an else part ,
which executes if no break statements executes in the for
loop
Syntax:
for <var_name> in some_seq:
indented statement 1
if test_cond:
break
else:
indented statement 3
indented statement 4
Example
Code: Output:
for i in range(10):
print(i)
else:
print(“Loop complete”)
Example
Code: Output:
for i in range(1,10):
print(i)
if i%5==0:
break
else:
print(“Loop complete”)
Using Nested Loop
A nested loop is a loop that occurs within another loop, and are
constructed like so:
Syntax:
for <var_name> in some_seq:
for <var_name> in some_seq:
indented statement 1
indented statement 2
.
.
indented statement n
unindented statement
unindented statement
Example
Code: Output:
numbers = [1, 2, 3]
alpha = ['a', 'b', 'c']
for n in numbers:
print(n)
for ch in alpha:
print(ch)
Exercise
Sample Output:
Solution
Code: Output:
for i in range(1,5):
for j in range(1,4):
print("*",end="")
print()
Solution
Code:
for i in range(1,5):
print("*"*3)
Exercise
Sample Output:
Solution
Code: Output:
for i in range(1,5):
for j in range(1,i+1):
print("*",end="")
print()
Exercise
Sample Output:
Solution
Code: Output:
for i in range(4,0,-1):
for j in range(1,i+1):
print("*",end="")
print()
Exercise
Code: Output:
x = int(input('Enter a number: '))
while x != 0:
for y in range (1, x+1):
print (y)
y+=1
x = int(input('Enter a number: '))
PYTHON
LECTURE 20
Today’s Agenda
• Calling A Function
For example:
print(“hello”)
message=“Good Morning”
print(message.lower())
def add(a,b):
print("Values are",a,"and",b)
c=a+b
print("Their sum is",c)
How To Call A Function ?
Syntax:
function_name(arguments)
Complete Example
def add(a,b):
print("Values are",a,"and",b)
c=a+b
print("Their sum is",c)
add(5,10)
add(2.5,5.4)
Output:
Returning Values
From Function
Syntax:
return <expression>
Complete Example
def add(a,b):
c=a+b
return c
x=add(5,10)
print("Sum of 5 and 10 is",x)
y=add(2.5,5.4)
print("Sum of 2.5 and 5.4 is",y)
Output:
Exercise
Sample Output:
Solution
def absolute(n):
if n>0:
return n
else:
return -n
x=absolute(-7)
print("absolute of -7 is",x)
y=absolute(9)
print("absolute of 9 is",y)
Exercise
Sample Output:
Solution
def factorial(n):
f=1
while n>1:
f=f*n
n=n-1
return f
x=int(input("Enter an int:"))
y=factorial(x)
print("Factorial of",x,"is",y)
Guess The Output
def greet(name):
print("Hello",name)
greet("sachin")
greet()
Output:
Guess The Output
def greet(name):
print("Hello",name)
greet("sachin", "amit")
Output:
Guess The Output
def greet(name):
print("Hello",name)
return
print("bye")
greet("sachin")
Output:
Guess The Output
def greet(name):
print("Hello",name)
x=greet("sachin")
print("value in x is",x)
Output:
Returning Multiple Values
From Function
Syntax:
return <value 1, value 2, value 3, . . . >
For example:
return a,b,c
Syntax 1:
var 1,var 2,var 3=<function_name>()
Syntax 2:
var=<function_name>()
def calculate(a,b):
Here Python will
c=a+b automatically set x
d=a-b and y to be of int
type and z to be of
return c,d tuple type
x,y=calculate(5,3)
print("Sum is",x,"and difference is",y)
z=calculate(15,23)
print("Sum is",z[0],"and difference is",z[1])
Output:
PYTHON
LECTURE 21
Today’s Agenda
• Types Of Arguments
Parameters V/s Arguments?
Positional Argument
Keyword Argument
Default Argument
def attach(s1,s2):
s3=s1+s2 These are called
print("Joined String is:",s3)
POSITIONAL
ARGUMENTS
attach("Good","Evening")
Output:
Positional Arguments
def attach(s1,s2):
s3=s1+s2
print("Joined String is:",s3)
attach("Good")
Output:
Guess The Output
def grocery(name,price):
print("Item is",name,"It's price is",price)
grocery("Bread",20)
grocery(150,"Butter")
Output:
The Problem With
Positional Arguments
Syntax:
function_name(paramname1=value,paramname2=value)
Complete Example
def grocery(name,price):
print("Item is",name,"It's price is",price)
grocery(name="Bread",price=20)
grocery(price=150,name="Butter")
Output:
Point To Remember!
For example:
def display(num1,num2):
# some code
Syntax:
def function_name(paramname1=value,paramname2=value):
# function body
Complete Example
greet("Sachin")
greet("Amit","How are you?")
Output:
Point To Remember!
If we call it as :
show(5,7)
Still it will work and output will be 5 7 30
But if we call it as
show(5, ,7)
Then it will be an error
Exercise
def cal_area(radius,pi=3.14):
area=pi*radius**2
print("Area of circle with radius",radius,"is",area)
rad=int(input("Enter radius:"))
cal_area(rad)
Guess The Output ?
def addnos(a,b):
c=a+b
return c
def addnos(a,b,c):
d=a+b+c
return d
print(addnos(10,20))
print(addnos(10,20,30))
Output:
Why Did The Error Occur ?
def addnos(*a):
sum =0
for x in a:
sum=sum+x
return sum
print(addnos(10,20))
print(addnos(10,20,30))
Output:
Exercise
def findlargest(*names):
max=0
for s in names:
if len(s)>max:
max=len(s)
return max
print(findlargest("January","February","March"))
Output:
Exercise
def findlargest(*names):
max=0
largest=""
for s in names:
if len(s)>max:
max=len(s)
largest=s
return largest
print(findlargest("January","February","March"))
Output:
Point To Remember!
def addnos(*a,*b):
Point To Remember!
def addnos(*a,n):
sum =n
for x in a:
sum=sum+x
return sum
print(addnos(20,30,n=10))
print(addnos(20,30,40,n=10))
Guess The Output
def addnos(*a,n):
sum =n
for x in a:
sum=sum+x
return sum
print(addnos(20,n=10,30))
Output:
SyntaxError: Positional argument follows keyword argument
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(10,20)
Output:
10 20 3 4
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(10,20,30,40)
Output:
10 20 30 40
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(d=10,a=20,b=30)
Output:
20 30 3 10
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show()
Output:
TypeError
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(c=30,d=40,10,20)
Output:
SyntaxError
Guess The Output
def show(a,b,c=3,d=4):
print(a,b,c,d)
show(30,40,b=15)
Output:
TypeError : got multiple values for argument ‘b’
PYTHON
LECTURE 22
Today’s Agenda
• Local Scope
• Global Scope
• Argument Passing
Variable Scopes
GLOBAL VARIABLE
LOCAL VARIABLE
A variable which is defined inside a function is local to that function.
It is accessible from the point at which it is defined until the end of the
function.
Output:
I love Python
Example
def f():
print(s)
s = "I love Python"
f()
Even though the
variable s has been
Output: declared after the
function f( ) , still it is
I love Python considered to be
global and can be
accessed from
anywhere in our code
Example
def f():
print(s)
f()
s="I love Python"
def f():
s="I love Python"
print(s)
f()
The variable s now
becomes a local
Output: variable and a
function can easily
I love Python access all the local
variables inside it’s
definition
Example
def f():
s="I love Python"
print(s)
f()
print(s)
The variable s is local
Output: and cannot be
accessed from outside
I love Python it’s function’s
NameError! definition
Example
Output:
I love Python
I love C
I love C
Guess The Output ?
a=1
Output:
def f():
print ('Inside f() : ', a)
global : 1
def g(): inside f( ):1
a=2 global: 1
print ('Inside g() : ',a) inside g( ): 2
def h(): global : 1
global a inside h( ): 3
a=3 global : 3
print ('Inside h() : ',a)
a=0 Output:
if a == 0: 7
3
b=1 0
def my_function(c): 1
NameError!
d=3
print(c)
print(d)
my_function(7)
print(a)
print(b)
print(c)
print(d)
Guess The Output ?
a, b, x, y = 1, 15, 3,4
foo(17, 4)
print(a, b, x, y)
Argument Passing
Call by value
Call by reference.
Call By Value
def show(a):
print("Inside show , a is",a," It's id is",id(a))
Since Python uses Pass by
object reference , so when
a=10 we passed a , Python
passed the address of the
print("Outside show, a is",a,"object
It'spointed
id is",id(a))
by a and this
address was received by
show(a) the formal variable a in the
function’s argument list. So
both the references are
Output: pointing to the same object
Guess The Output ?
def show(mynumbers):
print("Inside show , mynumbers is",mynumbers)
mynumbers.append(40)
print("Inside show , mynumbers is",mynumbers)
Since list is a mutable type ,
mynumbers=[10,20,30] so any change made in the
formal reference
print("Before calling show, mynumbers a does not
is",mynumbers)
create a new object in
show(mynumbers) memory . Rather it changes
the data
print("After calling show, mynumbers stored in original
is",mynumbers)
list
Output:
Guess The Output ?
def show(mynumbers):
mynumbers=[50,60,70]
print("Inside show , mynumbers is",mynumbers)
If we create a new
mynumbers=[10,20,30] object inside the
print("Before calling show, mynumbers is",mynumbers)
function , then Python
will make the formal
show(mynumbers) reference mynumbers
print("After calling show, mynumbers refer
is",mynumbers))
to that new object
but the actual
argument mynumbers ,
Output: will still be refering to
the actual object
Guess The Output ?
def increment(a):
a=a+1
a=10 When we pass n to
increment(n), the function
increment(a) has the local variable n referring
to the same object. Since integer
print(a) is immutable, so Python is not
able to modify the object’s
value to 11 in place and thus it
created a new object. But the
original variable n is still
Output: referring to the same object
with the value 10
10
Guess The Output ?
def swap(a,b):
a,b=b,a
a=10
b=20
swap(a,b)
print(a)
print(b)
Output:
10
20
Guess The Output ?
def changetoupper(s):
s=s.upper()
s="bhopal"
changetoupper(s)
print(s)
Output:
bhopal
Guess The Output ?
def changetoupper(s):
s=s.upper()
return s
s="bhopal"
s=changetoupper(s)
print(s)
Output:
BHOPAL
PYTHON
LECTURE 23
Today’s Agenda
Syntax:
lambda [arg1,arg2,..]:[expression]
def add(a,b):
return a+b
Output:
How To Use
Lambda Functions ?
Output:
Example
squareit=lambda a: a*a
print(squareit(25))
print(squareit(10))
Output:
Example
import math
sqrt=lambda a: math.sqrt(a)
print(sqrt(25))
print(sqrt(10))
Output:
Exercise
Solution:
firstchar=lambda str: str[0]
Output:
Exercise
Solution:
Solution:
iseven=lambda n: n%2==0
print("10 is even :",iseven(10))
print("7 is even:",iseven(7))
Output:
Exercise
Solution:
Output:
PYTHON
LECTURE 24
Today’s Agenda
r = map(func, iterable)
def square(num):
return num**2
What Is map( ) Function?
mynums=[1,2,3,4,5]
mynums=[1,2,3,4,5]
for x in mynums:
print(square(x))
Complete Code
def square(num):
return num**2
mynums=[1,2,3,4,5]
for x in mynums:
print(square(x))
Output:
1
4
9
16
25
Using map( ) Function
def square(num):
return num**2
mynums=[1,2,3,4,5]
result=map(square,mynums)
print(result)
Output:
mynums=[1,2,3,4,5] mynums=[1,2,3,4,5]
result=map(square,mynums) # we can club the 2 lines in 1 line
sqrnum=list(result) sqrnum=list(map(square,mynums))
print(squrnum)
print(sqrnum)
Output:
Previous Code Using map( )
mynums=[1,2,3,4,5]
print(list(map(square,mynums)))
Output:
Previous Code Using map( )
In case we want to iterate over this list , then we can use for loop
def square(num):
return num**2
mynums=[1,2,3,4,5]
for x in map(square,mynums):
print(x)
Output:
Exercise
def inspect(mystring):
if len(mystring)%2==0:
return "EVEN"
else:
return mystring[0]
months=["January","February","March"]
print(list(map(inspect,months)))
Output:
What Is filter( ) Function?
filter(function, sequence)
The first argument should be a function which must return a boolean value
If the function returned True for that item , filter( ) returns that item
as part of it’s return value otherwise the item is not returned.
What Is filter( ) Function?
def check_even(num):
return num%2==0
What Is filter( ) Function?
mynums=[1,2,3,4,5,6]
mynums=[1,2,3,4,5,6]
for x in mynums:
if check_even(x):
print(x)
Complete Code
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
for x in mynums:
if check_even(x):
print(x)
Output:
2
4
6
Using filter( ) Function
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
print(filter(check_even,mynums))
Output:
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
print(list(filter(check_even,mynums)))
Output:
Previous Code Using filter( )
In case we want to iterate over this list , then we can use for loop
as shown below:
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
for x in filter(check_even,mynums):
print(x)
Output:
Guess The Output
def f1(num):
return num*num
Ideally , the function passed
to filter( ) should return a
mynums=[1,2,3,4,5] boolean value. But if it
print(list(filter(f1,mynums))) doesn’t return boolean value
, then whatever value it
returns Python converts it to
boolean . In our case for
Output: each value in mynums the
return value will be it’s
[1,2,3,4,5] square which is a non-zero
value and thus assumed to
be True. So all the elements
are returned by filter()
Guess The Output
def f1(num):
return num%2
For every even number
mynums=[1,2,3,4,5] the return value of the
function f1( ) will be 0
print(list(filter(f1,mynums)))
which is assumed to be
False and for every odd
number the return value
Output: will be 1 which is
[1,3,5] assumed to be True .
Thus filter( ) returns only
those numbers for which
f1( ) has returned 1.
Guess The Output
def f1(num):
print("Hello")
Hello is displayed 5 times
mynums=[1,2,3,4,5] because the filter( )
print(list(filter(f1,mynums))) function has called f1( )
function 5 times. Now for
Output:
each value in mynums ,
Hello since f1( ) has not
Hello returned any value , by
default it’s return value is
Hello
assumed to be None
Hello which is a representation
Hello of False. Thus filter( )
returned an empty list.
[]
Guess The Output
def f1(num):
pass
def f1():
pass The function filter() is trying
to call f1( ) for every value in
the list mynums. But since
mynums=[1,2,3,4,5] f1( ) is a non-parametrized
print(list(filter(f1,mynums))) function , this call generates
TypeError
Output:
Guess The Output
def f1():
pass
mynums=[]
print(list(filter(f1,mynums)))
Output:
[]
Guess The Output
def f1(num):
return num%2
def f1(num):
pass Since f1( ) is not returning
anything , so it’s return
value by default is assumed
mynums=[1,2,3,4,5] to be None and because
map( ) has internally called
print(list(map(f1,mynums)))
f1 () 5 times , so the list
returned contains None 5
times
Output:
[ None,None,None,None ,None ]
Guess The Output
def f1():
pass
mynums=[]
print(list(map(f1,mynums)))
Output:
[]
Using Lambda Expression
With map( ) And filter( )
mynums=[1,2,3,4,5]
sqrnum=list(map(lambda num: num*num,mynums))
print(sqrnum)
Exercise
months=["January","February","March"]
print(list(map(lambda mystring: mystring[0],months)))
Output:
Exercise
months=["January","February","March"]
print(list(map(lambda mystring: "EVEN" if len(mystring)%2==0 else
mystring[0],months)))
Output:
Using Lambdas With filter( )
def check_even(num):
return num%2==0
mynums=[1,2,3,4,5,6]
print(list(filter(check_even,mynums)))
mynums=[1,2,3,4,5,6]
print(list(filter(lambda num:num%2==0 ,mynums)))
Exercise
Output:
PYTHON
LECTURE 25
Today’s Agenda
• List -I
• What Is A List ?
• Creating A List
• Accessing The List Elements
• Adding New Data In The List
• The Slice Operator With List
What Is A List ?
# empty list
my_list = []
# list of integers
my_list = [1, 2, 3]
mynums=[10,20,30,40,50]
print(mynums)
Output:
[10,20,30,40,50]
Accessing Individual Elements
For example:
mynums=[10,20,30,40,50]
mynums=[10,20,30,40,50]
print(mynums[0])
print(mynums[1])
print(mynums[-3])
print(mynums[-2])
Output:
10
20
30
40
Accessing List Elements Using
While Loop
mynums=[10,20,30,40,50]
n=len(mynums) Just like len( )
i=0 works with strings
while i<n: , similarly it also
works with list
print(mynums[i]) also and returns
i=i+1 number of
elements in the
list
Output:
10
20
30
40
50
Accessing List Elements Using
For Loop
mynums=[10,20,30,40,50]
for x in mynums: Since list is a
print(x) sequence type , so
for loop can
Output: iterate over
10 individual
elements of the
20 list
30
40
50
Exercise
mynums=[10,20,30,40,50]
n=len(mynums)
for i in range(n-1,-1,-1):
print(mynums[i])
Output:
50
40
30
20
10
Adding New Data In The List
This method takes one argument and adds it at the end of the list
mynums=[10,20,30,40,50]
print(mynums)
Remember , lists are
mynums.append(60) mutable . So append( )
print(mynums) method doesn’t create a
new list , rather it simply
Output: adds a new element to the
[10,20,30,40,50] existing list.
CAN YOU PROVE THIS ?
[10,20,30,40,50,60]
Solution
mynums=[10,20,30,40,50]
print(mynums)
print(id(mynums)) As we can see in the both
mynums.append(60) the cases the id( )
function is returning the
print(mynums) same address . This
means that no new list
print(id(mynums)) was created.
Output:
Exercise
Output:
Solution
mynums=[]
i=1
while i<=5:
x=int(input("Enter "+str(i)+" element:"))
mynums.append(x)
i=i+1
print("The list is:")
sum=0
for x in mynums:
print(x)
sum+=x
print("Sum is",sum)
Slice Operator With List
Syntax: list_var[x:y]
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[1:4]) print(mynums[3:5])
• Output: • Output:
[20,30,40] [40,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[0:4]) print(mynums[0:10])
• Output: • Output:
[10,20,30,40] [10,20,3040,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[2:2]) print(mynums[6:10])
• Output: • Output:
[] []
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[1: ]) print(mynums[:3])
• Output: • Output:
[20,30,40,50 ] [10,20,30 ]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[ :-2]) print(mynums[-2:])
• Output: • Output:
[10, 20,30 ] [40,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-2:1]) print(mynums[-2:-2])
• Output: • Output:
[] []
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-2:2]) print(mynums[-2:4])
• Output: • Output:
[] [40]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-4:2]) print(mynums[1:-2])
• Output: • Output:
[20 ] [20,30]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-2: -1]) print(mynums[-1:-2])
• Output: • Output:
[40] []
Using Step Value
s[begin:end:step]
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[1:4:2]) print(mynums[1:4:0])
• Output: • Output:
[20,40] ValueError: Slice
step cannot be
0
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[4:1:1]) print(mynums[4:1:-1])
• Output: • Output:
[] [50,40,30]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[::]) print(mynums[::-1])
• Output: • Output:
[10,20,30,40,50 ] [50,40,30,20,10]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[::-2]) print(mynums[::2])
• Output: • Output:
[50,30,10 ] [10,30,50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-1:-4:]) print(mynums[-1:-4:-1])
• Output: • Output:
[] [50,40,30]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-4:-1:]) print(mynums[-4:-1:-1])
• Output: • Output:
[20,30,40] []
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-1: :-2]) print(mynums[-1::2])
• Output: • Output:
[50,30,10] [50]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[-1:4 :2]) print(mynums[-3::-1])
• Output: • Output:
[] [30,20,10]
The Slicing Operator
• Example: • Example:
mynums=[10,20,30,
mynums=[10,20,30,40,50]
40,50]
print(mynums[:-3:-1]) print(mynums[-1:-1:-1])
• Output: • Output:
[50,40] []
PYTHON
LECTURE 26
Today’s Agenda
• List -II
• Modifying A List
• Deletion In A List
• Appending / Prepending Items In A List
• Multiplyng A List
• Membership Operators On List
Modifying A List
sports=["cricket","hockey","football"]
print(sports)
sports[3]="badminton"
print(sports)
Output:
Modifying Multiple Values
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:3]=["badminton","tennis","rugby","table
tennis"]
The number of elements
print(sports) inserted need not be equal to
the number replaced. Python
Output: just grows or shrinks the list
as needed.
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:2]=["badminton","tennis","rugby","table
tennis"]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:1]=["badminton","tennis"]
print(sports) If we have end index same or less
than start index , then Python
doesn’t remove anything . Rather it
simply inserts new elements at the
given index and shifts the existing
Output: element
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:0]=["badminton","tennis"]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:-1]=["badminton","tennis"]
print(sports)
Since -1 is present in the list ,
Python removed items from 1 to
second last item of the list and
inserted new items there
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:-2]=["badminton","tennis"]
print(sports)
Output:
Deleting Item From The List
Example:
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[3]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[4]
print(sports)
Subscript operator will generate
IndexError whenever we pass
invalid index
Output:
Deleting Multiple Items
OR
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:3]=[]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:5]=[]
print(sports)
Slice operator never generates
IndexError , so the code will work
fine and remove all the items from
given start index to the end of the
list
Output:
Example
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[1:3]
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[1:5]
print(sports)
Here also , since we have used the
slice operator , no exception will
Output: arise
Guess The Output ?
sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[0:4]
print(sports)
Output:
Deleting Entire List
Example:
outdoor=["cricket","hockey","football"]
indoor=["carrom","chess","table-tennis"]
allsports=outdoor+indoor
print(allsports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=["carrom","chess","table-tennis"]+sports
print(sports)
Output:
Guess The Output ?
evens=[4,6,8]
evens=2+evens
print(evens)
Output:
Guess The Output ?
evens=[4,6,8]
evens=list(2)+evens
print(evens)
Output:
Guess The Output ?
evens=[4,6,8]
evens=[2]+evens
print(evens)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports+"boxing"
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports+list("boxing")
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports+["boxing"]
print(sports)
Output:
Multiplying A List
sports=["cricket","hockey","football"]
sports=sports*3.0
print(sports)
Output:
Guess The Output ?
sports=["cricket","hockey","football"]
sports=sports*["boxing"]
print(sports)
Output:
Membership Operator On List
Example:
sports=["cricket","hockey","football"]
print("cricket" in sports)
Output:
Exercise
myints=[]
print("Enter 5 unique integers:")
i=0
while i<=4:
item=int(input("Enter element:"))
found=False
for x in myints:
if x==item:
print("Item already present")
found=True
break;
if found==False:
myints.append(item)
i=i+1
print("integers inputted by you are:")
for x in myints:
print(x)
Exercise
list1=[]
list2=[]
print("Enter 5 unique nos for first list:")
for i in range(1,6):
item=int(input("Enter element:"))
list1.append(item)
print("Enter 5 unique nos for second list:")
for i in range(1,6):
item=int(input("Enter element:"))
list2.append(item)
count=0
for x in list1:
for y in list2:
if x==y:
count=count+1
if(count==0):
print("These lists have no common items")
else:
print("These lists have",count," items common")
Exercise
Output:
Solution
list1=[]
list2=[]
list3=[]
print("Enter 5 unique nos for first list:")
for i in range(1,6):
item=int(input("Enter element:"))
list1.append(item)
print("Enter 5 unique nos for second list:")
for i in range(1,6):
item=int(input("Enter element:"))
list2.append(item)
for x in list1:
for y in list2:
if x==y:
list3.append(x)
if(len(list3)==0):
print("These lists have no common items")
else:
print("These lists have",len(list3)," items common")
print("These items are:",list3)
PYTHON
LECTURE 27
Today’s Agenda
• List -III
• Built In Functions For List
Built In Functions For List
These are:
len()
max()
min()
sum()
sorted()
list()
any()
all()
The len( ) Function
Output:
4
The max( ) Function
Example:
nums=[5,2,11,3]
print(max(nums))
Output:
11
Guess The Output ?
months=["january","may","december"]
print(max(months))
Output:
may
Guess The Output ?
booleans=[False,True]
print(max(booleans))
Output:
True
Guess The Output ?
mynums=[1.1,1.4,0.9]
print(max(mynums))
Output:
1.4
Guess The Output ?
mynums=[True,5,False]
print(max(mynums))
Output:
5
Guess The Output ?
mynums=[0.2,0.4,True,0.5]
print(max(mynums))
Output:
True
Guess The Output ?
mynums=["True",False]
print(max(mynums))
Output:
Guess The Output ?
values=[10,"hello",20,"bye"]
print(max(values))
Output:
Guess The Output ?
fruits=["apple","banana","orange"]
print(max(fruits))
Output:
Orange
Guess The Output ?
fruits=["apple","banana","orange",None]
print(max(fruits))
Output:
The min( ) Function
Example:
nums=[5,2,11,3]
print(min(nums))
Output:
2
Guess The Output ?
months=["january","may","december"]
print(min(months))
Output:
december
The sum( ) Function
Example:
nums=[10,20,30]
print(sum(nums))
Output:
60
Guess The Output ?
nums=[10,20,30,True,False]
print(sum(nums))
Output:
61
Guess The Output ?
nums=['1','2','3']
print(sum(nums))
Output:
Guess The Output ?
nums=[2.5,3.5,4.5]
print(sum(nums))
Output:
10.5
The sorted( ) Function
Example:
nums=[7,4,9,1]
print(sorted(nums))
print(nums)
Output:
Guess The Output ?
months=["january","may","december"]
print(sorted(months))
Output:
[“december”,”january”,”may”]
Guess The Output ?
months=["january","may","december",3]
print(sorted(months))
Output:
Guess The Output ?
values=[2.4,1.0,2,3.6]
print(sorted(values))
Output:
[1.0,2,2.4,3.6]
Guess The Output ?
values=["bhopal","bhop","Bhopal"]
print(sorted(values))
Output:
[“Bhopal”,”bhop”,”bhopal”]
Sorting In Descending Order
Example:
nums=[3,1,5,2]
print(sorted(nums,reverse=True))
Output:
The list( ) Function
Example:
city="bhopal"
x=list(city)
print(x)
Output:
Guess The Output ?
n=20
x=list(n)
print(x)
Output:
Guess The Output ?
n="20"
x=list(n)
print(x)
Output:
Guess The Output ?
t=(10,20,30)
x=list(t)
print(x)
This is a
Output: tuple
The any( ) Function
Example:
x = [1, 3, 4, 0]
print(any(x))
Output:
Guess The Output ?
x = [0, False]
print(any(x))
Output:
Guess The Output ?
x = [0, False, 5]
print(any(x))
Output:
Guess The Output ?
x= []
print(any(x))
Output:
The all( ) Function
Syntax:
list(iterable)
Example:
x = [1, 3, 4, 0]
print(all(x))
Output:
Guess The Output ?
x = [0, False]
print(all(x))
Output:
Guess The Output ?
x = [1,3,4,5]
print(all(x))
Output:
Guess The Output ?
x = [0, False, 5]
print(all(x))
Output:
Guess The Output ?
x= []
print(all(x))
Output:
PYTHON
LECTURE 28
Today’s Agenda
• List -IV
• Methods Of List
List Methods
These are:
append()
extend()
insert()
index()
count()
remove()
pop()
clear()
sort()
reverse()
The append( ) Method
Syntax:
list_var.append(item)
Example:
primes=[2,3,5,7]
primes.append(11)
print(primes)
Output:
Guess The Output ?
Output:
Exercise
Output:
Solution
Syntax:
list_var.extend(iterable)
Output:
Example:
primes=[2,3,5,7]
primes.extend([11,13,17])
print(primes)
Guess The Output ?
primes=[2,3,5,7]
primes.extend(11)
print(primes)
Output:
Guess The Output ?
primes=[2,3,5,7]
primes.extend([11])
print(primes)
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
colors=["red","green"]
colors.extend("blue")
print(colors)
Output:
Guess The Output ?
colors=["red","green"]
colors.extend(["blue"])
print(colors)
Output:
Guess The Output ?
a = [1, 2, 3]
b = [4, 5, 6].extend(a)
print(b)
Output:
The insert( ) Method
Syntax:
list_var.insert(index,item)
Example: Output:
primes=[2,3,7,9]
primes.insert(2,5)
print(primes)
Guess The Output ?
primes=[2,3,7,9]
primes.insert(-2,5)
print(primes)
Output:
Guess The Output ?
primes=[2,3,5,7]
primes.insert(5,9)
print(primes)
The method insert( ) works like
slicing operator . So even if the
index given is beyond range , it will
add the element at the end.
Output:
Guess The Output ?
primes=[2,3,5,7]
primes.insert(-5,9)
print(primes)
Output:
Exercise
Output:
Solution
i=1
sortednums=[]
print("Enter any 5 random integers:")
while i<=5:
n=int(input())
pos=0
for x in sortednums:
if x>n:
break
pos=pos+1
sortednums.insert(pos,n)
i=i+1
print("Sorted list is:")
print(sortednums)
The index( ) Method
Syntax:
list_var.index(item)
Output:
Example:
primes=[2,3,5,7]
pos=primes.index(5)
print("position of 5 is",pos)
Guess The Output ?
Output:
Guess The Output ?
mynums = [10,20,30,40,50]
x = mynums.index(20)
print("20 occurs at",x,"position")
x = mynums.index(60)
print("60 occurs at",x,"position")
x = mynums.index(10)
print("10 occurs at",x,"position")
Output:
Guess The Output ?
Output:
The count( ) Method
Syntax:
list_var.count(item)
Output:
Example:
country=['i','n','d','i','a']
x=country.count('i')
print("i occurs",x,"times in",country)
Guess The Output ?
Output:
Guess The Output ?
points = [1, 4, 2, 9, 7, 8, 9, 3, 1]
x = points.count(9)
print("9 occurs",x,"times")
Output:
Guess The Output ?
Output:
The remove( ) Method
Syntax:
list_var.remove(item)
Output:
Example:
vowels=['a','e','i','o','u']
vowels.remove('a')
print(vowels)
Guess The Output ?
subjects=["phy","chem","maths"]
subjects.remove("chem")
print(subjects)
Output:
Guess The Output ?
subjects=["phy","chem","maths","chem"]
subjects.remove("chem")
print(subjects)
subjects.remove("chem")
print(subjects)
subjects.remove("chem")
print(subjects)
Output:
The pop( ) Method
The pop() method removes and returns the element at the given
index (passed as an argument) from the list.
Syntax:
list_var.pop(index)
If the index passed to the pop() method is not in the range, it throws IndexError:
pop index out of range exception.
The pop() method returns the element present at the given index.
Also, the pop() method updates the list after removing the element
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
del v/s pop( ) v/s remove( )
Syntax:
list_var.clear( )
Example:
fruits = ['apple', 'banana', 'cherry']
print(fruits)
fruits.clear() Output:
print(fruits)
The sort( ) Method
Syntax:
list_var.sort(reverse=True|False, key=name of func)
Parameter Values:
Parameter Name Description
reverse Optional. reverse=True will sort
the list descending. Default is
reverse=False
key Optional. A function to specify the
sorting criteria(s)
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
Guess The Output ?
mylist = ["a",10,True]
mylist.sort()
print(mylist)
Output:
Guess The Output ?
mylist = [25,10,True,False]
mylist.sort()
print(mylist)
Output:
Passing Our
Own Function As Key
def sortSecond(val):
return val[1]
list1 = [(1,2),(3,3),(1,1)]
list1.sort(key=sortSecond)
print(list1)
Output:
Guess The Output ?
def sortSecond(val):
return 0
list1 = [(1,2),(3,3),(1,1)]
list1.sort(key=sortSecond)
print(list1)
Output:
Guess The Output ?
Output:
Guess The Output ?
def myFunc(val):
return val[2]
Output:
The reverse( ) Method
Syntax:
list_var.reverse( )
Example:
os = ['Windows', 'macOS', 'Linux']
print('Original List:', os) Output:
os.reverse()
print('Updated List:', os)
PYTHON
LECTURE 29
Today’s Agenda
• List -V
• List Comprehension
What Is Comprehension ?
text="Bhopal"
myList=[]
for x in text:
myList.append(x)
print(myList)
Output:
Using Lambda
Output:
Understanding
List Comprehension
Output:
Syntax For
List Comprehension
Syntax:
Explanation
Output:
Using for Loop
squaresList=[]
for i in range(1,6):
squaresList.append(i**2)
print(squaresList)
Using List Comprehension
Output:
Using for Loop
text=input("Type a string:")
uppersList=[]
for x in text.split():
uppersList.append(x.upper())
print(uppersList)
Using List Comprehension
text=input("Type a string:")
uppersList=[x.upper()for x in text.split()]
print(uppersList)
Exercise
Output:
Using for Loop
myNums=[]
text=input("Enter 5 integers:")
for x in text.split():
myNums.append(int(x))
print("List is:",myNums)
print("Sum is:",sum(myNums))
Using List Comprehension
text=input("Enter 5 integers:")
myNums=[int(x) for x in text.split()]
print("List is:",myNums)
print("Sum is:",sum(myNums))
Adding Conditions In
List Comprehension
Syntax:
Solution
squaresList=[x**2 for x in range(1,6) if x%2!=0]
print(squaresList)
Output:
Exercise
Output:
Using for Loop
def removevowels(text):
myList=[]
for x in text:
if x not in "aeiou":
myList.append(x)
return myList
text=input("Type a string:")
finalList=removevowels(text)
print(finalList)
Using List Comprehension
def removevowels(text):
myList=[x for x in text if x not in "aeiou"]
return myList
text=input("Type a string:")
finalList=removevowels(text)
print(finalList)
Exercise
Output:
Solution
def get_numbers(myList):
mynumberList=[x for x in myList if type(x) is int]
return mynumberList
myList=["bhopal",25,"$","hello",34,21,"indore",22]
print("Actual List")
print(myList)
print("List with numbers only")
mynumberList=get_numbers(myList)
print(mynumberList)
Exercise
Output:
Solution
def getlength(str):
myList=[len(x) for x in str.split() if x!="the"]
return myList
text=input("Type a string:")
myList=getlength(text)
print(myList)
Adding Multiple Conditions
In List Comprehension
Syntax:
Solution
myList=[x**2 for x in range(1,21) if x%2==0 if x%3==0]
print(myList)
Output:
Previous Code Using for Loop
myNums=[]
for x in range(1,21):
if x%2==0:
if x%3==0:
myNums.append(x**2)
print(myNums)
Exercise
Output:
Solution
text=input("Type a string:")
myList=get_upper(text)
print(myList)
What About
Logical Operators ?
Example:
a = [1,2,3,4,5,6,7,8,9,10]
b = [x for x in a if x % 2 == 0 or x % 3 == 0]
print(b)
Output:
Exercise
Output:
Solution
def remove_min_max(myList):
myNewList=[x for x in myList if x!=min(myList) and x!=max(myList)]
return myNewList
a=[10,3,15,12,24,6,1,18]
print("Original list")
print(a)
print("After removing min and max element")
print(remove_min_max(a))
If – else
In List Comprehension
Syntax:
Output:
Nested
List Comprehension
a=[20,40,60]
b=[2,4,6] Explanation:
c.append(x * y)
print(c)
Output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]
Nested
List Comprehension
a=[20,40,60]
b=[2,4,6]
c=[x * y for x in a for y in b]
print(c)
Output:
[40, 80, 120, 80, 160, 240, 120, 240, 360]
Exercise
Output:
Solution
def flatten(mylist):
newlist=[y for x in mylist for y in x]
return newlist
mylist = [[1,2,3],[4,5,6],[7,8]]
print("Before calling flatten list is")
print(mylist)
newlist=flatten(mylist)
print("After calling flatten list is")
print(newlist)
PYTHON
LECTURE 30
Today’s Agenda
• Tuple-I
• What Is A Tuple ?
• Differences With List
• Benefits Of Tuple
• Creating Tuple
• Packing / Unpacking A Tuple
• Accessing A Tuple
What Is A Tuple ?
# empty tuple
my_tuple = ()
my_tuple = (2,)
print(my_tuple)
print(type(my_tuple))
Output:
Guess The Output ?
my_tuple = ()
print(my_tuple)
print(type(my_tuple))
Output:
Packing And Unpacking
A Tuple
Packing:
Packing is a simple syntax which lets us create tuples "on the fly"
without using the normal notation:
a = 1, 2, 3
This creates a tuple of 3 values and assigned it to a. Comparing this to
the "normal" way:
a = (1, 2, 3)
Packing And Unpacking
A Tuple
Unpacking:
We can also go the other way, and unpack the values from a tuple
into separate variables:
a = 1, 2, 3
x, y, z = a
Next, the tuple is assigned to the left hand side of the = sign:
Output:
Guess The Output ?
def add(a,b,c,d):
print("Sum is",a+b+c+d)
mytuple=(10,20,30,40)
add(*mytuple)
Output:
Accessing The Tuple
values=(10,20,30,40)
print(values)
Output:
Accessing
Individual Elements
For example:
mynums=(10,20,30,40,50)
mynums=(10,20,30,40,50)
print(mynums[0]) Even though we
create tuple using
print(mynums[1]) the symbol of ( ) but
print(mynums[-3]) when we access it’s
individual element ,
print(mynums[-2]) we still use the
subscript or index
operator [ ]
Output:
Accessing Tuple Elements
Using
While Loop
mynums=(10,20,30,40,50)
n=len(mynums) Just like len( )
works with list,
i=0 similarly it also
while i<n: works with tuple
and returns
print(mynums[i]) number of
elements in the
i=i+1
tuple
Output:
Accessing Tuple Elements
Using
For Loop
mynums=(10,20,30,40,50)
for x in mynums: Since tuple is a
print(x) sequence type , so
for loop can
iterate over
Output: individual
elements of the
tuple
Exercise
title,singer,year,songs=album
print("Title:",title)
print("Year:",year)
print("Singer:",singer)
for info in songs:
print("\tSong Number:{0},Song
Name:{1}".format(info[0],info[1]))
Slice Operator With Tuple
Just like we can apply slice operator with lists and strings
, similarly Python allows us to apply slice operator with
tuple also.
Syntax: tuple_var[x:y]
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[1:4]) print(mynums[3:5])
• Output: • Output:
(20,30,40) (40,50)
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[0:4]) print(mynums[0:10])
• Output: • Output:
(10,20,30,40) (10,20,3040,50)
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[2:2]) print(mynums[6:10])
• Output: • Output:
() ()
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[1: ]) print(mynums[:3])
• Output: • Output:
(20,30,40,50 ) (10,20,30)
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
Mynums=(10,20,30,40,50)
40,50)
print(mynums[ :-2]) print(mynums[-2:])
• Output: • Output:
(10, 20,30 ) (40,50)
Using Step Value
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[1:4:2]) print(mynums[1:4:0])
• Output: • Output:
(20,40) ValueError: Slice
step cannot be
0
The Slicing Operator
• Example: • Example:
mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[4:1:1]) print(mynums[4:1:-1])
• Output: • Output:
() (50,40,30)
The Slicing Operator
• Example: • Example:
Mynums=(10,20,30,
mynums=(10,20,30,40,50)
40,50)
print(mynums[::]) print(mynums[::-1])
• Output: • Output:
(10,20,30,40,50 ) (50,40,30,20,10)
PYTHON
LECTURE 31
Today’s Agenda
• Tuple-II
• Changing The Tuple
• Deleting The Tuple
• Functions Used With Tuple
Changing A Tuple
mynums=(10,20,30,40,50)
mynums[0]=15
Output:
Guess The Output ?
mynums=([10,20],30,40,50)
print(mynums) Why did the code run?
mynums[0][0]=15 Although a tuple is immutable,
print(mynums) but if it contains a mutable
data then we can change
it’s value
Output:
Guess The Output ?
myvalues=("hello",30,40,50)
print(myvalues)
myvalues[0]="hi"
print(myvalues)
Output:
Guess The Output ?
myvalues=(["hello",20],30,40,50)
print(myvalues)
myvalues[0][0]="hi"
print(myvalues)
Output:
Guess The Output ?
mynums=(10,20,30,40,50)
print(mynums) Why did the code run?
mynums=(15,25,35,45,55) Tuple object is immutable ,
print(mynums) but tuple reference is mutable.
So we can assign a new
tuple object to the same reference
Output:
Deleting A Tuple
mynums=(10,20,30,40,50)
print(mynums)
del mynums[0]
print(mynums)
Output:
Guess The Output ?
mynums=(10,20,30,40,50)
print(mynums)
del mynums[2:4]
print(mynums)
Output:
Guess The Output ?
mynums=(10,20,30,40,50)
print(mynums)
del mynums
print(mynums)
Output:
Built In Functions For Tuple
But only those functions work with tuple which do not modify it
Can you figure out which of these functions will work with
tuple ?
Answer:
len() All of them will work with tuple.
max()
min() Will sorted( ) also work ?
sum()
sorted() Yes, even sorted( ) function
tuple() will also work since it does not
any() change the original tuple ,
all() rather it returns a sorted copy
of it
The len( ) Function
Output:
4
The max( ) Function
Example:
nums=(5,2,11,3)
print(max(nums))
Output:
11
Guess The Output ?
months=("january","may","december“)
print(max(months))
Output:
may
Guess The Output ?
booleans=(False,True)
print(max(booleans))
Output:
True
Guess The Output ?
Mynums=(True,5,False)
print(max(mynums))
Output:
5
Guess The Output ?
mynums=("True",False)
print(max(mynums))
Output:
Guess The Output ?
values=(10,"hello",20,"bye")
print(max(values))
Output:
Guess The Output ?
fruits=("apple","banana","orange")
print(max(fruits))
Output:
orange
Guess The Output ?
fruits=("apple","banana","orange",None)
print(max(fruits))
Output:
The min( ) Function
Example:
nums=(5,2,11,3)
print(min(nums))
Output:
2
Guess The Output ?
months=("january","may","december")
print(min(months))
Output:
december
The sum( ) Function
Example:
nums=(10,20,30)
print(sum(nums))
Output:
60
Guess The Output ?
nums=(10,20,30,True,False)
print(sum(nums))
Output:
61
Guess The Output ?
nums=('1','2','3')
print(sum(nums))
Output:
Guess The Output ?
nums=(2.5,3.5,4.5)
print(sum(nums))
Output:
10.5
The sorted( ) Function
Output:
Guess The Output ?
months=("january","may","december")
print(sorted(months))
Output:
[“december”,”january”,”may”]
Guess The Output ?
months=("january","may","december",3)
print(sorted(months))
Output:
Guess The Output ?
values=(2.4,1.0,2,3.6)
print(sorted(values))
Output:
[1.0,2,2.4,3.6]
Guess The Output ?
values=("bhopal","bhop","Bhopal")
print(sorted(values))
Output:
[“Bhopal”,”bhop”,”bhopal”]
Sorting In Descending Order
Example:
nums=(7,4,9,1)
print(sorted(nums,reverse=True))
print(nums)
Output:
The tuple( ) Function
Example:
city="bhopal"
x=tuple(city)
print(x)
Output:
Guess The Output ?
n=20
x=tuple(n)
print(x)
Output:
Guess The Output ?
n="20"
x=tuple(n)
print(x)
Output:
Guess The Output ?
l=[10,20,30]
x=tuple(l)
print(x)
Output:
The any( ) Function
Example:
x = (1, 3, 4, 0)
print(any(x))
Output:
Guess The Output ?
x = (0, False)
print(any(x))
Output:
Guess The Output ?
x = (0, False, 5)
print(any(x))
Output:
Guess The Output ?
x= ()
print(any(x))
Output:
Guess The Output ?
x= ("","0", "")
print(any(x))
Output:
Guess The Output ?
x= ("",0, "")
print(any(x))
Output:
Guess The Output ?
x= (4)
print(any(x))
Output:
Guess The Output ?
x= (4,)
print(any(x))
Output:
The all( ) Function
Syntax:
all(iterable)
Example:
x = (1, 3, 4, 0)
print(all(x))
Output:
Guess The Output ?
x = (0, False)
print(all(x))
Output:
Guess The Output ?
x = (1,3,4,5)
print(all(x))
Output:
Guess The Output ?
x = (0, False, 5)
print(all(x))
Output:
Guess The Output ?
x= ()
print(all(x))
Output:
PYTHON
LECTURE 32
Today’s Agenda
• Tuple-III
• Methods Used With Tuple
Syntax:
tuple_var.index(item)
Output:
Example:
primes=(2,3,5,7)
pos=primes.index(5)
print("position of 5 is",pos)
Guess The Output ?
Output:
Guess The Output ?
mynums = (10,20,30,40,50)
p = mynums.index(20)
print("20 occurs at",p,"position")
p = mynums.index(60)
print("60 occurs at",p,"position")
p = mynums.index(10)
print("10 occurs at",p,"position")
Output:
The count( ) Method
Syntax:
tuple_var.count(item)
Output:
Example:
country=('i','n','d','i','a')
x=country.count('i')
print("i occurs",x,"times in",country)
Guess The Output ?
Output:
Guess The Output ?
points = (1, 4, 2, 9, 7, 8, 9, 3, 1)
x = points.count(9)
print("9 occurs",x,"times")
Output:
Guess The Output ?
Output:
Operations Allowed On Tuple
These are:
Membership Operators
Concatenation Operator
Multiplication
Relational Operators
Membership Operators
my_tuple = ('a','p','p','l','e',)
print('a' in my_tuple)
print('b' in my_tuple)
print('g' not in my_tuple)
Output:
Concatenation On Tuple
odds=(1,3,5)
evens=(2,4,6)
all=odds+evens
print(all)
Output:
Guess The Output ?
ages=(10,20,30)
names=("amit","deepak","ravi")
students=ages+names
print(students)
Output:
Multiplication On Tuple
a=(10,20,30)
b=a*3
print(b)
Output:
Guess The Output ?
a=(10,20,30)
b=a*3.0
print(b)
Output:
Relational Operators
On Tuples
a=(1,2,3)
b=(1,3,4)
print(a<b)
Output:
True
Guess The Output ?
a=(1,3,2)
b=(1,2,3)
print(a<b)
Output:
False
Guess The Output ?
a=(1,3,2)
b=(1,3,2)
print(a<b)
Output:
False
Guess The Output ?
a=(1,2,3)
b=(1,2,3,4)
print(a<b)
Output:
True
Guess The Output ?
a=(5,2,7)
b=(1,12,14)
print(a>b)
Output:
True
Guess The Output ?
a=()
b=(0)
print(a<b)
Output:
TypeError : < not supported between instances of
‘tuple’ and ‘int’
Guess The Output ?
a=()
b=(0,)
print(a<b)
Output:
True
Guess The Output ?
a=(1,2)
b=("one","two")
print(a<b)
Output:
Guess The Output ?
a=(1,"one")
b=(1,"two")
print(a<b)
Output:
True
PYTHON
LECTURE 33
Today’s Agenda
• Strings -I
• What Is A String ?
• Creating A String
• Different Ways Of Accessing Strings
• Operators Which Work On Strings
What Is A String ?
my_string = 'Hello'
print(my_string)
my_string = "Hello"
print(my_string)
my_string = '''Hello'''
print(my_string)
my_string = """Hello, welcome to
the world of Python"""
print(my_string)
Output:
How Can Strings
Be Accessed ?
city="Bhopal"
print(city)
Output:
Bhopal
Accessing Individual
Elements
For example:
city=“Bhopal”
city="Bhopal"
print(city[0])
print(city[1])
print(city[-1])
print(city[-2])
Output:
B
h
l
a
Guess The Output ?
city="Bhopal"
print(city[6])
Output:
IndexError: String index out of range
Guess The Output ?
city="Bhopal"
print(city[1.5])
Output:
TypeError: String indices must be integers
Accessing String Elements Using
while Loop
city="Bhopal"
i=0
Just like len( )
while i<len(city): works with lists
print(city[i]) and tuple
i=i+1 similarly it also
works with string
returns number of
Output: elements in the
B string
h
o
p
a
l
Accessing String Elements Using
for Loop
city="Bhopal"
for ch in city: Since string is a
print(ch) sequence type , so
for loop can
Output: iterate over
B individual
elements of the
h string
o
p
a
l
Exercise
city="Bhopal"
for i in range(len(city)-1,-1,-1):
print(city[i])
Output:
l
a
p
o
h
B
Slice Operator With String
Just like we can apply slice operator with lists and tuples,
similarly Python allows us to apply slice operator with
strings also.
Syntax: string_var[x:y]
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[3:5])
print(city[1:4])
• Output:
• Output:
pa
hop
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[0:10])
print(city[0:4])
• Output:
• Output:
Bhopal
Bhop
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[6:10])
print(city[2:2])
• Output:
• Output:
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[:4])
print(city[1:])
• Output:
• Output:
Bhop
hopal
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[-2:])
print(city[:-2])
• Output:
• Output:
al
Bhop
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[-2:-2])
print(city[-2:1])
• Output:
• Output:
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[-2:5])
print(city[-2:2])
• Output:
• Output:
a
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[1:-2])
print(city[-4:3])
• Output:
• Output:
hop
o
Using Step Value
s[begin:end:step]
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[1:4:0])
print(city[1:4:2])
• Output:
• Output:
ValueError: Slice
hp
step cannot be
0
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal"
print(city[4:1:-1])
print(city[4:1:1])
• Output:
• Output:
apo
The Slicing Operator
• Example: • Example:
city="Bhopal"
city="Bhopal" print(city[::-1])
print(city[::])
• Output:
• Output: lapohB
Bhopal
The Operators
With Strings
Example:
a="Good"
b="Morning"
c="User"
print(a+b+c)
Output:
GoodMorningUser
The Operator *
Example:
a="Bye"
print(a*2)
print(2*a)
Output:
ByeBye
ByeBye
Guess The Output ?
a="Bye"
print(a*0) The * operator
print(a*-2) allows it’s
operand to be
negative or 0 in
Output: which case it
returns an empty
string
Guess The Output ?
x="Ba"+"na"*2
print(x)
Output:
Banana
The Operator in
Example:
a="banana"
print(“nana” in a)
print(“nani” in a)
Output:
True
False
The Operator not in
Example:
a="banana"
print(“nana” not in a)
print(“nani” not in a)
Output:
False
True
The Relational Operators
False
"tim" == "tie" True
"free" != "freedom" True
"arrow" > "aron" True
"right" >= "left“ False
"teeth" < "tee" False
"yellow" <= "fellow" True
"abc" > " "
The Identity Operators
Example: Output:
a = 'London'
b = 'London' True
c = 'Paris' False
print(a is b) False
print(a is c) False
print(b is c) True
print(b is not a)
print(b is not c)
PYTHON
LECTURE 34
Today’s Agenda
• Strings -II
• Built In String Functions
• Printing string using f-string
• Calculating time for code snippets
• Modifying Strings
Built In String Functions
These are:
len()
max()
min()
chr()
ord()
The len( ) Function
Example:
name="Sachin"
print(len(name))
Output:
6
The max( ) Function
Example:
name="bhopal"
print(max(name))
Output:
p
Guess The Output ?
str="abc123#$.y@*"
print(max(str))
Output:
y
Guess The Output ?
str="False,True"
print(max(str))
Output:
u
Guess The Output ?
str="1.1,0.4,1.9"
print(max(str))
Output:
9
The min( ) Function
Example:
name="bhopal"
print(min(name))
Output:
a
Guess The Output ?
str=“Bhopal"
print(min(str))
Output:
B
Guess The Output ?
str="abc123#$.y@*"
print(min(str))
Output:
#
Guess The Output ?
str="1.1,0.4,1.9"
print(min(str))
Output:
,
The chr( ) Function
Example:
print(chr(122))
Output:
z
Guess The Output ?
print(chr(43))
Output:
+
Guess The Output ?
print(chr(1))
Output:
Guess The Output ?
print(chr(0))
Output:
Guess The Output ?
print(chr(-1))
Output:
ValueError: chr() argument not in range
The ord( ) Function
Example:
print(ord(‘a’))
Output:
97
Guess The Output ?
print(ord("+"))
Output:
43
Guess The Output ?
print(ord("5"))
Output:
53
The str( ) Function
Example:
print(str(49.2))
Output:
49.2
Guess The Output ?
print(str(True))
Output:
True
Guess The Output ?
print(str(25))
Output:
25
String Interpolation
To understand this feature , can you tell how can we print the
following 2 variables using print( ):
name=“Sachin”
age=34
name="Sachin"
age=34
print(f"My name is {name} and my age is {age}")
Arbitary Expressions
a=10
b=20
print(f"sum is {a+b}")
Output:
Function Calls
import math
a=10
b=20
print(f"max of {a} and {b} is {max(a,b)}")
print(f"Factorial of {a} is {math.factorial(10)}")
Output:
Method Calls
vowels=["a","e","i","o","u","a"]
ch="a"
print(f"{ch} is occuring in {vowels}
{vowels.count(ch)} times")
Output:
PYTHON
LECTURE 35
Today’s Agenda
• Strings -III
• String Methods
String Methods
capitalize( )
Returns a copy of the string with first character
capitalized and rest of the characters in lower case.
Example:
name="guido van rossum"
newname=name.capitalize()
print(f"Original name is {name}\nCapitalized name is {newname}")
Output:
String Conversion Methods
Output:
String Conversion Methods
Output:
String Conversion Methods
swapcase()
Returns a copy of the string with the case of every
character swapped . Means that lowercase characters
are changed to uppercase and vice-versa.
Example:
name="Sachin Kapoor"
newname=name.swapcase()
print(f"Original name is {name}")
print(f"Swapped name is {newname}")
Output:
String Conversion Methods
title()
Returns a copy of the string converted to proper case or
title case. i.e. , all words begin with uppercase letter and
the rest are in lowercase.
Example:
text="we got independence in 1947"
newtext=text.title()
print(f"Original text is {text}")
print(f"Title text is {newtext}")
Output:
String Conversion Methods
Output:
String Conversion Methods
text = "physics,chemistry,maths"
print(text.title())
Output:
String Conversion Methods
text = "physics_chemistry_maths"
print(text.title())
Output:
String Conversion Methods
text = "physics1chemistry2maths"
print(text.title())
Output:
String Conversion Methods
Output:
String Comparison Methods
Example:
s = 'this is good'
print(s.islower())
Example:
s = "THIS IS GOOD!"
print(s.isupper())
Example:
s = ""
print(s.isupper())
print(s.islower())
Output:
String Comparison Methods
istitle( )
Example: Output:
s = 'Python Is Good.' True
print(s.istitle()) False
True
s = 'Python is good'
True
print(s.istitle())
False
s = 'This Is @ Symbol.'
print(s.istitle())
s = '99 Is A Number'
print(s.istitle())
s = 'PYTHON'
print(s.istitle())
String Comparison Methods
isalpha( )
Example: Output:
name = "Monalisa" True
print(name.isalpha()) False
False
name = "M0nalisa"
print(name.isalpha())
isdigit( )
Example: Output:
text = "12345" True
print(text.isdigit()) True
False
text = "012345" False
print(text.isdigit())
text = “a12345"
print(text.isdigit())
String Comparison Methods
isdecimal( )
Example: Output:
text = "12345" True
print(text.isdecimal()) True
False
text = "012345"
False
print(text.isdecimal())
text = “a12345"
print(text.isdecimal())
String Comparison Methods
isnumeric( )
Example: Output:
text = "12345" True
print(text.isnumeric()) True
False
text = "012345" False
print(text.isnumeric())
text = “a12345"
print(text.isnumeric())
isdigit( ) V/s isdecimal( ) V/s
isnumeric( )
In Python:
Example: Output:
s = '\u00B23455'
print(s)
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
s = '\u00BD'
print(s)
print(s.isdigit())
print(s.isdecimal())
print(s.isnumeric())
String Comparison Methods
isalnum( )
Example: Output:
name = "M234onalisa" True
print(name.isalnum()) False
True
name = "M3ona Shah " True
print(name.isalnum())
name = "Mo3nalisaSha22ah"
print(name.isalnum())
name = "133"
print(name.isalnum())
String Comparison Methods
isspace( )
Example: Output:
s = ' \t' True
print(s.isspace()) False
True
s='a' False
print(s.isspace())
s=''
print(s.isspace())
s = ''
print(s.isspace())
String Comparison Methods
startswith( )
Example: Output:
text = "Python is easy to learn." False
True
result = text.startswith('is easy')
True
print(result)
True
result = text.startswith('Python is ')
print(result)
endswith( )
Example:
text = "Python is easy to learn." Output:
False
result = text.endswith('to learn')
print(result)
True
True
result = text.endswith('to learn.')
print(result)
False
False
result = text.endswith('learn.', 7) True
print(result)
index( )
Returns the index of first occurrence of a substring
inside the string (if found).
Example: Output:
text= 'Sunday is a fun day' 7
3
result = text.index('is a fun') 16
print(result) ValueError
result = text.index('day')
print(result)
result = text.index('day',7)
print(result)
result = text.index('night')
print(result)
String Searching Methods
find( )
Returns the first index of a substring inside the string (if
found).
If the substring is not found, it returns -1
Example: Output:
text= 'Sunday is a fun day' 7
3
result = text.find('is a fun') 16
print(result) -1
result = text.find('day')
print(result)
result = text.find('day',7)
print(result)
result = text.find('night')
print(result)
String Searching Methods
rfind( )
Returns the highest index of a substring inside the string
(if found).
Example: Output:
text= 'Sunday is a fun day' 7
16
result = text.rfind('is a fun') 3
print(result) -1
result = text.rfind('day')
print(result)
result = text.rfind('day',0)
print(result)
result = text.rfind('night')
print(result)
String Searching Methods
count( )
Returns the number of occurrences of a substring in the
given string
Example: Output:
text = "Python is awesome, isn't it?" 2
substring = "is" 1
0
count = text.count(substring)
print(count)
substring = "i"
count = text.count(substring, 8, 25)
print(count)
substring="ton"
count = text.count(substring)
print(count)
String Replacement Methods
replace( )
Returns a copy of the string where all occurrences of a substring is
replaced with another substring.
The replace() method returns a copy of the string where old substring is
replaced with the new substring. The original string is unchanged.
If the old substring is not found, it returns the copy of the original string.
String Replacement Methods
Example: Output:
text = "Blue Blue Blue" Black Black Black
newtext= text.replace("ue","ack") Black Black Blue
Blue Blue Blue
print(newtext)
newtext= text.replace("ue","ack",2)
print(newtext)
newtext= text.replace("eu","ack")
print(newtext)
String Replacement Methods
strip( )
Returns a copy of the string with both leading and trailing
characters removed (based on the string argument passed).
Example: Output:
text = " Good Morning " Original text:[ Good Morning ]
newtext= text.strip() New text:[Good Morning]
print("Original text:["+text+"]")
print("New text:["+newtext+"]")
Exercise
def get_full_name():
while True:
name=input("Type your full name:").strip()
if name.find(" ")!=-1:
return name
print("Please enter your full name!")
def get_password():
while True:
pwd=input("Type your password:")
cap_letter_present=False
digit_present=False
for x in pwd:
if x.isdigit():
digit_present=True
elif x.isupper():
cap_letter_present=True
if digit_present==False or cap_letter_present==False or len(pwd)<8:
print("Password must be of 8 or more characters in length\nwith atleast 1 digit and 1 capital
letter")
else:
return pwd
def get_first_name(fullname):
spacepos=fullname.find(" ")
return fullname[0:spacepos]
fullname=get_full_name()
pwd=get_password()
firstname=get_first_name(fullname)
print("Hello",firstname,"\nThank you for joining us!")
String Replacement Methods
split( )
The split() method breaks up a string at the specified
separator and returns a list of strings.
The split() breaks the string at the separator and returns a list of
strings.
String Replacement Methods
Example: Output:
text= 'Live and let live' [‘Live’,’and’,’let’,’live’]
print(text.split()) [‘Milk’,’ Butter’,’ Bread’]
[‘Milk,Butter,Bread’]
grocery = 'Milk, Butter, Bread'
print(grocery.split(', '))
print(grocery.split(':'))
String Replacement Methods
join( )
The join() method returns a string concatenated with the
elements of an iterable.
Syntax: <str>.join(<iterable>)
String Replacement Methods
Example:
mylist = ["C","C++","Java","Python"]
s = "->"
print(s.join(mylist))
Output:
C→C++→Java→Python
String Replacement Methods
Example:
letters = 'PYTHON'
letters_spaced = ' '.join(letters)
print(letters_spaced)
Output:
PYTHON
PYTHON
LECTURE 36
Today’s Agenda
• Dictionary-I
• What Is A Dictionary ?
• What Is Key-Value Pair ?
• Creating A Dictionary
• Important Characteristics Of A Dictionary
• Different Ways To Access A Dictionary
• An Important Point
What Is A Dictionary ?
Syntax:
d={
<key>: <value>,
<key>: <value>,
...
<key>: <value>
}
How To Create A Dictionary?
# empty dictionary
my_dict = { }
print(student_data)
Output:
Accessing Individual
Elements
print(student_data[3])
print(student_data.get(3))
Output:
Difference Between
[ ] And get( )
Output:
Another Way To
Iterate Only On Keys
Output:
How to get values ?
Output:
A Performance Issue ?
Syntax:
Explanation:
Output:
Iterate Only On Values
Output:
A Very Important Point !
But you must have observed that it was not the case with
us.
Output:
• Dictionary-II
• Updating Elements In Dictionary
• Removing Elements From Dictionary
• Functions Used In Dictionary
Updating A Dictionary
These are:
assignment operator or
Output:
Guess The Output ?
Output:
Updating Using
update( ) Method
dict_var.update( dict_var2)
accounts={101:50000,102:45000,103:55000}
print("Current Accounts Present")
print(accounts)
id=int(input("Enter account id:"))
amt=int(input("Enter amount:"))
balance=accounts.get(id)
if balance == None:
accounts[id]=amt
print("New Account Created")
else:
newbalance=balance+amt
accounts[id]=newbalance
print("Account updated")
print("Account Details:")
print(accounts)
Removing Data From
Dictionary
These are:
pop(key): removes the entry with provided key and returns it’s value
clear(): clears all the items in the dictionary and returns an empty
dictionary
The pop() Method
dict_var.pop(key,[default])
dict_var.popitem( )
Just like list , Python also allows us to delete an item from the
dictionary by calling the operator/keyword del
del dict_var[key]
If we do not pass the key then del deletes the entire dictionary
object
Guess The Output ?
Output:
The clear() Method
dict_var.clear( )
Output:
Functions Used With
Dictionary
len()
max()
min()
any()
all()
sorted()
dict()
The len( ) Function
Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}
print(len(sixMonths))
Output:
6
The max( ) Function
Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}
print(max(sixMonths))
Output:
May
Guess The Output ?
Output:
Guess The Output ?
Output:
6
Guess The Output ?
Output:
True
Guess The Output ?
data={False:0,True:1,None:2}
print(max(data))
Output:
Exercise
players={}
i=1
while i<=5:
name=input("Enter player name:")
runs=int(input("Enter runs:"))
players[name]=runs
i=i+1
print(players)
runs=max(players.values())
print("Highest runs are :",runs)
Exercise
Modify the previous code so that you are able to find out
the name of the player also who has scored the highest
score
Sample Output
Solution
players={}
i=1
while i<=5:
name=input("Enter player name:")
runs=int(input("Enter runs:"))
players[name]=runs
i=i+1
print(players)
max=0
pl=""
for name,runs in players.items():
if runs>max:
max=runs
pl=name
print("Player with top score is",pl,"with score of",max)
The min( ) Function
Example:
sixMonths = {"Jan":31, "Feb":28, "Mar":31, "Apr":30, "May":31,
"Jun":30}
print(min(sixMonths))
Output:
Apr
The any( ) Function
Example:
data={1:31,2:28,3:30}
print(any(data))
Output:
Guess The Output ?
data={0:1,False:2,'':3}
print(any(data))
Output:
Guess The Output ?
data={'0':1,False:2,'':3}
print(any(data))
Output:
Guess The Output ?
data= { }
print(any(data))
Output:
The all( ) Function
Example:
data={1:31,2:28,3:30,0:10}
print(all(data))
Output:
Guess The Output ?
data={1:31,2:28,3:30}
print(all(data))
Output:
Guess The Output ?
data={'0':1,True:2,' ':3}
print(all(data))
Output:
Guess The Output ?
data= { }
print(all(data))
Output:
The sorted( ) Function
Output:
Guess The Output ?
Output:
Guess The Output ?
Output:
The dict( ) Function
Example:
months = dict(Jan=31,Feb=28)
print('months = ',months)
print(type(months))
Output:
Guess The Output ?
months = dict([('Jan',31),('Feb',28)])
print('months = ',months)
Output:
Guess The Output ?
months = dict((('Jan',31),('Feb',28)))
print('months = ',months)
Output:
Guess The Output ?
months = dict({'Jan':31,'Feb':28})
print('months = ',months)
Output:
Guess The Output ?
months = dict(12)
print('months = ',months)
Output:
The kwargs Function
Argument
Example:
def addnos(x,y,z):
print("sum:",x+y+z)
addnos(10,20,30)
addnos(10,20,30,40,50)
Output:
The kwargs Function
Argument
def addnos(*args):
sum=0
for x in args:
sum=sum+x
print("sum:",sum)
addnos(10,20,30)
addnos(10,20,30,40,50)
Output
The args Function
Argument
def show_details(**data):
print("\nData type of argument:",type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
show_details(Firstname="Amit", Lastname="Sharma",
Email="[email protected]", Country="India", Age=25,
Phone=9893198931)
The kwargs Function
Argument
PYTHON
LECTURE 38
Today’s Agenda
• Dictionary-III
• Dictionary Methods
• Removing Elements From Dictionary
• Functions Used In Dictionary
Dictionary Methods
clear()
copy()
setdefault()
get()
items()
keys()
pop()
popitem()
update()
values()
The copy( ) Method
Syntax:
dict.copy()
Example:
original = {1:'one', 2:'two'}
new = original.copy()
print('new: ', new)
print('original: ', original)
Output:
copy( ) v/s =
Output: Output:
The setdefault( ) Method
This method method returns the value of a key (if the key is in
dictionary).
If not, it inserts key with a value to the dictionary.
Syntax:
dict.setdefault(key,[value])
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
print(cars)
value=cars.setdefault("Hyundai")
print("Value is",value)
print(cars)
value=cars.setdefault("Hyundai","i10")
print("Value is",value)
print(cars)
value=cars.setdefault("Renault")
print("Value is",value)
print(cars)
value=cars.setdefault("Audi","Q7")
print("Value is",value)
print(cars)
Output:
Using in And not in
With Dictionary
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
print(cars)
print("Hyundai is present:","Hyundai" in cars)
print("Audi is present:" ,"Audi" in cars)
print("Renault not present:","Renault" not in cars)
Output:
Dictionary Comprehension
Syntax:
Explanation
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
newcars={ k:v for (k,v) in cars.items()}
print(newcars)
Output:
Exercise
cars = {"Maruti":"Ciaz","Hyundai":"Verna","Honda":"Amaze"}
newcars={}
for (k,v) in cars.items():
newcars[k]=v
Output:
Exercise
Output:
Exercise
Output:
Exercise
Output:
Solution
str=input("Type a string:")
mydict={ch:str.count(ch) for ch in str}
for k,v in mydict.items():
print(k,":",v)
Adding Conditions To
Dictionary Comprehension
Syntax:
dict_variable = { key:value for (key,value) in iterable <test_cond>}
Output:
Exercise
Output:
Exercise
Output:
Restrictions On
Dictionary Keys
Example:
d={65:"A", 3.14:"pi", True:1}
print(d)
Output:
Restrictions On
Dictionary Keys
Example:
d={int:1, float:2, bool:3}
print(d)
print(d[float])
Output:
Restrictions On
Dictionary Keys
Example:
d={"MP":"Indore","UP":"Lucknow","RAJ":"Jaipur"}
print(d)
d["MP"]="Bhopal"
print(d)
Output:
Restrictions On
Dictionary Keys
Output:
Restrictions On
Dictionary Keys
Example:
d = {(1, 1): 'a', (1, 2): 'b', (2, 1): 'c', (2, 2): 'd'}
print(d)
print(d[(1,2)])
Output:
Restrictions On
Dictionary Keys
Example:
d = {[1, 1]: 'a', [1, 2]: 'b', [2, 1]: 'c', [2, 2]: 'd'}
print(d)
Output:
Restrictions On
Dictionary Values
IN→India
US→America
AU→Australia
CA→Canada
Sample Output
Solution
def show_menu():
print("SELECT AN OPTION:")
print("view: View country names")
print("add: Add a country")
print("del: Delete a country")
print("exit- Exit the program")
print()
def show_codes(countries):
codes=list(countries.keys())
codes.sort()
str="Country Codes:"
for x in codes:
str+=x+" "
print(str)
Solution
def view_country(countries):
show_codes(countries)
code=input("Enter country code:")
cname=countries.get(code.upper())
if cname==None:
print("There is no country for country code",code)
else:
print("Country is",cname)
def add_country(countries):
code=input("Enter country code:")
code=code.upper()
cname=countries.get(code)
if cname==None:
cname=input("Enter country name:")
cname=cname.title()
countries[code]=cname
print(cname, "added to the list")
else:
print(code ,"is already used by",cname)
Solution
def del_country(countries):
code=input("Enter country code:")
cname=countries.pop(code.upper(),"NF")
if cname=="NF":
print("Sorry! You entered a wrong country code")
else:
print(cname ,"was deleted successfully! from the list")
countries={"IN":"India","US":"America","AU":"Australia","CA":"Canada"}
while True:
show_menu()
choice=input("Your choice:")
if choice=="view":
view_country(countries)
elif choice=="add":
add_country(countries)
elif choice=="del":
del_country(countries)
elif choice=="exit":
break;
else:
print("Wrong choice ! Try again!")
Exercise
Modify the previous code , so that now you are able to store
3 values for each key . These are COUNTRY NAME ,
CAPITAL CITY and POPULATION. Provide same options
to the user and start with the following data
IN→India , Delhi,1320000000
US→America,Washington,320000000
AU→Australia,Canberra,24000000
CA→Canada,Ottawa,940000
Sample Output
PYTHON
LECTURE 39
Today’s Agenda
In all the programs we wrote till now, we have designed our program
around functions i.e. blocks of statements which manipulate
data.
• Thus we can say that a class represents the data type and
object represents a kind of variable of that data type
Syntax:
class <class_name>:
# class members
Example:
class Emp:
pass
Creating Objects
Syntax:
var_name=class_name( )
Example:
e=Emp()
Full Code
class Emp:
pass
1.The first line shows the class
name which is Emp.
Output:
Adding
Data Members/Attributes
class Emp:
def __init__(self):
print("Object created. . .")
class Emp:
def __init__(self):
print("Object created. . .")
e=Emp()
f=Emp()
g=Emp()
Output:
The argument self ?
What is self ?
Why it is required ?
What Is self ?
class Emp:
def __init__():
print("Object created. . .")
As you can observe ,
Python has generated an
e=Emp() exception , since it has
passed the object address
as argument while calling
the method __init__() but
we have not declared any
argument to receive it
Output:
Can We Give Some Other Name
To self ?
class Emp:
def __init__(myself):
print("Object created. . .")
Output:
More About self
No , not at all
class Emp:
def __init__(self):
print("Object Created...")
e=Emp()
print(self)
Output:
The Most Important Role
Of self
Syntax:
class <class_name>:
def __init__(self):
self.<var_name>=value
.
.
Example
The variables
class Emp: self.age,self.name
and self.salary are
def __init__(self): called instance
variables
self.age=25
self.name="Rahul" Remember , we cannot
use self outside the class
self.salary=30000.0 . So outside the class we
will have to use the
reference variable e
e=Emp()
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Another very important
point to understand if you
Output: are from C++ background is
that in Python by default
everything in a class is
public . So we can direclty
access it outside the class
A Very Important Point!
Inside the methods of the class , they are always accessed using self so
that Python will refer them for current object
Outside the class , we cannot access them using self because self is
only available within the class.
So outside the class we have to access them using the object reference
we have created
Guess The Output ?
class Emp:
def __init__(self):
Unlike C++ or Java ,
self.age=25 in Python we can
self.name="Rahul" create instance
variables outside the
class by directly using
e=Emp() the object reference
e.salary=30000.0
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Output:
A Problem With The Code
class Emp:
def __init__(self,age,name,salary):
self.age=age
The variables age,
self.name=name
name an salary are
self.salary=salary called local variables
e=Emp(25,"Rahul",30000.0)
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
f=Emp(31,"Varun",45000.0)
print("Age:",f.age,"Name:",f.name,"Salary:",f.salary)
Output:
An Important Point
The variables age , name and salary used in the argument list
of __init__() are called parameters or local variables.
class Emp:
def __init__(self,x,y,z):
self.age=x
self.name=y
self.salary=z
e=Emp(25,"Rahul",30000.0)
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
f=Emp(31,"Varun",45000.0)
print("Age:",f.age,"Name:",f.name,"Salary:",f.salary)
Output:
Guess The Output ?
class Emp:
e1=Emp("amit")
def __init__(self,name):
e2=Emp("sumit",23)
self.name=name
e3=Emp("deepak",34,50000.)
def __init__(self,name,age): print(e1.name)
self.name=name print(e2.name,e2.age)
self.age=age print(e3.name,e3.age,e3.sal)
def __init__(self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
Output:
Why Didn’t The Code Run ?
Yes !
class Emp:
def __init__(self,name,age=0,sal=0.0):
self.name=name
self.age=age
self.sal=sal
e1=Emp("amit")
e2=Emp("sumit",23)
e3=Emp("deepak",34,50000.)
print(e1.name)
print(e2.name,e2.age)
print(e3.name,e3.age,e3.sal)
Output:
PYTHON
LECTURE 40
Today’s Agenda
• Types Of Methods
• Adding Instance Methods
• Obtaining Details Of Instance Variables
• Different Ways To Create Instance Variables
• Deleting Instance Variables
Adding
Methods In Class
class Emp:
def __init__(self,age,name,salary):
self.age=age
self.name=name
self.salary=salary
def show(self):
print("Age:",self.age,"Name:",self.name,"Salary:",self.salary)
e=Emp(25,"Rahul",30000.0)
f=Emp(31,"Varun",45000.0)
e.show()
f.show()
Output:
Exercise
import math
class Circle:
def __init__(self,radius):
self.radius=radius
def cal_area(self):
area=math.pi*math.pow(self.radius,2)
print("Area of circle is",area)
def cal_circumference(self):
circumf=math.tau * self.radius
print("Circumference of circle is",circumf)
radius=int(input("Enter radius:"))
cobj=Circle(radius)
cobj.cal_area()
cobj.cal_circumference()
Guess The Output ?
class Emp:
Output:
Guess The Output ?
class Emp:
def __init__(self):
self.name=“Amit”
self.age=24
self.sal=50000.0
def show(self):
print(self.age,self.name,self.sal)
e1=Emp()
e1.show()
Output:
Guess The Output ?
class Emp:
Output:
Local Var V/s Instance Var
They are declared inside method body but They are declared inside method body
without using self always using self
They are only accessible to the method They are always available to every instance
in which they have been declared method
They live only till the execution of the They are a part of object , so they live
method is not over. Once it is over they are until the object gets destroyed
destroyed
They can be declared in any method They also can be declared and defined in any
defined inside the class instance method but normally it is advised to
declare / create them inside the method
__init__() and then use them in other
instance methods
Methods V/s Constructor
Methods Constructor
They can be declared with any name we It always has the name __init__()
like
They can be called as many number of It is called just once for one object
times as we want for a single object
They are used for performing different tasks It is exclusively used for creation and
related to the object , also called business initialization of instance members for
logic an object
Obtaining Details Of
Instance Variables
class Emp:
def __init__(self):
self.name="Amit"
self.age=24
self.sal=50000.0
e1=Emp()
print(e1.__dict__)
Output:
Guess The Output ?
class Emp:
def __init__(self):
self.name="Amit"
self.age=24
sal=50000.0
e1=Emp()
print(e1.__dict__)
Output:
Guess The Output ?
class Emp:
def __init__(self):
self.name="Amit"
self.age=24
def set_sal(self):
self.sal=50000.0
e1=Emp()
print(e1.__dict__)
e1.set_sal()
print(e1.__dict__)
Output:
Guess The Output ?
class Emp:
def __init__(self):
self.name="Amit"
self.age=24
def set_sal(self):
self.sal=50000.0
comm=2000.0
e1=Emp()
print(e1.__dict__)
e1.set_sal()
print(e1.__dict__)
Output:
Guess The Output ?
class Emp:
Since __dict__ is a
def __init__(self): dictionary , we can
self.name="Amit" manipulate it and
self.age=24 add/del instance
self.sal=50000.0 members from it
def show(self):
print(self.name,self.age,self.sal,self.department)
e1=Emp()
print(e1.__dict__)
e1.__dict__['department']='IT'
print(e1.__dict__)
e1.show()
Output:
Guess The Output ?
class Emp:
def __init__(self):
self.name="Amit"
self.age=24
self.sal=50000.0
def show(self):
print(self.name,self.age,self.sal,self.department)
e1=Emp()
print(e1.__dict__)
e1.__dict__['department']='IT'
print(e1.__dict__)
e1.show()
del e1.__dict__['age']
e1.show()
Output:
Challenge !
e1=Emp("Amit",24,50000.0)
e1.show()
Output:
Solution
class Emp:
def __init__(self,**kwargs):
self.__dict__.update(kwargs)
def show(self):
print(self.name,self.age,self.sal)
e1=Emp(name="Amit",age=24,sal=50000.0)
e1.show()
Output:
How Many Ways Are There To
Create Instance Variables ?
class Emp:
e1=Emp("Amit",24,30000.0)
def __init__(self,name,age,sal):
e2=Emp("Sumit",34,45000.0)
self.name=name
e1.setDept("Finance")
self.age=age e1.setProject("Banking Info System")
self.sal=sal e1.setBonus(20000.0)
def setDept(self,department): e2.setDept("Production")
self.department=department print(e1.__dict__)
def setProject(self,project): print() Since Python is
self.project=project print(e2.__dict__)
dynamically typed
def setBonus(self,bonus): language so object’s of
self.bonus=bonus same class can have
different number of
Output: instance variables
Deleting Instance Variables
class Boy:
def __init__(self,name,girlfriend):
self.name=name
self.girlfriend=girlfriend
def breakup(self):
del self.girlfriend
b1=Boy("Deepak","Jyoti")
print(b1.__dict__)
b1.breakup()
print(b1.girlfriend)
Output:
Guess The Output ?
class Engineer:
def __init__(self,girlfriend,job):
self.girlfriend=girlfriend
self.job=job
def fired(self):
del self.job
e1=Engineer("Rani","Software Engineer")
print(e1.__dict__)
e1.fired()
del e1.girlfriend
print(e1.__dict__)
Output:
Guess The Output ?
class Emp:
def __init__(self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
e1=Emp("Amit",24,50000.0)
print(e1.__dict__)
del e1
print(e1.__dict__)
Output:
Guess The Output ?
Output:
Guess The Output ?
For example :
Syntax:
class <class_name>:
<var_name>=<value>
def __init__(self):
This is called a
// object specific code class variable
Using name of the class anywhere inside the methods of the class
class CompStudent:
The variable
stream = 'cse' stream is class
def __init__(self,name,roll): variable
self.name = name
self.roll = roll
Everytime we will access
obj1 = CompStudent('Atul',1) the class variable stream
obj2 = CompStudent('Chetan', 2) from any object , the
print(obj1.name) value will remain same
print(obj1.roll)
print(obj1.stream)
print(obj2.name)
print(obj2.roll) Output:
print(obj2.stream)
print(CompStudent.stream)
Exercise
class Emp:
raise_amount=7.5
def __init__(self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
def increase_sal(self):
self.sal=self.sal+(self.sal*Emp.raise_amount/100)
def display(self):
print(self.name,self.age,self.sal)
e1=Emp("Amit",24,50000.0)
e2=Emp("Sumit",26,45000.0)
print("Before incrementing :")
print("_____________________");
e1.display()
e2.display()
e1.increase_sal()
e2.increase_sal()
print()
print("After incrementing by",Emp.raise_amount,"percent:")
print("__________________________________");
e1.display()
e2.display()
Declaring Class Variable
Inside Constructor
def __init__(self):
<class name>.<var_name>=<value>
self.<var_name>=<value>
.
.
.
Example
class CompStudent:
We have shifted the
var decl from class
def __init__(self,name,roll): body to constructor
CompStudent.stream='cse' body , but still it will
self.name = name be treated as class
self.roll = roll variable because we
have prefixed it with
classnname
obj1 = CompStudent('Atul',1)
obj2 = CompStudent('Chetan', 2)
print(obj1.name)
print(obj1.roll)
print(obj1.stream)
print(obj2.name)
print(obj2.roll) Output:
print(obj2.stream)
print(CompStudent.stream)
Declaring Class Variable
Inside Instance Method
def <method_name>(self):
<class name>.<var_name>=<value>
self.<var_name>=<value>
.
.
.
Example
class Emp:
raise_per=7.5
comp_name="Google"
def __init__(self):
self.name="Amit"
self.age=24
self.sal=50000.0
e1=Emp()
print(e1.__dict__)
print()
print(Emp.__dict__)
Output:
How many class variables
will be created by this code?
class Sample:
i=10
def __init__(self):
Sample.j=20
def f1(self): Three class variables
Sample.k=30 will be created by the
Sample.m=40 code called i,j and m
s1=Sample()
print(Sample.__dict__)
Output:
How many class variables
will be created by this code?
class Sample:
i=10
def __init__(self):
Sample.j=20
def f1(self):
Sample.k=30
Sample.m=40
s1=Sample()
s2=Sample()
s1.f1()
s2.f1()
print(Sample.__dict__)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
print("Constructor called. . .")
print(Sample.i)
print(self.i)
def f1(self):
print("f1 called. . .")
print(Sample.i)
print(self.i)
s1=Sample()
s1.f1()
Output:
Guess The Output ?
class Sample:
s1=Sample()
i=10
s1.f1()
def __init__(self):
print(Sample.i)
print("Constructor called. . .") print(s1.i)
print(Sample.i)
print(self.i)
def f1(self):
print("f1 called. . .")
print(Sample.i)
print(self.i)
Output:
Guess The Output ?
As mentioned previously , if
class Sample: we use self or object reference
i=10 to modify a class variable ,
then Python does not modify
def __init__(self): the class variable . Rather it
self.i=20 creates a new instance
variable inside the object’s
memory area by the same
name.
s1=Sample() So in our case 2 variables by
print(Sample.i) the name i are created . One as
class variable and other as
instance variable
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
self.i=20
s1=Sample()
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
Sample.i=20
s1=Sample()
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
Sample.i=20
s1=Sample()
s1.i=30
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
Sample.i=20
s1=Sample()
Sample.i=30
print(Sample.i)
print(s1.i)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
self.j=20
s1=Sample()
s2=Sample()
s1.i=100
s1.j=200
print(s1.i,s1.j)
print(s2.i,s2.j)
Output:
Guess The Output ?
class Sample:
i=10
def f1(self):
self.j=20
s1=Sample()
s2=Sample()
s1.i=100
s1.j=200
print(s1.i,s1.j)
print(s2.i,s2.j)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
self.j=20
s1=Sample()
s2=Sample()
Sample.i=100
s1.j=200
print(s1.i,s1.j)
print(s2.i,s2.j)
Output:
Deleting Class Variables
class Sample:
i=10
def __init__(self):
del Sample.i
print(Sample.__dict__)
s1=Sample()
print()
print(Sample.__dict__)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
del self.i
print(Sample.__dict__)
s1=Sample()
print()
print(Sample.__dict__)
Output:
Guess The Output ?
class Sample:
i=10
def __init__(self):
del Sample.i
print(Sample.__dict__)
s1=Sample()
del Sample.i
print()
print(Sample.__dict__)
Output:
PYTHON
LECTURE 42
Today’s Agenda
• Class Methods
• Creating Class Methods
• Accessing Class Methods
• Static Methods
• Accessing Static Methods
• Difference Between Instance Method , Class Method and Static
Methods
Class Methods
class Emp:
raise_amount=0
@classmethod
def set_raise_amount(cls):
cls.raise_amount=float(input("Enter raise percentage:"))
def __init__(self,name,age,sal):
self.name=name
self.age=age
self.sal=sal
def increase_sal(self):
self.sal=self.sal+(self.sal*Emp.raise_amount/100) This can can also
def display(self): be written as
print(self.name,self.age,self.sal)
Emp.set_raise_amount()
Emp.raise_amount
e1=Emp("Amit",24,50000.0)
e2=Emp("Sumit",26,45000.0)
print("Before incrementing :")
print("_____________________");
e1.display()
e2.display()
e1.increase_sal()
e2.increase_sal()
print()
print("After incrementing by",Emp.raise_amount,"percent:")
print("__________________________________");
e1.display()
e2.display()
Static Methods
The third type of method a Python class can contain are called
static methods
Just like class methods , they also do not require any object to
be called and can be called using name of the class
Static Methods
Notice that a
Syntax: static method
class <class_name>: doesn’t get any
implicit
@staticmethod argument by
Python
def <method_name>(<arg_list> )
// argument specific code
Example
class MyMath:
@staticmethod
def add_nos(a,b):
c=a+b
return c
@staticmethod
def mult_nos(a,b):
c=a*b
return c
A static method can access class data using the name of the
class.
class Demo:
def display(): Since we have not used the
decorator @staticmethod with the
print("Inside display")
method display ( ) and we are
calling it using object reference , so
Python is considering it to be an
d=Demo()
instance method. As we know to
d.display() every instance method Python
passes an implicit argument called
self and we have to receive it in our
method ,but in display we haven’t
done so. Thus the code is throwing
Output:
TypeError
Guess The Output ?
class Demo:
def display():
print("Inside display")
Demo.display()
Output:
Guess The Output ?
class Demo:
def display(self):
print("Inside display") Don’t think Python is
considering it as an instance
method . Python is still
Demo.display() considering it a static method
because we are calling it using
class name .The Exception is
Output: occurring because the method is
parameterized and we are not
passing it any argument.
Guess The Output ?
class Demo:
def display(self):
print("Inside display")
Now since the required
argument has been
Demo.display(“Hello”) passed , Python has
successfully executed the
Output: method as a static
method
Guess The Output ?
class Demo:
def display(self):
Now since we are calling
print("Inside display")
it using the object
reference , Python has
D=Demo() passed the first argument
D.display( ) as address of the object
and executed the code
considering the method
Output:
as an instance method
When To Use
Each Type Of Method ?
• Encapsulation
• The Destructor
Encapsulation
self.name="Rahul"
self.salary=30000.0
e=Emp()
print("Age:",e.age,"Name:",e.name,"Salary:",e.salary)
Output:
How To Achieve Encapsulation
In Python ?
Syntax:
self.__<var_name>=<value>
Achieving Encapsulation
e=Emp()
print("Age:",e.age)
print("Name:",e.name)
print("Salary:",e.__salary)
Output:
Achieving Encapsulation
class Emp:
def __init__(self):
self.__age=25
self.__name="Rahul"
self.__salary=30000.0
def show(self):
print("Age:",self.__age,"Name:",self.__name,"Salary:",self.__salary)
e=Emp()
e.show()
Output:
Private Methods
class Emp:
def __init__(self):
self.__age=25
self.__name="Rahul"
self.__salary=30000.0
def __show(self):
print("Age:",self.__age,"Name:",self.__name,"Salary:",self.__salary)
e=Emp()
e.__show()
Output:
An Important Point
class Emp:
def __init__(self):
self.__age=25
self.__name="Rahul"
self.__salary=30000.0
def show(self):
print("Age:",self.__age,"Name:",self.__name,"Salary:",self.__salary)
e=Emp()
e.show()
print("Age:",e._Emp__age,"Name:",e._Emp__name,"Salary:",e._Emp__salary)
Output:
The setattr() And getattr()
Functions
class Data:
pass
d = Data()
d.id = 10
print(d.id)
setattr(d, 'id', 20)
print(d.id)
Output:
10
20
The __str__() Method
For predefined classes like list ,tuple or str , we get the contents of
the object
For our own class objects we get the class name and the id of the
object instance (which is the object’s memory address in CPython.)
Why Is It So ?
obj=object()
print(type(obj))
print(dir(obj))
Output:
The __str__() Method
class Emp:
def __init__(self,age,name,salary):
self.age=age
self.name=name
self.salary=salary
def __str__(self):
return f"Age:{self.age},Name:{self.name},Salary:{self.salary}"
e=Emp(25,"Rahul",30000.0)
print(e)
Output:
Destructor
class Test:
def __init__(self):
print("Object created")
def __del__(self):
print("Object destroyed")
t1=Test()
del t1
print("done")
Output:
Guess The Output ?
class Test:
We must remember that Python
def __init__(self): destroys the object only when the
print("Object created") reference count becomes 0 . Now
in this case after deleting t1 , still
the object is being refered by t2 .
def __del__(self): So the __del__() was not called
print("Object destroyed") on del t1. It only gets called when
t2 also goes out of scope at the
t1=Test()
end of the program and reference
t2=t1 count of the object becomes 0
del t1
print("done")
Output:
Guess The Output ?
class Test:
def __init__(self):
print("Object created")
def __del__(self):
print("Object destroyed")
t1=Test()
t2=t1
del t1
print("t1 deleted")
del t2
print("t2 deleted")
print("done")
Output:
PYTHON
LECTURE 44
Today’s Agenda
• Inheritance
• Types Of Inheritance
• Single Inheritance
• Using super( )
• Method Overriding
Inheritance
The new class is called derived (or child) class and the
one from which it inherits is called the base (or parent)
class.
Real Life Examples
Real Life Examples
Benefits
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
For Ex:
class Account:
pass
class SavingAccount(Account):
pass
Example
class A:
def __init__(self):
print("Instantiating A...")
As you can see,
class B(A): Python called the
constructor of class
pass A , since B class
doesn’t has any
b=B() constructor defined
Output:
How Constructors Behave
In Inheritance ?
class A:
def __init__(self):
print("Instantiating A...")
This time , Python
class B(A): did not call the
constructor of class
def __init__(self): A as it found a
print("Instantiating B...") constructor in B
itself
b=B()
Output:
How Constructors Behave
In Inheritance ?
class Rectangle:
def __init__(self): Notice that we have
self.l=10 to explicitly pass the
self.b=20 argument self while
calling __init__()
method of parent
class Cuboid(Rectangle):
class
def __init__(self):
Rectangle.__init__(self)
self.h=30
def volume(self):
print("Vol of cuboid is",self.l*self.b*self.h)
obj=Cuboid()
obj.volume()
Output:
Calling Parent Constructor
Using super( )
class Rectangle:
Again notice that this
def __init__(self): time we don’t have to
self.l=10 pass the argument
self.b=20 self when we are
using super( ) as
class Cuboid(Rectangle): Python will
def __init__(self): automatically pass it
super().__init__();
self.h=30
def volume(self):
print("Vol of cuboid is",self.l*self.b*self.h)
obj=Cuboid()
obj.volume()
Output:
What Really Is super( ) ?
We don’t have to pass self while calling any method using super( ).
If the name of parent class changes after inheritance then we will not
have to rewrite the code in child as super( ) will automatically connect
itself to current parent
class Person:
def __init__(self,age,name):
self.age=age
self.name=name
def __str__(self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def __init__(self,age,name,id,sal):
super().__init__(age,name)
self.id=id
self.sal=sal
e=Emp(24,"Nitin",101,45000)
print(e)
Output:
Explanation
Now since the class Person has this method , Python calls
the __str__() method of Person which returns only the
name and age
Method Overriding
class Person:
def __init__(self,age,name):
self.age=age
self.name=name
def __str__(self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def __init__(self,age,name,id,sal):
super().__init__(age,name)
self.id=id
self.sal=sal
def __str__(self):
return f"Age:{self.age},Name:{self.name},Id:{self.id},Salary:{self.sal}"
e=Emp(24,"Nitin",101,45000)
print(e)
Output:
Role Of super( )
In Method Overriding
class Person:
def __init__(self,age,name):
self.age=age
self.name=name
def __str__(self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def __init__(self,age,name,id,sal):
super().__init__(age,name)
self.id=id
self.sal=sal
def __str__(self):
str=super().__str__()
return f"{str},Id:{self.id},Salary:{self.sal}"
e=Emp(24,"Nitin",101,45000)
print(e)
Output:
Exercise
__init___() : This method should accept an argument and initialize radius with it
__init___() : This method should initialize instance members radius and height
with the parameter passed.
area( ): This method should override Circle’s area( ) to calculate and return area of
Cylinder . ( formula: 2πr2+2πrh)
Output:
A Very Important Point!
Syntax:
<base_class_name>.<method_name>(<der_obj>)
Example
Output:
PYTHON
LECTURE 45
Today’s Agenda
• MultiLevel Inheritance
• Hierarchical Inheritance
class A:
# properties of class A
class B(A):
# class B inheriting property of class A
# more properties of class B
class C(B):
# class C inheriting property of class B
# thus, class C also inherits properties of class A
# more properties of class C
Exercise
class Person:
def __init__(self,age,name):
self.age=age
self.name=name
print("Person constructor called. . .")
def __str__(self):
return f"Age:{self.age},Name:{self.name}"
class Emp(Person):
def __init__(self,age,name,id,sal):
super().__init__(age,name)
self.id=id
self.sal=sal
print("Emp constructor called. . .")
def income(self):
return self.sal
def __str__(self):
str=super().__str__()
return f"{str},Id:{self.id},Salary:{self.sal}"
Solution
class Manager(Emp):
def __init__(self,age,name,id,sal,bonus):
super().__init__(age,name,id,sal)
self.bonus=bonus
print("Manager constructor called. . .")
def income(self):
total=super().income()+self.bonus
Output:
return total
def __str__(self):
str=super().__str__()
return f"{str},Bonus:{self.bonus}"
m=Manager(24,"Nitin",101,45000,20000)
print(m)
print("Manager's Salary:",Emp.income(m))
print("Manager's Total Income:",m.income())
Hierarchical Inheritance
class SchoolMember:
def tell(self):
class Teacher(SchoolMember):
def tell(self):
super().tell()
print("Salary:",self.salary)
Example
class Student(SchoolMember):
Syntax:
class MyBase(object):
pass
class MyDerived(MyBase):
pass
print(issubclass(MyDerived, MyBase))
print(issubclass(MyBase, object))
print(issubclass(MyDerived, object))
print(issubclass(MyBase, MyDerived))
Output:
Guess The Output ?
class MyBase:
pass In Python 3 , every
class implicitly
class MyDerived(MyBase): inherits from object
class but in Python 2
pass it is not so. Thus in
Python 2 the 2nd and
print(issubclass(MyDerived, MyBase)) 3rd print( ) statements
would return False
print(issubclass(MyBase, object))
print(issubclass(MyDerived, object))
print(issubclass(MyBase, MyDerived))
Output:
Alternate Way
Syntax:
class MyBase:
pass Output:
class MyDerived(MyBase):
pass
d = MyDerived()
b = MyBase()
print(isinstance(d, MyBase))
print(isinstance(d, MyDerived))
print(isinstance(d, object))
print(isinstance(b, MyBase))
print(isinstance(b, MyDerived))
print(isinstance(b, object))
PYTHON
LECTURE 46
Today’s Agenda
• Multiple Inheritance
• The MRO Algorithm
• Hybrid Inheritance
• The Diamond Problem
Multiple Inheritance
class A:
# properties of class A
class B:
#properties of class B
class C(A,B):
# class C inheriting property of class A
# class C inheriting property of class B
# more properties of class C
Example
class A:
Output:
def m(self):
print("m of A called")
Why did m( ) of A
class B: got called ?
def m(self):
print("m of B called") This is because of a
special rule in
Python called MRO
class C(A,B):
pass
obj=C()
obj.m()
What Is MRO In Python ?
MRO RULE :
In the multiple inheritance scenario, any specified attribute is searched
first in the current class. If not found, the search continues into
parent classes, left-right fashion and then in depth-first
without searching same class twice.
Can We See This MRO ?
class A:
def m(self):
print("m of A called")
class B:
def m(self):
print("m of B called")
class C(A,B):
pass
print(C.mro())
Output
Another Way To See MRO ?
class A:
def m(self):
print("m of A called")
class B:
def m(self):
print("m of B called")
class C(A,B):
pass
print(C.__mro__)
Output
The Hybrid Inheritance
class A: obj=D()
def m1(self): obj.m1()
print("m1 of A called") obj.m2()
class B(A): obj.m3()
def m2(self):
print("m2 of B called")
class C(A):
def m3(self):
print("m3 of C called")
class D(B,C):
pass
Output:
The Diamond Problem
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called")
class C(A):
def m(self):
print("m of C called")
class D(C,B):
pass
Output:
Guess The Output
class A:
obj=D()
def m(self):
obj.m()
print("m of A called")
Why m() of C was called ?
class B(A):
pass MRO goes from left to right first
and then depth first. In our case
class C(A): Python will look for method m()
def m(self): in B but it won’t find it there .
Then it will search m() in C
print("m of C called")
before going to A. Since it finds
m() in C, it executes it dropping
class D(B,C): the further search
pass
Output:
Guess The Output
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called")
class C(A):
def m(self):
print("m of C called")
class D(B,C):
def m(self):
print("m of D called")
Output:
Guess The Output
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called")
class C(A):
def m(self):
print("m of C called")
class D(B,C):
def m(self):
print("m of D called")
B.m(self)
C.m(self)
A.m(self)
Output:
Guess The Output
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called") Why m() of A was called
A.m(self)
twice?
class C(A):
def m(self):
This is because we have
print("m of C called") called A.m(self) in both B
A.m(self) and C classes due to which
class D(B,C):
def m(self):
the method m() of A gets
print("m of D called") called 2 times
B.m(self)
C.m(self)
Output:
Using super( ) To Solve
The Previous Problem
class A:
def m(self): obj=D()
print("m of A called") obj.m()
class B(A):
def m(self):
print("m of B called")
super().m()
class C(A):
def m(self):
print("m of C called")
super().m()
class D(B,C):
def m(self):
print("m of D called")
super().m()
Output:
PYTHON
LECTURE 47
Today’s Agenda
• Operator Overloading
What Is
Operator Overloading?
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def __str__(self): Why did TypeError occur?
return f"x={self.x},y={self.y}"
TypeError was raised since
Python didn't know how to
p1=Point(10,20) add two Point objects
p2=Point(30,40) together.
p3=p1+p2
print(p3)
Output:
How To Perform
Operator Overloading?
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def __add__(self,other):
x=self.x+other.x
y=self.y+other.y
p=Point(x,y)
return p
def __str__(self):
return f"x={self.x},y={self.y}“
p1=Point(10,20)
p2=Point(30,40)
p3=p1+p2
print(p3)
Output:
Explanation
It searched for the magic method __add__() in our Point class since
the left side operand i.e. p1 is of Point class.
Finally addition was done and a new object p was returned which was
copied to p3
Guess The Output
class Point:
def __init__(self,x,y):
self.x=x
self.y=y
def __add__(self,other):
x=self.x+other.x
y=self.y+other.y
p=Point(x,y)
return p
def __str__(self):
return f"x={self.x},y={self.y}"
p1=Point(10,20)
p2=Point(30,40)
p3=p1+p2
print(p3)
p4=p1+p2+p3
print(p4)
Output:
Exercise
__init___() : This method should accept 2 arguments and initialize feet and
inches with it
__str__(): This method should return string representation of feet and inches
__add___() : This method should add 2 Distance objects and return another
Distance object as the result. While adding if sum of inches becomes >=12 then it
should be appropriately converted to feet
Solution
def __str__(self):
return f"feet={self.feet},inches={self.inches}“
Output:
Guess The Output ?
def __str__(self):
return f"feet={self.feet},inches={self.inches}“
Output:
Solution
Addition p1 + p2 p1.__add__(p2)
Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2 p1.__pow__(p2)
Division p1 / p2 p1.__truediv__(p2)
__str__(): This method should return string representation of name and price
__add___() : This method should add price of 2 Books and return the total price
Solution
def __add__(self,other):
totalprice=self.price+other.price
return totalprice
def __str__(self):
return f"name={self.name},price={self.price}"
Output:
Guess The Output ?
def __repr__(self):
return f"name={self.name},price={self.price}"
Output:
Why Did TypeError Occur ?
So Python called __add__() method of Book class since the left operand
is b1 which is object of class Book
Now Python used 800 as the calling object and b3 as argument so the
call became 800.__add__(b3).
So Python now looks for a method __add__() in int class which can add
an int and a book but it could not find such a method in int class which can
take Book object as argument .
Equal to p1 == p2 p1.__eq__(p2)
__init___() : This method should accept 2 arguments and initialize feet and
inches with it
__str__(): This method should return string representation of feet and inches
__eq___() : This method should compare 2 Distance objects and return True if
they are equal otherwise it should return False
Solution
-= p1-=p2 p1.__isub__(p2)
+= p1+=p2 p1.__iadd__(p2)
*= p1*=p2 p1.__imul__(p2)
/= p1/=p2 p1.__idiv__(p2)
%= p1%=p2 p1.__imod__(p2)
[] obj[0] obj.__getitem__(self,index)
• Exception Handling
• Introduction To Exception Handling
• Exception Handling Keywords
• Exception Handling Syntax
• Handling Multiple Exceptions
• Handling All Exceptions
What Is An Exception ?
try
except
else
raise
finally
Exception Handling Syntax
try: Remember !
In place of Exception I and
You do your operations here; Exception II , we have to use
the names of Exception
......................
classes in Python
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
Improved Version
Of Previous Code
Example:
A try statement may have more than one except clause for
different exceptions.
import math
try:
x=10/5
print(x)
ans=math.exp(3)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(20000)
print(ans)
except ZeroDivisionError:
print("Division by 0 exception occurred!")
except ArithmeticError:
print("Numeric calculation failed!")
Output:
Guess The Output !
import math
try:
x=10/5
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Guess The Output !
import math
try:
x=10/0
print(x)
ans=math.exp(20000)
print(ans)
except ArithmeticError:
print("Numeric calculation failed!")
except ZeroDivisionError:
print("Division by 0 exception occurred!")
Output:
Exercise
If the user enters a non integer value then ask him to enter only integers
If denominator is 0 , then ask him to input non-zero denominator
Repeat the process until correct input is given
Only if the inputs are correct then display their division and
terminate the code
Sample Output
Solution
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
Single except,
Multiple Exception
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except (ValueError,ZeroDivisionError):
print("Either input is incorrect or denominator is 0. Try
again!")
Sample Output
Handling All Exceptions
In this case for every exception this except clause will run
.
The only problem will be that we will never know the type
of exception that has occurred!
Exception Handling Syntax
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break
except:
print("Some problem occurred. Try again!")
Sample Output
PYTHON
LECTURE 49
Today’s Agenda
• Exception Handling
• Using Exception Object
• Getting Details Of Exception
• Raising An Exception
• Using finally Block
• Creating User Defined Exceptions
Using Exception Object
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except (ValueError,ZeroDivisionError) as e:
print(e)
Sample Output
Obtaining Exception Details
The variable type is the name of exception class, value is the instance of
exception class and traceback contains the complete trace of the
exception
Example
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except:
a,b,c=sys.exc_info()
print("Exception class:",a)
print("Exception message:",b)
print("Line number:",c.tb_lineno)
Sample Output
Obtaining Exception Details
Using traceback class
import traceback
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except:
print(traceback.format_exc())
Sample Output
Raising An Exception
Syntax:
raise ExceptionClassName
raise ExceptionClassName( message )
Exercise
If the user enters a non integer value then ask him to enter only integers
If denominator is 0 , then ask him to input non-zero denominator
If any of the numbers is negative or numerator is 0 then
display the message negative numbers not allowed
Repeat the process until correct input is given
Only if the inputs are correct then display their division and
terminate the code
Sample Output
Solution
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
if a<=0 or b<0:
raise Exception("Negative numbers not allowed!Try again")
c=a/b
print("Div is ",c)
break;
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
except Exception as e:
print(e)
The finally Block
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
c=a/b
print("Div is ",c)
break;
except ZeroDivisionError:
print("Denominator should not be zero")
finally:
print("Thank you for using the app!")
Output:
Creating User Defined
Exception
class NegativeNumberException(Exception):
pass
while(True):
try:
a=int(input("Input first no:"))
b=int(input("Input second no:"))
if a<=0 or b<0:
raise NegativeNumberException("Negative numbers are not
allowed!Try again")
c=a/b
print("Div is ",c)
break;
except ValueError:
print("Please input integers only! Try again")
except ZeroDivisionError:
print("Please input non-zero denominator")
except NegativeNumberException as e:
print(e)
PYTHON
LECTURE 50
Today’s Agenda
• What Is DBMS ?
• What Is SQL ?
What is Data?
What is Database ?
Introduction
What is Data?
What is a Database?
A database is a collection of inter-related data or information that is
organized so that it can easily be accessed, managed, and updated .
Let's also consider the Facebook. It needs to store, manipulate and present
data related to members, their friends, member activities, messages,
advertisements and lot more. Here also database is used
How Databases
Store The Data ?
Oracle
MySQL
MS SQL Server
SQLite
PostgreSQL
IBM DB2
Advantages:
Platform-independent
https://oracle.github.io/odpi/doc/installation.html
#windows
But before using pip , we must set it’s path by setting it’s
location in PATH environment variable
Installing cx_Oracle Using pip
This will display all the modules currently installed and will
show the name of cx_Oracle also
Verifying The Installation
PYTHON
LECTURE 51
Today’s Agenda
import cx_Oracle
Step 2-
Establishing The Connection
After importing the module ,we must open the connection to the
Oracle server.
cx_Oracle.connect( “connection_details”)
If there is any problem in connecting to the database , then this function throws the
exception called cx_Oracle.DatabaseError
Important Attributes/Methods Of
Connection Object
This object holds complete details of the connection and we can get
these details by calling it’s attributes or methods.
It can also hold the set of rows returned by the query and lets us
work with the records in that set, in sequence, one at a time.
cur=conn.cursor()
Important Attributes/Methods Of
Cursor Object
Syntax:
For example:
cur.execute('select * from allbooks')
The execute( ) Method
Example:
cur.close()
conn.close()
An Important Point!
The Cursor object holds all the rows it retrieved from the
database as tuples.
Execute the query to select name of the book and it’s price from the
table Allbooks
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks")
for x in cur:
print(x)
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB"
Exercise
import cx_Oracle
conn=None We will just have to unpack
cur=None each row of the tuple to get
try: the individual values
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks")
for name,price in cur:
print(name,price)
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB"
Using The Method fetchone( )
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks order by bookprice desc")
x=cur.fetchone()
if x is not None:
print(x)
Syntax:
cur.fetchall()
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks order by bookprice desc")
x=cur.fetchall()
print(x)
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Output
Exercise
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Select bookname,bookprice from allbooks")
booklist=cur.fetchall()
recnum=int(input(f"Enter the record number(1 to
{len(booklist)}):"))
Solution
It has 2 syntaxes:
After executing insert if we want to get the number of row inserted we can
use the cursor attribute rowcount
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Insert into allbooks values(116,'Python Web Prog','Python',500)")
n=cur.rowcount
print(n," row inserted")
conn.commit()
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
except (Exception) as ex:
print(ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Executing Dynamic Queries
Using position
Using name
Using bind variables
By Position
In this Insert query
:1,:2,:3 and :4 are
called bind variables
import cx_Oracle
and they will be
conn=None replaced with the
cur=None values of the actual
try: variables
id,name,subject and
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
price before the query
print("Connected successfully to the DB")
is sent for execution.
cur=conn.cursor() Also , parenthesis is
id=int(input("Enter bookid:")) required because
these values are sent
name=input("Enter bookname:")
as a tuple
subject=input("Enter subject:")
price=int(input("Enter bookprice:"))
cur.execute("Insert into allbooks
values(:1,:2,:3,:4)",(id,name,subject,price))
n=cur.rowcount
print(n," row inserted")
conn.commit()
Using bind variables
By Position
import cx_Oracle
conn=None
cur=None Here we have first packed
try: the variables id ,
name , subject and
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
price into a tuple
print("Connected successfully to the DB") called myvalues and
cur=conn.cursor() then we have passed it
as argument to the
id=int(input("Enter bookid:")) method execute( )
name=input("Enter bookname:")
subject=input("Enter subject:")
price=int(input("Enter bookprice:"))
myvalues=(id,name,subject,price)
cur.execute("Insert into allbooks values(:1,:2,:3,:4)",myvalues)
n=cur.rowcount
print(n," row inserted")
conn.commit()
Sample Output
Using bind variables
By Name
import cx_Oracle
In this Insert query
conn=None the bind variables
cur=None :bid , :bname ,:sub
try: and :amt have to be
replaced with
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB") replaced with the
values of the actual
cur=conn.cursor() variables
id=int(input("Enter bookid:")) id,name,subject and
name=input("Enter bookname:") price , by using
subject=input("Enter subject:") dictionary or
price=int(input("Enter bookprice:")) keyword arguments
cur.execute("Insert into allbooks
values(:bid,:bname,:sub,:amt)",bid=id,bname=name,sub=subje
ct,amt=price)
n=cur.rowcount
print(n," row inserted")
conn.commit()
Sample Output
Important Points About
bind variables
It has 2 syntaxes:
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Update allbooks set bookprice=500 where bookid=125 ")
n=cur.rowcount
print(n," rows updated")
conn.commit()
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
except (Exception) as ex:
print(ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Exercise
Sample Run 1
Sample Run 2
Solution
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
subject=input("Enter subject name:")
amount=int(input("Enter the amount to increase:"))
cur=conn.cursor()
cur.execute("Update allbooks set bookprice=bookprice+:1 where subject=:2",(amount,subject))
n=cur.rowcount
if n==0:
print("No rows updated")
else:
print(n, "rows updated")
conn.commit()
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
except (Exception) as ex:
print(ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Deleting Record
It has 2 syntaxes:
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
cur.execute("Delete from allbooks where bookid=131")
n=cur.rowcount
print(n," row deleted")
conn.commit()
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
except (Exception) as ex:
print(ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
Exercise
Sample Run 1
Sample Run 2
Solution
import cx_Oracle
conn=None
cur=None
try:
conn=cx_Oracle.connect("scott/tiger@Sachin-PC/orcl")
print("Connected successfully to the DB")
cur=conn.cursor()
subject=input("Enter subject name:")
cur.execute("Delete from allbooks where subject=:1",(subject,))
n=cur.rowcount
if n==0:
print("No rows deleted")
else:
print(n," rows deleted")
conn.commit()
except (cx_Oracle.DatabaseError)as ex:
print("Error in connecting to Oracle:",ex)
except (Exception) as ex:
print(ex)
finally:
if cur is not None:
cur.close()
print("Cursor closed successfully")
if conn is not None:
conn.close()
print("Disconnected successfully from the DB")
PYTHON
LECTURE 53
Today’s Agenda
• File Handling
• What Is File Handling ?
• What Is The Need Of File Handling ?
• Examples Where Files Are Used?
• Python’s Way Of Handling Files
• File Opening Modes
• Writing In A File
• Different Ways For Reading From A File
What Is File Handling ?
Mobile’s Phonebook
Computer/Mobile Games
Call Logs
Gallery In Mobile
Windows Registry
Steps Needed For File Handling
Syntax:
Mode Description
Mode Description
Example 1:
f = open("employees.txt", "r")
Example 2:
f = open("teams.txt", "w")
Example 3:
f = open("teams.txt", "a")
For example:
f = open("C:/Users/sachin/documents/README.txt", "w")
f = open(r"C:\Users\sachin\documents\README.txt", "w")
f.close()
The TextIOWrapper Class
Method Description
Reads the specified number of characters
from the file and returns them as string.
read([num])
If num is omitted then it reads the entire
file.
readline() Reads a single line and returns it as a string.
Reads the content of a file line by line and
readlines()
returns them as a list of strings.
Writes the string argument to the file and
write(str) returns the number of characters written to
the file.
Moves the file pointer to the given offset
seek(offset, origin)
from the origin.
Returns the current position of the file
tell()
pointer.
close() Closes the file
Exceptions Raised In
File Handling
Now ask the user to type a message and write it in the file .
Also properly handle every possible exception the code can throw
Sample Output
Solution
fin=None
try:
fin=open("d:\\message.txt","r")
text=fin.read()
print(text)
except FileNotFoundError as ex:
print("Could not open the file: ",ex)
finally:
if fin is not None:
fin.close()
print("File closed successfully")
Output:
Exercise
Now ask the user to continuously type messages and save them in the
file line by line.
Also properly handle every possible exception the code can throw
Sample Output
Solution
fout=None
try:
fout=open("d:\\message.txt","w")
text=input("Type your message and to stop just press ENTER on a newline\n")
lines=0
while True:
if text=="":
break
lines+=1
fout.write(text+"\n")
text=input()
finally:
if fout is not None:
fout.close()
print("File closed successfully")
Exercise
Now read and display the contents of the file line by line.
try:
fin=open("d:\\message.txt","r")
lines=0
while True:
text=fin.readline()
if text=="":
break
lines+=1
print(text,end="")
finally:
if fin is not None:
fin.close()
print("File closed successfully")
Using for Loop To
Read The File
The only point is that when we use for loop on the file
object , Python reads and returns one line at a time.
Exercise
Now read and display the contents of the file line by line.
fin=None
try:
fin=open("d:\\message.txt","r")
lines=0
for text in fin:
print(text,end="")
lines+=1
print("Total lines read are :",lines)
finally:
if fin is not None:
fin.close()
print("File closed successfully")