PYTHON
UNIT I
MODULE I: Features of python
Phases of Program
Problem Definition
For eg : Add two numbers
Algorithm
Input a=10
Input b =20
sum =a+b
Flowchart
Coding (Python,C,C ++,Java)
Testing
Identifiers
A python identifier is a name used to identify a
variable,function,class ,module or any object.
Python is a case senstive language.
Following are the rules for naming an Identifier in
python.
Identifier can be a combination of letters in
lowercase(a to z) or upper case (A to Z) or digits (0
to 9) or an underscore(_).
Reserved keyword cannot be used as an identifier.
Identifiers cannot begin with digits . For eg 2count,
5student
Special symbols like @,!,#,$,% cannot be used in an
identifier.
For eg: #sum, total@
Identifier can be of any length.
Valid Identifiers Example:
person,name,max_count,total
Reserved Keywords
Keywords reserved by the Programming language
and prevent the user or the programmer from using
it as an identifier in a program.
Variables
Variables are reserved memory location to store
values.
Based on the value assigned interpreter assign
memory.
Python variable do not need explicit declaration to
reserve memory space. Declaration happens
automatically when you assign value to a variable
Sign “=“ is used to assign values to a variable.
a=10
b=12.2
name=“Rahul”
a=b=c=1
a, b , c= 1 , 2.2 , ”ram”
Reading the input
Python provides two built-in functions to read a line
of text from standard input which default comes
from the keyboard.
Two Built in functions: raw_input and input
raw_input function functions reads one line from
standard input and return it as string.
Raw_input function is not supported by python 3.
Raw_input function reads one line from standard
input and return it as a string.
Input function is equivalent to raw_input, except
that it assumes the input is a valid python
expression and returns the evaluated result to you.
n=input(“enter a number:”)
print(“The number is:”,n)
o The function used to print output on a screen is
print function .
o The print function converts the expressions you pass
into a string and writes the result into standard
output.
Operators
Used to manipulate the value of operands.
Consider the operation a=b+c , here a,b ,c are the
operands and +,= are called the operators.
Following are the type of operators supported by
python
Arithmetic operators
Comparsion(Relational) operators
Assignment operators
Logical operators
Bitwise operators
Membership operators
Identity operators
Arithmetic operators
Arithmetic operators are used for performing basic
arithmetic operations.
n=input("enter the first number")
m=input("enter the second number")
x=int(n) // convert to integer value
y=int(m) // convert to integer value
sum=x+y // + is addition operation
sub=x-y // - is sub operation
div=x/y // / is division operation
mod=x%y // % is modulus operation
exp=x**2 // ** is exp operation
floor=x//y // // is floor div
print ("result is:",sum)
print ("result is:",sub)
print("result is:",div)
print("result is",mod)
print("result is:",exp)
print("result is:",floor)
Comparsion(Relational) operators
Compares the value on either sides of them and
decide the relation among them.
• n=input("enter the first number")
• m=input("enter the second number")
x=int(n)
y=int(m)
print("x==y is:",(x==y))
print("x!=y is:",(x!=y))
print("x<y is:",(x<y))
print("x>y is:",(x>y))
print("x<=y is:",(x<=y))
print("x>=y is:",(x>=y))
Assignment Operators
a,b=10,3
a+=b // a=a+b
print(a)
a,b=10,3
a-=b // a=a-b
print(a)
a,b=10,3
a*=b // a=a*b
print(a)
a,b=15,3
a/=b // a=a/b
print(a)
a,b=15,5
a%=b // a=a%b
print(a)
a,b=10,2
a**=b // a=a**b
print(a)
a,b=10,3
a//=b // a=a//b
print(a)
N=5
M=2
X=INT(N) //CONVERT STRING INTO INTEGER
TYPE :NUMBERS
Y=INT(M) //CONVERT STRING INTO INTEGER
TYPE :NUMBERS
A,B=10,3
A+=B A=A+B
Bitwise operators
Number system
• The number system having just these two digits – 0
and 1 – is called binary number system.
• In any binary number, the rightmost digit is
called least significant bit (LSB) and leftmost
digit is called most significant bit (MSB).
Binary number to decimal
Decimal to Binary
Binary AND and OR
Binary XOR
X Y XOR
T T F
T F T
F T T
F F F
Binary AND
a,b=60,2 a= 0011 1100
print(a&b) b=0000 0010
0000 0000 -> 0
Binary OR
a,b=60,2 a= 0011 1100
print(a|b) b=0000 0010
00 11 1110
00 11 1110
=0*2^7+0*2^6+1*2^5+1*2^4+1*2^3+1*2^2+1*2^1
+0*2^o
=0+0+32+16+8+4+2+0
=62
Binary XOR
a,b=60,2 a= 0011 1100
print(a|b) b=0000 0010
0011 1 1 1 0
Binary ones compliment
a=60 a= 0011 1100
print(~a) 1100 0011
Filp the bit from 0 to 1/ /1 to 0
~a=-a-1
-61
0011 1101
1 1 00 0010
1
110 0 001 1
Bitwise left
a,b=60,2
print(a<<b) ->240
0 0 1 1 1 1 0 0->60
1 1 1 1 0 0 0 0 ->240
1 1 1 1 00 00
Bitwise Right
a,b=60,2
print(a>>b) ->15
0 0 1 1 1 1 00
0 0 0 0 1 1 1 1 -> 15
Logical operators
a,b,c,d=10,5,2,1
print((a>b)and(c>d)) ->True
a,b,c,d=10,5,2,1
print((a>b)or(c<d)) ->True
a,b=10,5
print(not(a>b)) ->False
Membership operators
g='rohit'
print('h' in g) -> True
g='rohit'
print('f' in g) -> False
g='rohit'
print('f' not in g) -> True
Identity operators
a,b,c=10,10,5
print(a is b) -> True
a,b,c=10,10,5
print(a is c) ->False
a,b,c=10,10,5
print(a is not c) ->True
a,b,c=10,10,5
print(a is not b) ->False
Python Data Types
Numbers
String
List
Tuple
Set
Dictionary
Numbers
Number data type store numeric value.
Eg: a=20, b=10
We can delete single or multiple object by using del
statement
del a,b //used to delete objects
Python support four basic numerical data type
Int [integers]
Long int [ octal /hexadecimal numbers]
Float [floating point real values]
Complex[complex numbers]
Mathematical functions
1) a=-10
s=abs(a)
print(s) ->10
2) import math
a=25
s=math.sqrt(a)
print(s) ->5
3) import math
a=32.3
s=math.ceil(a)
print(s) -> 33
4) import math
a=32.3
s=math.floor(a)
print(s) ->32
5) a,b=3,2
s=pow(a,b)
print(s) ->9
6) a=2
s=math.exp(a)
print(s) -> 7.389056
7) import math
a=2
s=math.log(a)
print(s) ->0.693147
8) import math
a=2
s=math.log10(a)
print(s) ->0.301029953
9) a,b,c= 10,2,3
s=max(a,b,c)
print(s) ->10
10) a,b,c=10,2,3
s=min(a,b,c)
print(s) ->2
11) a=10.2385678
s=round(a,2)
print(s) ->10.24
Python number method modf() returns the
fractional and integer parts of x in a two-item tuple.
Both parts have the same sign as x. The integer part
is returned as a float.
12) import math
a=10.2385678
s=(math.modf(a))
print(s) -> (0.2385678,10.0)
Trigonometric Functions
import math
print(math.sin(90))
print(math.cos(90))
print(math.tan(90))
print(math.asin(1))
print(math.acos(1))
print(math.tan(1))
print(math.atan2(2,3))
print(math.hypot(3,4))
print(math.degrees(90))
print(math.radians(90))
STRINGS
String in Python are identified as contiguous set of
characters represented in the quotation marks.
In python string is represented as pair of single
quotes/double quotes.
Subsets of string can be taken using the slice
operator { [] and [:] } with indexes starting at 0 in
the beginning of the string and ending at -1.
The plus(+) sign is the concatenation operator and
(*) is the repetition operator.
str="welcome to python programming"
print(str) -> welcome to python programming
print(str[0]) ->w
print(str[11:17]) ->python
print(str[11:]) ->python programming
print(str*2) -> welcome to python programming
welcome to python programming
print(str+'world')-> welcome to python programming
world
str="geeksforgeeks"
print(str) ->geeksforgeeks
print(str[3:6]) ->ksf
print(str[-1]) ->s
print(str[0]) ->g
print(str[2:-4]) ->eksforg
print(str[-7:-2]) ->orgee
String Formatting Functions
len(string)
Function used to return the length of the string
s=“welcome to python”
print(“length of the string is”, len(s))
lower()
Return a copy of string in which all uppercase
alphabets in a string is converted to lowercase one.
s=“WELCOME TO PYTHON”
print(s.lower())
upper()
Return a copy of string in which all lowercase
alphabets in a string is converted to upper one.
s=“welcome to python”
print(s.upper())
swapcase()
Return a copy of string in which case of all the
alphabets are swapped. Lower case are converted to
upper case and vice versa.
s=WELcome To C
print(s.swapcase())
capitalize()
Return a copy of the string with only its first
character capitalized.
s=“welcome To c”
print(s.capitalize())
title()
Return a copy of the string in which first characters of
all the words are capitalized.
s=“welcome to python”
print(s.title())
lstrip()
Return a copy of the string in which all the characters
have been stripped from the beginning. The default
character is whitespaces.
s=“ welcome to python”
print(s.lstrip()) ->welcome to python
s=“$$$$$ welcome to python”
print(s.lstrip(‘$’) -> welcome to python
s=“welcome to python”
print(s.lstrip(‘welcome’) ->to python
rstrip()
Method returns a copy of the string with trailing
characters removed (based on the string argument
passed). If no argument is passed, it removes trailing
spaces.
str="welcome to python"
print(str.rstrip(‘noth')) ->welcome to py
str="welcome to python"
print(str.rstrip('th')) ->welcome to python
str=“welcome to python ******”
print(str.rstrip(‘*”))-> welcome to python
str=“welcome to pythonnnnnnn”
print(str.rstrip(‘n’))-> welcome to pytho
strip()
Inbuilt function in Python programming language
that returns a copy of the string with both leading
and trailing characters removed (based on the string
argument passed).
str="*********welcome to python**********"
print(str.strip('*')) -> welcome to python
str=“the great rohit sharma was the”
print(str.strip(‘the’))->great rohit sharma was
str1="geene for meene"
str2="eneg"
print(str1.strip(str2)) -> for m
max()
Inbuilt function in Python programming language
that returns the highest alphabetical
character in a string.
str1="rahul"
print(max(str1)) -> u
min()
Inbuilt function in Python programming language
that returns the minimum alphabetical
character in a string.
str1="rahul"
print(min(str1)) -> a
isdigit()
The isdigit() method returns “True” if all characters
in the string are digits, Otherwise, It returns “False”.
str1="rahul"
print(str1.isdigit()) ->False
str2='134565'
print(str2.isdigit()) -> True
isalpha()
Returns “True” if all characters in the string are
alphabets, Otherwise, It returns “False”.
str1="rahul"
print(str1.isalpha())-> True
str2='rahul134'
print(str2.isalpha()) -> False
islower ()
This methods returns “True” if all characters in the
string are lowercase, Otherwise, It returns “False”.
s='Welcome to python'
print(s. islower()) -> False
s='welcome to python'
print(s.islower()) -> True
isspace()
This method returns true if there are only
whitespace characters in the string and there is at
least one character, false otherwise.
str1="welcome to c"
print(str1.isspace()) -> False
str2=“ “
print(str2.isspace()) ->True
isupper()
This method returns True if all the characters are in
upper case, otherwise False.
str=“welcome to python
print(str.isupper()) -> False
str=“WELCOME TO PYTHON”
print(str.isupper()) ->True
istitle()
This method returns true if the string is a titlecased
string and there is at least one character, for example
uppercase characters may only follow uncased
characters and lowercase characters only cased
ones.It returns false otherwise.
str1=“Welcome To Python
print(str1.istitle()) -> True
str2=“welcome to python”
print(str2.istitle()) -> False
rfind()
• The rfind() method finds the last occurrence of the
specified value.
• rfind() method returns -1 if the value is not found.
string.rfind(value, start, end)
Value: Searched item.
Start: Optional. where to start the search.Default is
zero
End: Optional. where to end the search.Default is to
end of the string.
str1="Welcome To Python"
print(str1.rfind('o')) ->15
str1="Welcome To Python"
print(str1.rfind('o',0,-1)) ->15
str1="Welcome To Python"
print(str1.rfind('o',5,10)) ->9
str1="Welcome To Python”
print(str1.rfind('f')) -> -1
rindex()
• The rindex() method finds the last occurrence of the specified value.
• The rindex() method raises an exception if the value is not found.
string.rindex(value, start, end)
Value: Searched item.
Start: Optional. where to start the search.Default is zero
End: Optional. where to end the search.Default is to end of the string.
str1="Welcome To Python"
print(str1.rindex('o')) ->15
str1="Welcome To Python"
print(str1.rindex('o',0,-1)) ->15
str1="Welcome To Python"
print(str1.rindex('o',5,10)) ->9
str1="Welcome To Python”
print(str1.index('f')) -> substring not found
center()
The center() method will center align the string,
using a specified character.
string.center(length, character)
Length : The length of the returned string
Character: Optional. The character to fill the missing
space on each side. Default is “ ”(space)
str1="Welcome To Python"
print(str1.center(21,'*'))-> **Welcome To Python**
ljust()
The method will left align the string, using a specified
character (space is default) as the fill character.
string.ljust(length, character)
str1="Welcome To Python"
print(str1.rjust(25,'*')) ->Welcome To Python********
rjust()
The method will right align the string, using a
specified character (space is default) as the fill
character.
string.ljust(length, character)
str1="Welcome To Python"
print(str1.rjust(25,'*')) ->********Welcome To Python
startswith()
The startswith() method returns True if the string starts
with the specified value, otherwise False.
string.startswith(value, start, end)
Value : The value to check if the string starts with .
Start : An Integer specifying at which position to start the
search
end : An Integer specifying at which position to end the
search
str1="welcome to python"
print( str1.startswith('w')) -> True
str1="welcome to python"
print( str1.startswith('c',3,6)) -> True
str1=“welcome to python”
Print(str1.startswith(‘t’,9,11)-> False
endswith()
The endswith() method returns True if the string starts
with the specified value, otherwise False.
string.endswith(value, start, end)
Value : The value to check if the string starts with .
Start : An Integer specifying at which position to start the
search
end : An Integer specifying at which position to end the
search
str1="welcome to python"
print( str1.endswith('n')) -> True
str1=“welcome to python”
print(str1.endswith(‘o’)) -> False
str1="welcome to python"
print( str1.endswith('o',11,-1)) -> True
count()
The count() method returns the number of times a
specified value appears in the string.
string.count(value, start, end)
str1="welcome to python"
print(str1.count('o')) -> 3
str1="welcome to python"
print(str1.count('f')) -> 0
str1="welcome to python"
print(str1.count('o',0,10)) -> 2
zfill()
• The zfill() method adds zeros (0) at the beginning of
the string, until it reaches the specified length.
string.zfill(len)
str1="welcome to python"
print(str1.zfill(20))-> 000welcome to python
str1="welcome to python“
print(str1.zfill(30)) -> 0000000000000welcome to
python
LIST
List is an ordered sequence of items.
One of the most used data type in python
Flexible data type
All items in a list do not need to be of same type.
In list items are seperated by commas and enclosed
within brackets [].
The value stored in a list can be accessed using the
slice operator ([],[:]) with indices starting at ‘0’ and
ending at ending with ‘-1’
‘+’ is the list concatentaion operator.
‘*’ is the repetition operator.
list1=['abc',22,22.05]
list2=['cde',32,23.05]
print(list1) -> ['abc', 22, 22.05]
print(list2) -> ['cde', 32, 23.05]
print(list1[0]) -> [abc]
print(list1[-1]) -> [22.05]
print(list1[0:-1]) -> ['abc', 22]
print(list2*2) -> ['cde', 32, 23.05, 'cde', 32, 23.05]
print(list1+list2) -> ['abc', 22, 22.05, 'cde', 32, 23.05]
List Functions
len()
Gives the total length of list.
list1=['abc',22,22.05]
print(len(list1)) -> 3
max()
Returns maximum value from the list.
list1=[12,18,20]
print(max(list1)) -> 20
min()
Returns minimum value from the list.
list1=[12,18,20]
print(min(list1)) -> 12
pop()
• The pop() method removes the element at the
specified position.
• By default removes last item.
list1=[23,45,62]
list1.pop()
print(list1) ->[23,45]
list1=[23,45,62]
list1.pop(1)
print(list1) ->[23,62]
clear()
Removes all items from a list.
list1=[23,45,62]
list1.clear()
print(list1) ->[]
Tuple
• Similar to list
• Main difference between list and tuple are list are
enclosed in square brackets([]) and their elements
and size can be changed.
• Tuple are enclosed in parentheses and cannot be
updated.
s1=('abc','cde',23,45.03)
s2=('pqr','fgh',34,24.45)
print(s1) -> ('abc', 'cde', 23, 45.03)
print(s2) -> ('pqr', 'fgh', 34, 24.45)
print(s1[1:-1])-> ('cde', 23)
print(s2[0:2])-> ('pqr', 'fgh')
print(2*s1)-> ('abc', 'cde', 23, 45.03, 'abc', 'cde', 23,
45.03)
print(s1+s2)-> ('abc', 'cde', 23, 45.03, 'pqr', 'fgh', 34,
24.45)
Built in tuple functions
Len()
Returns total length of the tuple.
s1=('abc','cde',34,56.07)
print(len(s1)) ->4
Min()
Returns items from the tuple with minimum value.
s1=(2,4,5,6)
print(min(s1)) ->2
Max()
Returns item from the tuple with maximum value
s1=(2,4,5,6)
print(max(s1)) ->6
SET
• Set is an unordered sequence of items.
• In set items are seperated by commas and enclosed
within brackets({ }) .
• No duplicate elements
SET FUNCTIONS
len()
Returns length of the set.
s={23,34,21,12}
print(len(s)) ->4
max()
Returns items from the set with maximum value.
s={23,34,21,12}
print(max(s)) ->34
Min()
Returns items from the set with minimum value.
s={23,34,21,12}
print(min(s)) ->12
sum()
Returns sum of all items in the list.
s={1,2,3,4,5}
print(sum(s)) ->15
any()
Returns true ,if set contain atleast one item ,False
otherwise.
s={12,23,45,23}
print(any(s)) ->True
s={}
print(any(s)) ->false
all()
The all() function returns True if all items are true,
otherwise it returns False.
set = {True, True, True}
print(all(set)) ->True
set = {True, True, False}
print(all(set)) ->False
Set methods
add()
• The add() method adds an element to the set.
• If the element already exists, the add() method does
not add the element.
s = {23,45,67,89}
s.add(24)
print(s) -> {67, 45, 23, 24, 89}
s = {23,45,67,89}
s.add(23)
print(s) ->{89, 67, 45, 23}
Remove()
• The remove() method removes the specified element
from the set.
• remove() method will raise an error if the specified
item does not exist
s = {23,45,67,89}
s.remove(23)
print(s) -> {89, 67, 45}
s = {23,45,67,89}
s.remove(32)
print(set) -> KeyError: 32
discard()
• The discard() method removes the specified item
from the set.
• No error
s = {23,45,67,89}
s.discard(23)
print(s) -> {89, 67, 45}
s = {23,45,67,89}
s.discard(21)
print(s) -> {89, 67, 45, 23}
pop()
The pop() method removes a random item from the
set.
set.pop()
s={12,34,23,45}
s.pop()
print(s) -> 12,23,45
union()
Return a set that contains all items from both sets,
duplicates are excluded.
s1={12,34,23,45,11}
s2={12,16,17}
s3=s1.union(s2)
print(s3) -> {16, 17, 34, 23, 11, 12, 45}
s1={12,34,23,45,11}
s2={12,16,17}
s3={2,3,4}
s4=s1.union(s2,s3) ->{34, 2, 3, 4, 11, 12, 45, 16, 17, 23}
update()
The update() method updates the current set, by
adding items from another set.
s1={12,34,23,45,11}
s2={12,16,17}
s1.update(s2)
print(s1) -> {34, 11, 12, 45, 16, 17, 23}
Intersection()
The intersection() method returns a set that contains
the similarity between two or more sets.
s1={12,34,23,45,11}
s2={12,16,17}
s3=s1.intersection(s2)
print(s3) -> {12}
Difference()
The difference() method returns a set that contains
the difference between two sets.
s1={12,34,23,45,11}
s2={12,16,17}
s3=s1.difference(s2)
print(s3) -> {34, 11, 45, 23}
isdisjoint()
Method returns True if none of the items are present
in both sets, otherwise it returns False.
s1={12,34,23,45,11}
s2={12,16,17}
s3=s1.isdisjoint(s2)
print(s3) ->False
s1={12,34,23,45,11}
s2={19,16,17}
s3=s1.isdisjoint(s2)
print(s3) ->True
issubset()
Method returns True if all items in the set exists in
the specified set, otherwise it retuns False.
s1={12,34,23,45,19,16,17}
s2={19,16,17}
s3=s2.issubset(s1)
print(s3) -> True
s1={12,34,23,45,19,16,17}
s2={19,16,25}
s3=s2.issubset(s1)
print(s3) -> False
issuperset()
Method returns True if all items in the specified set
exists in the original set, otherwise it retuns False.
s1={12,34,23,45,19,16,17}
s2={12,34,17}
s3=s1.issuperset(s1)
print(s3) -> True
Dictionary
Dictionary in Python is an unordered collection of data
values.
Dictionary holds key:value pair.
Key value is provided in the dictionary to make it more
optimized.
In Python, a Dictionary can be created by placing
sequence of elements within curly {} braces, separated
by ‘comma’.
Dictionary holds a pair of values, one being the Key
and the other corresponding pair element being
its Key:value.
Access elements using ([]) brackets.
Use get() function.
Dictionary List
Unordered Ordered
Access via key Access vai index
Collection of key value pairs Collection of elements
Preferred when you have unique key Preferred for ordered data
values
No duplicate members Allow duplicate members
dic={1:'arun',2:'roshan',3:'amal'}
print(dic) -> {1: 'arun', 2: 'roshan', 3: 'amal'}
dic={1:'arun',2:'amal',3:'arjun'}
print(dic[1]) ->arun
print(dic[2]) ->amal
print(dic[3]) ->arjun
dic={'name':'Rohitsharma','age':33,'Average':52.5}
print(dic['name']) -> Rohitsharma
print(dic['age']) -> 33
print(dic['Average']) ->52.5
Dictionary methods
dict.clear()
Removes all elements of dictionary .
dic={'name':'Rohitsharma','age':33,'Average':52.5}
dic.clear()
print(dic) ->{}
dict.copy()
It returns a copy of the specified dictionary.
dic={'name':'Rohitsharma','age':33,'Average':52.5}
dic1=dic.copy()
print(dic) -> {'name': 'Rohitsharma',
'age':33,'Average': 52.5}
print(dic1)-> {'name': 'Rohitsharma', 'age': 33,
'Average': 52.5}
dict.keys()
Returns a list containing the dictionary's keys
dic={'name':'Rohitsharma','age':33,'Average':52.5}
s=dic.keys()
print(s)-> dict_keys(['name', 'age', 'Average'])
dic.values()
Returns a list containing the dictionary values.
dic={'name':'Rohitsharma','age':33,'Average':52.5}
s=dic.values()
print(s)->dict_values(['Rohitsharma', 33, 52.5])
dic.items()
It returns key-value pairs of dictionary as tuples in a
list.
dic={'name':'Rohitsharma','age':33,'Average':52.5}
s=dic.items()
print(s)->dict_items([('name', 'Rohitsharma'), ('age',
33), ('Average', 52.5)])
dic.pop()
The pop() method removes the specified item from
the dictionary.
dic={'name':'Rohitsharma','age':33,'Average':52.5}
dic.pop('age')
print(dic)->{'name': 'Rohitsharma', 'Average': 52.5}
dic.popitem()
Remove the last item from the dictionary.
dic={'name':'Rohitsharma','age':33,'Average':52.5}
dic.popitem()
print(dic) -> {'name': 'Rohitsharma', 'age': 33}