Python Notes
Python Notes
C SE, SRI TW
M
CHAPTER 1: Introduction
Python Name - Famous Tv Show Monty python's flying
circus. Python is
General-purpose
interpreted
interactive
high-level programming language
History:
Features:
Easy to learn
Easy to read
Easy to maintain
Broad standard library
Interactive mode
1
Ranj i th K umar. C SE, SRI TW
M
Portable
Extendable
Databases
GUI Programming
Scalable
Python supports functional and Structured programming
methods as well as OOP. It is also Used as a Scripting
Language or can be compiled to byte code for building large
applications. It provides high level dynamic datatype and
supports dynamic type checking. Python supports automatic
garbage collections and easily integrated with other
languages like C, C++, Java.
Use Case:
Shell scripting
Gaming programming
Windows development
Testing code
Web development
2
Ranj i th K umar. C SE, SRI TW
M
Special Features:
Versions of Python
CPython (Original)
Cython (Compatible for c program)
Jython (JVM based Code)
IronPython (C# .Net)
[Link] mode
[Link] mode
1. Interactive mode:
3
Ranj i th K umar. C SE, SRI TW
M
>>> 25+653+12.5
690.5
To exit from python prompt use exit function
>>> exit() or control+Z
2. Script mode:
Pycharm:
Installing Pycharm
To download PyCharm visit the website
[Link] and
Click the
"DOWNLOAD" link under the Community Section.
4
Ranj i th K umar. C SE, SRI TW
M
Features:
Be More Productive
Save time while PyCharm takes care of the routine. Focus on the
bigger things and embrace the keyboard-centric approach to
get the most of PyCharm’s many productivity features
5
Ranj i th K umar. C SE, SRI TW
M
Memory Operations
No declaration
Store values in variable name
Retrieve value
Delete variable (del)
Constants / arithmetic operations decide variable types
Example:
>>> 10
>>> a = 10
>>> del(a)
Types:
Int
Float
String
Boolean
Numbers:
- int (10)
- long (0122L) - in python3 no long datatype
- float (15.20)
- Complex (3.4j) - j might be lower case or upper case
- Type conversion
- int()
- float()
6
Ranj i th K umar. C SE, SRI TW
M
- long()
- complex()
Example:
a = int(10) print(b)
print(a) 10 10.56 -- automatically
b=
converts string into float
float(“10.56”) a+b
7
Ranj i th K umar. C SE, SRI TW
M
Chapter 3: Operators
Types of Operators:
Arithmetic Operators
Relational/Comparison Operators
Assignment Operators
Bitwise Operators
Logical Operators
Membership Operators
Identity Operators
Arithmetic Operators
Addition (+) Add two operands and unary plus
Subtraction (-) Subtract right operand from the left or
unary minus Multiply ( * ) Multiply two operands
Divide ( / ) Divide left operand by the right one (always
results into float)
Modulus ( % ) remainder of the division of left operand by the
right
Floor Division(//) division that results into whole number
adjusted to the left in the number line
Exponent ( ** ) left operand raised to the power of right
operand
Example:
8
Ranj i th K umar. C SE, SRI TW
M
Comparison Operator
These Operators compare the values on either sides of them and
decide the relation among them.
Equal (==)
Not equal (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
Example:
Ranj i th K umar. C SE, SRI TW
M
Assignment Operator
An Assignment Operator is the operator used to assign a new
value to a variable.
Assign ( = )
Add AND ( += )
Multiply AND ( *= )
Subtract AND ( -= )
Divide AND ( /= )
Modulus AND ( %= )
Exponent AND ( **= )
Example:
10
Ranj i th K umar. C SE, SRI TW
M
Bitwise Operator
Bitwise operator works on bits and performs bit-by-bit
operation bin() can be used to obtain binary representation
of an integer number.
11
Ranj i th K umar. C SE, SRI TW
M
Logical Operator
Membership Operator
These Operators are used to test whether a value or a variable
is found in a sequence (Lists, Tuples, Sets, Strings, Dictionaries).
13
Ranj i th K umar. C SE, SRI TW
M
Chapter 4: Sequences
Sequence Operations:
[Link]
[Link]
[Link]
[Link]
[Link]
1. List:
14
Ranj i th K umar. C SE, SRI TW
M
Similar to arrays in c (but arrays can store similar datatype)
Example:
Fruit = ['mango', 'apple', 'orange']
Operations:
[Link](elem) - To store the new element after the last
one
[Link](index, elem) - To define where you want to store
the value
[Link](list2)
[Link](elem)
[Link](elem)
[Link]()
[Link]()
Example 1:
Subjects = ['physics', 'Chemistry', 'Maths'] Games =
['Football', 'Cricket', 'Tennis'] [Link]('History')
#append
operation print(Subjects)
[Link](1,'History') # TO insert into the second
position
print(Subjects)
[Link](Games)
print(Subjects)
[Link]('Chemistry')
print(Subjects)
[Link]() # it prints the elements in the
reverse order
print(Subjects)
print(Subjects + Games) # Similar
to [Link](Games)
# Repeat the list twice
15
Ranj i th K umar. C SE, SRI TW
M
print(Subject * 2)
Example 2:
list = [ 'abcd', 786, 2.23, 'john', 70.2] tinylist = [123,
'john']
print (list) # Prints complete list
['abcd', 786, 2.23, 'john', 70.2]
print (list[0]) # Prints first element of the list
abcd
print (list[1:3]) # Prints elements starting from 2nd till
3rd
[786, 2.23]
print (list[2:]) # Prints elements starting from 3rd
element
[2.23, 'john', 70.2]
print (tinylist * 2) # Prints list two times
[123, 'john', 123, 'john']
print (list + tinylist) # Prints concatenated lists
['abcd', 786, 2.23, 'john', 70.2, 123, 'john'] del list[2]
print(list) [Link]("rahul")
print(list)
2. Strings:
16
Ranj i th K umar. C SE, SRI TW
M
Example:
Fruit = 'Mango'
Operations:
slicing - string[range]
Updating - string[range] + 'x'
Concatenation - String 1 +
String 2 Repetition - String 1 * 2
Membership - In, Not in
Reverse - String[:-1]
stg = 'Keep the blue flag flying high'
print(stg. len ()) - To print length of the
characters print([Link]('b')) - To print index
value of character 'b'
print([Link]('f')) - To check number of times
character 'f' repeated
print(stg[0:4]) - To print first 4 characters (4 is
ignored) print(stg[::-1]) - To reverse the string
print([Link]()) - To print in upper case
print(stg * 2) - To print the statements
twice print(stg + 'XXXX') - To
concatenate two strings
Membership testing:
if 'P' in stg:
print('It is an element')
Example:
name = 'My name is XXXX'
print (name)
My name is XXXX
name
17
Ranj i th K umar. C SE, SRI TW
M
'My name is XXXX' -- it represents variable type
a = 10
a
10
b = float(10) b
10.0
c = 10L
c
10L
type (c) - to display variable type
Substring:
name [0] - it prints 1st character from the
string 'M'
name[1] - it prints last character from
the string 'i'
name[2] - It prints empty
string ''
name[0:2] - 0-inclusive, 2-exclusive
'My'
name[0:3]
'My'
name[3:7]
'name'
name[-4:-1]
‘XXX'
name[-4:]
'XXXX'
b = '\x10' b
'\x10'
print(b)
18
Ranj i th K umar. C SE, SRI TW
M
b = 'Hello World\x11' b
'Hello World\x11'
3. Dictionaries:
Unordered collection of key-value pair
It is generally used when we have huge amount of data
Denoted by {}
Example:
d = {1:'value','key':2}
print(type(d)) print("d[1]=",
d[1])
Operations:
Length
del
membership testing
Demo:
Student = {'Name':'XXXX', 'Age':33} print(Student)
print(Student['Name']) - To print value of 'Name'
key Student['Gender'] = 'Male' - To add one more key-
value pair to existing dic
print(Student)
[Link]('Name') -To remove name key
value pair [Link]() -To clear all key value in a
dict or del a dict
Student['Name'] = 'Santhosh' - To change the name value
4. Tuples:
19
Ranj i th K umar. C SE, SRI TW
M
A tuple is a sequence of immutable Python objects
The tuples cannot be changed
Tuples are faster than list
Operations:
Index -[Link]()
Sclicing -Tuple[range]
Concatenation -
Tuple1+Tuple2 Repetition -
Tuple * 2
Count -[Link](elem)
Example:
Cricket = ('Dhoni', 'Sachin', 'Virot') Football =
('Hazard', 'Lampard', 'Terry')
[Link]('Dravid')
print(Football) - Error because it is
updatable # indexing
print(Cricket[1])
print([Link]('Virot')) - To print particular element
index
# Slicing
print(Football[0:2]) - 0 - Starting, 2 - means
actually (2-1)
# Concatenation
FoodCric = Football + Cricket
print(FoodCric)
# Repetition
print(Cricket * 2) #
count
print([Link]('Hazard'))
20
Ranj i th K umar. C SE, SRI TW
M
Question:
Football = [('Dhoni', 'Sachin', 'Virot'),('Hazard', 'Lampard', 'Terry')]
In the above example how the indexing will be created
Football is a List which contains 2 tuples
Football list index is 0 and 1
0 - tuples index ( 0, 1, 2)
1 - tuple index (0,1,2)
Example:
Points = [(1,2),(3,4),(6,7)]
[Link]((5,6))
print(Points)
[Link]((1,2))
print(Points)
5. Sets:
Example:
Fruit = {'Mango','Apple','Grapes'}
Operations:
21
Ranj i th K umar. C SE, SRI TW
M
Slicing
Add
element
clear
copy
Difference
Discard
Remove
Intersectio
n
Set1 = {1,2,3,4,5,6,6} - If we print this, '6' is
printed only once
Set2 = {5,6,7,8,9,10}
print(Set1)
Set1 = {1,2,3,4,5,6}
[Link](4) - To discard element 4
print(Set1)
print(Set1 | Set2) - Union Operation(Adding) print(Set1
& Set2) - Intersection (prints common elements
print(Set1 - Set2) - Difference
print(Set1 ^ Set2) - Symmetric difference (Except
common
elements in bothsets)
22
Ranj i th K umar. C SE, SRI TW
M
Example:
salary + bonus = Total salary
-> emp1 salary + bonus =
Total salary -> emp2 salary +
bonus = Total salary -> emp3
Write logic to calculate total salary of all employees
Types of Loops
[Link]
[Link]
[Link]
23
Ranj i th K umar. C SE, SRI TW
M
1. While:
Indefinite or conditional loops.
It will keep iterating until certain conditions are met
There is no guarantee ahead of time regarding how
many times the loop will iterate.
Syntax:
while expression:
<statements>
Example:
count = 0
while count < 9:
print("Number: ", count)
count = count + 1;
print("Print the Numbers")
When you don't know how many iterations are required, use while
loop.
2. For Loop:
Syntax:
for <variable> in <range>:
<statement 1;>
24
Ranj i th K umar. C SE, SRI TW
M
<statement 2;>
<statement n;>
Example 1:
Fruits = ["Mango", "Apple", "Orangle"] for fruit in
Fruits:
print ("Current fruit is: ", fruit) print("Good bye")
Example 2:
num = int(input("Number: "))
factorial = 1
if num < 0:
print("must be positive") elif
num == 0:
print("factorial = 1") else:
for i in range(1, num+1): factorial =
factorial * i
print(factorial)
3. Nested Loop:
print("Welcome to ATM")
25
Ranj i th K umar. C SE, SRI TW
M
restart = ('Y') chances
=3
balance = 67.14 while
chances >= 0:
pin = int(input('Please enter your 4 digit pin:')) if pin ==
(1234):
print('You entered your Pin Correctly \n') while restart
not in ('n', 'no', 'No','N'):
print("Please press 1 for your Balance \n") print("Please
press 2 for your Withdrawl \n") print("Please press 3 for
your Pay in \n") print("Please press 4 for your Return Card \
n") option = int (input ('What would you like to
choose?'))
if option == 1:
print('Your balance is Rs.', balance,'\n') restart =
input('Would you like to go back?') if restart in ('n', 'no',
'No','N'):
print('Thank you') break
elif option == 2: option2 =
('Y')
Withdrawl = float(input('How much would you like to withdraw? \
n Rs.10/Rs.20/Rs.40/Rs.60/Rs.80/Rs.100')
if Withdrawl in [10,20,40,60,80,100]: balance
= balance - Withdrawl
print("\n your balance is now Rs.", balance) if restart
in ('n', 'no', 'No','N'):
print('Thank you') break
elif Withdrawl != [10,20,40,60,80,100]: print("Invalid
Amount, please Re-try\n") restart = ('Y')
elif Withdrawl == 1:
Withdrawl = float(input('Please enter
desired amount:'))
elif option == 3:
Pay_in = float(input("How much would you like to pay
in?"))
balance = balance + Pay_in
print ("Your Balance is now Rs.", balance)
26
Ranj i th K umar. C SE, SRI TW
M
restart = input("Would you like to go back?") if restart
in ('n', 'no', 'No','N'):
print('Thank you') break
elif option == 4:
print("Please wait while your card is
returned...\n")
print("Thank you for your service") break
else:
Example 2:
count = 1
for i in range(10): print
(str(i) * i)
for j in range(0, i): count =
count +1
Output:
1
22
333
4444
55555
666666
7777777
88888888
999999999
27
Ranj i th K umar. C SE, SRI TW
M
Chapter 6: Functions
Built-in functions:
Python has many built-in function, you should know what
task that function performs
L1 = [1,2,3,4,5]
len(L1) - It writes number of elements in a list
5
sum(L1) - prints sum of L1
15
print(L1)
[1, 2, 3, 4, 5]
L2 = [5,3,4,2,1]
[Link]()
print(L2)
[1, 2, 3, 4, 5] - the input is changed
User-defined functions:
Demo 1
def add1(a):
----- b = a + 1 # indents
-------return b
28
Ranj i th K umar. C SE, SRI TW
M
# call the function
add1(5)
6
def add1(a):
... b = a+1
... return b
...
add1(5)
6
# Empty block
def nowork():
...
...
File "<stdin>", line 3
^
31
Ranj i th K umar. C SE, SRI TW
M
add1(2)
2 plus 1 equals 3 -- Output of Print
3 -- Output of return
Example:
pets = ('Dogs', 'Cats', 'Turtles', 'Rabbits')
# Collecting Arguments
def Ast(*names):
... for name in names:
... print(name)
...
Ast("XXXX","Santhosh","Monica") XXXX
32
Ranj i th K umar. C SE, SRI TW
M
Santhosh
Monica
Ast("Danie","Felix") Danie
Felix
Ast("Dolly",2)
Dolly
2
33
Ranj i th K umar. C SE, SRI TW
M
Chapter 7: FILES
Python too supports file handling and allows users to handle files
i.e., to read and write files, along with many other file handling
options, to operate on files. We can control what kind of
operations we can perform on a file with the mode parameter of
openfunction.
Syntax:
fileobject = open(filename, mode)
35
Ranj i th K umar. C SE, SRI TW
M
the end of the file if the file exists. That is, the file is
in the append mode. If the file does not exist, it creates
a new file for writing.
Opens a file for both reading and writing in binary
rb+ format. The file pointer placed at the beginning of the
file.
Opens a file for both writing and reading in binary format.
wb Overwrites the existing file if the file exists. If the file
+ does not exist, creates a new file for reading and
writing.
Opens a file for both appending and reading in
binary format. The file pointer is at the end of the file if
ab the file exists. The file opens in the append mode. If
+ the file does not exist, it creates a new file for reading
and writing
The file object attributes: Once a file is opened and you have
one file object, we can get various information related to that
file. A list of all attributes related to file object is here,
Attribute Description
[Link] Returns true if file is closed, false otherwise.
[Link] Returns access mode with which file was
opened.
[Link] Returns name of the file.
Returns false if space explicitly required with
[Link]
ce print, true otherwise.
Example:
# Open a file
fileo = open("[Link]", "wb")
print "Name of the file: ", [Link] print
"Closed or not ", [Link] print "Opening
mode: ", [Link]
36
Ranj i th K umar. C SE, SRI TW
M
Name of the file: [Link]
Closed or not: False
37
Ranj i th K umar. C SE, SRI TW
M
Opening mode: wb
Syntax:[Link](); Example:
# Open a file
fileo = open("[Link]", "wb")
print "Name of the file: ", [Link] # Close
opened file
[Link]()
Sample program:
import [Link]
import sys
f1=input("enter a source file").strip()
f2=input("enter a target file").strip() if
[Link](f2):
print(f2 +"already exists")
infile=open(f1,"r")
outfile=open(f2,"w")
countlines=countcharacters=0 for
line in infile:
countlines+=1 countcharacters+=len(line)
38
Ranj i th K umar. C SE, SRI TW
M
[Link](line)
print(countlines, "lines and",countcharacters,"characters copied")
print("Contents copied from file 1 to file 2") [Link]()
[Link]()
Syntax: [Link](string);
Here, passed parameter is the content to be written into the
opened file.
Example:
# Open a file
fileo = open("[Link]", "wb") [Link]("Python is a
great language!!\n"); # Close opend file
[Link]()
Result:
Python is a great language!!
39
Ranj i th K umar. C SE, SRI TW
M
Here, passed parameter is the number of bytes to be read from
the opened file. This method starts reading from the beginning of
the file and if count is missing, then it tries to read as much as
possible, maybe until the end of file.
Example:
# Open a file
fileo = open("[Link]", "r+") str =
[Link](10);
print "Read String is : ", str # Close
opend file [Link]()
Result:
Read String is : Python is
40