Python Notes For BCA
Python Notes For BCA
INTRODUTION TO PYTHON
1.1 Introduction:
General-purpose Object Oriented Programming language.
High-level language
Developed in late 1980 by Guido van Rossum at National Research Institute for
Mathematics and Computer Science in the Netherlands.
It is derived from programming languages such as ABC, Modula 3, small talk, Algol-
68.
It is Open Source Scripting language.
It is Case-sensitive language (Difference between uppercase and lowercase letters).
One of the official languages at Google.
Example:
>>>6+3
Output: 9
Note: >>> is a command the python interpreter uses to indicate that it is ready. The
interactive mode is better when a programmer deals with small pieces of code.
To run a python file on command line:
exec(open(“C:\Python33\python programs\program1.py”).read( ))
ii. Script Mode: In this mode source code is stored in a file with the .py extension
and use the interpreter to execute the contents of the file. To execute the script by the
interpreter, you have to tell the interpreter the name of the file.
Example:
if you have a file name Demo.py , to run the script you have to follow the following
steps:
2.2 TOKENS
Token: Smallest individual unit in a program is known as token.
There are five types of token in python:
1. Keyword
2. Identifier
3. Literal
4. Operators
5. Punctuators
as elif if or yield
All the keywords are in lowercase except 03 keywords (True, False, None).
2. Identifier: The name given by the user to the entities like variable name, class-name,
function-name etc.
3. Literal: Literals are the constant value. Literals can be defined as a data that is given
in a variable or constant.
Literal
String Literal
Numeric Boolean Special Collections
Eg.
5, 6.7, 6+9j
B. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as
well as double quotes for a String.
Eg:
"Aman" , '12345'
C. Boolean literal: A Boolean literal can have any of the two values: True or False.
None is used to specify to that field that is not created. It is also used for end of lists in
Python.
E. Literal Collections: Collections such as tuples, lists and Dictionary are used in Python.
4. Operators: An operator performs the operation on operands. Basically there are two
types of operators in python according to number of operands:
A. Unary Operator
B. Binary Operator
5. Separator or punctuator : , ; , ( ), { }, [ ]
B. Statements
A line which has the instructions or expressions.
C. Expressions:
A legal combination of symbols and values that produce a result. Generally it produces a value.
D. Comments: Comments are not executed. Comments explain a program and make a
program understandable and readable. All characters after the # and up to the end of the
physical line are part of the comment and the Python interpreter ignores them.
There are two types of comments in python:
i. Single line comment
ii. Multi-line comment
i. Single line comment: This type of comments start in a line and when a line ends, it is
automatically ends. Single line comment starts with # symbol.
Example: if a>b: # Relational operator compare two values
ii. Multi-Line comment: Multiline comments can be written in more than one lines. Triple
quoted ‘ ’ ’ or “ ” ”) multi-line comments may be used in python. It is also known as
docstring.
Example:
‘’’ This program will calculate the average of 10 values.
First find the sum of 10 values
and divide the sum by number of values
‘’’
Multiple Statements on a Single Line:
The semicolon ( ; ) allows multiple statements on the single line given that neither statement
starts a new code block.
Example:-
x=5; print(“Value =” x)
Creating a variable:
Example:
x=5
y = “hello”
Variables do not need to be declared with any particular type and can even change type after
they have been set. It is known as dynamic Typing.
x = 4 # x is of type int
x = "python" # x is now of type str
print(x)
variables. Example: x = y = z = 5
You can also assign multiple values to multiple variables. For example −
x , y , z = 4, 5, “python”
4 is assigned to x, 5 is assigned to y and string “python” assigned to variable z respectively.
x=12
y=14
x,y=y,x
print(x,y)
Now the result will be
14 12
Note: Expressions separated with commas are evaluated from left to right and assigned in same
order.
If you want to know the type of variable, you can use type( ) function :
Syntax:
type (variable-name)
Example:
x=6
type(x)
The result will be:
<class ‘int’>
If you want to know the memory address or location of the object, you can use id( )
function.
Example:
>>>id(5)
1561184448
>>>b=5
>>>id(b)
1561184448
You can delete single or multiple variables by using del statement. Example:
del x
del y, z
Example:
x = int(1) # x will be 1
y = int(2.8) # y will be 2
z = int("3") # z will be 3
float( ) - constructs a float number from an integer literal, a float literal or a string literal.
Example:
str( ) - constructs a string from a wide variety of data types, including strings, integer
literals and float literals.
Example:
Data Types
Primitive Collection
Data Type Data Type
Number String
int
float
complex
Example:
w=1 # int
y = 2.8 # float
z = 1j # complex
integer : There are two types of integers in python:
int
Boolean
x=1
y = 35656222554887711
z = -3255522
Boolean: It has two values: True and False. True has the value 1 and False has the
value 0.
Example:
>>>bool(0)
False
>>>bool(1)
True
>>>bool(‘ ‘)
False
>>>bool(-34)
True
>>>bool(34)
True
float : float or "floating point number" is a number, positive or negative, containing one
or more decimals. Float can also be scientific numbers with an "e" to indicate the power
of 10.
Example:
x = 1.10
y = 1.0
z = -35.59
a = 35e3
b = 12E4
c = -87.7e100
complex : Complex numbers are written with a "j" as the imaginary part.
Example:
>>>x = 3+5j
>>>y = 2+4j
>>>z=x+y
>>>print(z)
5+9j
>>>z.real
5.0
>>>z.imag
9.0
Real and imaginary part of a number can be accessed through the attributes real and imag.
RESULT
OPERATOR NAME SYNTAX
(X=14,
Y=4)
+ Addition x+y 18
_ Subtraction x–y 10
* Multiplication x*y 56
// Division (floor) x // y 3
% Modulus x%y 2
RESULT
OPERATOR NAME SYNTAX
(IF X=16,
Y=42)
False
> Greater than x>y
True
< Less than x<y
False
== Equal to x == y
True
!= Not equal to x != y
False
>= Greater than or equal to x >= y
True
<= Less than or equal to x <= y
iii. Logical operators: Logical operators perform Logical AND, Logical OR and Logical
NOT operations.
X Y X and Y
False False False
False True False
True False False
True True True
X Y X or Y
False False False
False True True
True False True
True True True
X Y X or Y
false false Y
false true Y
true false X
true true X
>>>0 or 0
0
>>>0 or 6
6
>>>‘a’ or ‘n’
’a’
>>>6<9 or ‘c’+9>5 # or operator will test the second operand only if the first operand
True # is false, otherwise ignores it, even if the second operand is
wrong
iv. Bitwise operators: Bitwise operators acts on bits and performs bit by bit operation.
Examples:
Let Output:
a = 10 0
b=4
14
print(a & b) -11
print(a | b) 14
2
print(~a)
40
print(a ^ b)
print(a >> 2)
print(a << 2)
v. Assignment operators: Assignment operators are used to assign values to the variables.
OPERA
TOR DESCRIPTION SYNTAX
a. Identity operators- is and is not are the identity operators both are used to check if
two values are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical
Example:
Let
a1 = 3
b1 = 3
a2 = 'PythonProgramming'
b2 = 'PythonProgramming'
a3 = [1,2,3]
b3 = [1,2,3]
Output:
False
True
False
Example:
>>>str1= “Hello”
>>>str2=input(“Enter a String :”)
Enter a String : Hello
>>>str1==str2 # compares values of string
True
>>>str1 is str2 # checks if two address refer to the same memory address
False
Example:
Let
x = 'Digital India'
y = {3:'a',4:'b'}
print('D' in x)
print('digital' not in x)
print('Digital' not in x)
print(3 in y)
print('b' in y)
Output:
True
True
False
True
False
2. Looping or Iteration
3. Jumping statements
2. if-else statement: When the condition is true, then code associated with if statement
will execute, otherwise code associated with else statement will execute.
Example:
a=10
b=20
if a>b:
print(“a is greater”)
else:
print(“b is greater”)
3. elif statement: It is short form of else-if statement. If the previous conditions were not true,
then do this condition". It is also known as nested if statement.
Example:
a=input(“Enter first number”)
b=input("Enter Second Number:")
if a>b:
print("a is greater")
elif a==b:
print("both numbers are equal")
else:
print("b is greater")
while
Loops in loop
Python
for loop
1. while loop: With the while loop we can execute a set of statements as long as a condition is
true. It requires to define an indexing variable.
Example: To print table of number 2
i=2
while i<=20:
print(i)
i+=2
2. for loop : The for loop iterate over a given sequence (it may be list, tuple or string).
Note: The for loop does not require an indexing variable to set beforehand, as the for command
itself allows for this.
primes = [2, 3, 5, 7]
for x in primes:
print(x)
it generates a list of numbers, which is generally used to iterate over with for loop.
range( ) function uses three types of parameters, which are:
a. range(stop)
b. range(start, stop)
Note:
Example:
for x in range(4):
print(x)
Output:
0
1
2
3
b. range(start, stop): It starts from the start value and up to stop, but not including
stop value.
Example:
Output:
2
3
4
5
c. range(start, stop, step): Third parameter specifies to increment or decrement the value by
adding or subtracting the value.
Example:
print(x)
Output:
3
5
7
Explanation of output: 3 is starting value, 8 is stop value and 2 is step value. First print 3 and
increase it by 2, that is 5, again increase is by 2, that is 7. The output can’t exceed stop-1 value
that is 8 here. So, the output is 3, 5, 8.
S.
No. range( ) xrange( )
1. break statement : With the break statement we can stop the loop even if it is true.
Example:
in while loop in for loop
i = 1 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
print(i) if x == "python":
if i == 3: break
break print(x)
i += 1
Output: Output:
1 java
2
3
Note: If the break statement appears in a nested loop, then it will terminate the very loop it is
in i.e. if the break statement is inside the inner loop then it will terminate the inner loop only
and the outer loop will continue as it is.
2. continue statement : With the continue statement we can stop the current iteration, and
continue with the next iteration.
Example:
in while loop in for loop
i = 0 languages = ["java", "python", "c++"]
while i < 6: for x in languages:
i += 1 if x == "python":
if i == 3: continue
continue print(x)
print(i)
Output: Output:
1 java c+
2 +
4
5
6
Syntax:
for loop while loop
Example:
for i in range(1,4):
for j in range(1,i):
print("*", end=" ")
print(" ")
Built in functions
Functions defined in
Types of functions modules
1. Library Functions: These functions are already built in the python library.
3. User Defined Functions: The functions those are defined by the user are called user
defined functions.
Example:
import random
n=random.randint(3,7)
Example:
def display(name):
Syntax:
function-name(parameter)
Example:
ADD(10,20)
OUTPUT:
Sum = 30.0
def functionName(parameter):
… .. …
… .. …
… .. …
… .. …
functionName(parameter)
… .. …
… .. …
OUTPUT:
(7, 7, 11)
OUTPUT:
7 7 11
b. Function not returning any value (void function) : The function that performs some
operationsbut does not return any value, called void function.
def message():
print("Hello")
m=message()
print(m)
OUTPUT:
Hello
None
Scope of a variable is the portion of a program where the variable is recognized. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
1. Local Scope
2. Global Scope
1. Local Scope: Variable used inside the function. It can not be accessed outside the function.
In this scope, The lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember the
value of a variable from its previous calls.
2. Global Scope: Variable can be accessed outside the function. In this scope, Lifetime of a
variable is the period throughout which the variable exits in the memory.
Example:
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
OUTPUT:
This is because the variable x inside the function is different (local to the function) from the
one outside. Although they have same names, they are two different variables with different
scope.
On the other hand, variables outside of the function are visible from inside. They have a global
scope.
We can read these values from inside the function but cannot change (write) them. In order to
modify the value of variables outside the function, they must be declared as global variables
using the keyword global.
5.6 RECURSION:
Definition: A function calls itself, is called recursion.
5.6.1 Python program to find the factorial of a number using recursion:
Program:
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
lambda keyword, is used to create anonymous function which doesn’t have any name.
While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
Syntax:
Lambda functions can have any number of arguments but only one expression. The expression
is evaluated and returned. Lambda functions can be used wherever function objects are
required.
Example:
value = lambda x: x *
4 print(value(6))
Output:
24
In the above program, lambda x: x * 4 is the lambda function. Here x is the argument and x *
4 is the expression that gets evaluated and returned.
6.1 Introduction:
Definition: Sequence of characters enclosed in single, double or triple quotation marks.
Basics of String:
Strings are immutable in python. It means it is unchangeable. At the same memory
address, the new value cannot be stored.
Each character has its index or can be accessed using its index.
String in python has two-way index for each location. (0, 1, 2, ……. In the forward
direction and -1, -2, -3,............in the backward direction.)
Example:
0 1 2 3 4 5 6 7
k e n d r i y a
-8 -7 -6 -5 -4 -3 -2 -1
The index of string in forward direction starts from 0 and in backward direction starts
from -1.
The size of string is total number of characters present in the string. (If there are n
characters in the string, then last index in forward direction would be n-1 and last index
in backward direction would be –n.)
i. String concatenation Operator: The + operator creates a new string by joining the
two operand strings.
Example:
>>>”Hello”+”Python”
‘HelloPython’
>>>’2’+’7’
’27’
>>>”Python”+”3.0”
‘Python3.0’
Note: You cannot concate numbers and strings as operands with + operator.
Example:
>>>7+’4’ # unsupported operand type(s) for +: 'int' and 'str'
It is invalid and generates an error.
ii. String repetition Operator: It is also known as String replication operator. It requires
two types of operands- a string and an integer number.
Example:
>>>”you” * 3
‘youyouyou’
>>>3*”you”
‘youyouyou’
b. Membership Operators:
in – Returns True if a character or a substring exists in the given string; otherwise False
not in - Returns True if a character or a substring does not exist in the given string; otherwise False
Example:
>>> "ken" in "Kendriya Vidyalaya"
False
>>> "Ken" in "Kendriya
Vidyalaya" True
>>>"ya V" in "Kendriya Vidyalaya"
True
>>>"8765" not in "9876543"
False
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
Example:
>>> 'abc'>'abcD'
False
>>> 'ABC'<'abc'
True
>>> 'abcd'>'aBcD'
True
>>> 'aBcD'<='abCd'
True
Example:
>>> ord('b')
98
>>> chr(65)
'A'
Program: Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value \n Press-2 to find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
print(chr(val))
else:
print("You entered wrong choice")
Interesting Fact: Index out of bounds causes error with strings but slicing a string outside the
index does not cause an error.
Example:
>>>str[14]
IndexError: string index out of range
>>> str[14:20] # both indices are outside the bounds
' ' # returns empty string
>>> str[10:16]
'ture'
Reason: When you use an index, you are accessing a particular character of a string, thus
the index must be valid and out of bounds index causes an error as there is no character to
return from the given index.
But slicing always returns a substring or empty string, which is valid sequence.
2. Write a program that reads a string and checks whether it is a palindrome string
or not.
str=input("Enter a string : ")
n=len(str)
mid=n//2
rev=-1
for i in range(mid):
if str[i]==str[rev]:
i=i+1
rev=rev-1
else:
print("String is not palindrome")
break
else:
print("String is palindrome")
3. Write a program to convert lowercase alphabet into uppercase and vice versa.
choice=int(input("Press-1 to convert in lowercase\n Press-2 to convert in uppercase\n"))
str=input("Enter a string: ")
if choice==1:
s1=str.lower()
print(s1)
elif choice==2:
s1=str.upper()
print(s1)
else:
print("Invalid choice entered")
CHAPTER-7
LIST IN PYTHON
7.1 Introduction:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
To create a list enclose the elements of the list within square brackets and separate the
elements by commas.
Syntax:
Example:
>>> L
>>> List
['h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n']
>>> L1
['6', '7', '8', '5', '4', '6'] # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> L1
>>> L2
[6, 7, 8, 5, 4, 3]
Note: With eval( ) method, If you enter elements without square bracket[ ], it will be
considered as a tuple.
>>> L1
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes.
List-name[start:end] will give you elements between indices start to end-1.
The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index
>>> number[2]
87
>>> number[-1]
27
>>> number[-8]
12
>>> number[8]
IndexError: list index out of range
>>> number[5]=55 #Assigning a value at the specified index
>>> number
[12, 56, 87, 45, 23, 55, 56, 27]
Method-1:
Output:
s
u
n
d
a
y
Method-2
>>> day=list(input("Enter elements :"))
Enter elements : wednesday
>>> for i in range(len(day)):
print(day[i])
Output:
w
e
d
n
e
s
d
a
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Joining Operator: It joins two or more lists.
Example:
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
Example:
>>> L1*3
>>> 3*L1
Slice Operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
>>> number[4:20]
>>> number[-1:-6]
[]
>>> number[-6:-1]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
>>> number[2:4]=["computer"]
>>> number
Note: The values being assigned must be a sequence (list, tuple or string)
Example:
>>> number=[12,56,87,45,23,97,56,27]
>>> number=[12,56,87,45,23,97,56,27]
Example:
Consider a list:
company=["IBM","HCL","Wipro"]
S. Function
Description Example
No. Name
1 append( ) To add element to the list >>> company.append("Google")
at the end. >>> company
Syntax: ['IBM', 'HCL', 'Wipro', 'Google']
list-name.append (element)
Error:
>>>company.append("infosys","microsoft") # takes exactly one
element TypeError: append() takes exactly one argument (2 given)
4 index( ) Returns the index of the >>> company = ["IBM", "HCL", "Wipro",
first element with the "HCL","Wipro"]
specified value. >>> company.index("Wipro")
Syntax: 2
list-name.index(element)
Error:
>>> company.index("WIPRO") # Python is case-sensitive language
ValueError: 'WIPRO' is not in list
>>> company.index(2) # Write the element, not index
ValueError: 2 is not in list
5 insert( ) Adds an element at the >>>company=["IBM","HCL","Wipro"]
specified position. >>> company.insert(2,"Apple")
>>> company
Syntax: ['IBM', 'HCL', 'Apple', 'Wipro']
list.insert(index, element)
>>> company.insert(16,"Microsoft")
>>> company
['IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
>>> company.insert(-16,"TCS")
>>> company
['TCS', 'IBM', 'HCL', 'Apple', 'Wipro',
'Microsoft']
[]
9 pop( ) Removes the element at >>>company=["IBM","HCL", "Wipro"]
the specified position and >>> company.pop(1)
returns the deleted 'HCL'
element. >>> company
Syntax: ['IBM', 'Wipro']
list-name.pop(index)
>>> company.pop( )
The index argument is
'Wipro'
optional. If no index is
specified, pop( ) removes and
returns the last item in the list.
Error:
>>>L=[ ]
>>>L.pop( )
IndexError: pop from empty list
10 copy( ) Returns a copy of the list. >>>company=["IBM","HCL", "Wipro"]
>>> L=company.copy( )
Syntax: >>> L
list-name.copy( ) ['IBM', 'HCL', 'Wipro']
11 reverse( ) Reverses the order of the >>>company=["IBM","HCL", "Wipro"]
list. >>> company.reverse()
Syntax: >>> company
list-name.reverse( ) ['Wipro', 'HCL', 'IBM']
Takes no argument,
returns no list.
12. sort( ) Sorts the list. By default >>>company=["IBM","HCL", "Wipro"]
in ascending order. >>>company.sort( )
>>> company
Syntax: ['HCL', 'IBM', 'Wipro']
list-name.sort( )
To sort a list in descending order:
>>>company=["IBM","HCL", "Wipro"]
>>> company.sort(reverse=True)
>>> company
['Wipro', 'IBM', 'HCL']
Deleting the elements from the list using del statement:
Syntax:
Example:
>>> L=[10,20,30,40,50]
>>> L
>>> L= [10,20,30,40,50]
>>> L
>>> del L # deletes all elements and the list object too.
>>> L
S.
del remove( ) pop( ) clear( )
No.
S.
append( ) extend( ) insert( )
No.
Adds an element at the
Adds single element in the end Add a list in the end of specified position.
1
of the list. the another list
(Anywhere in the list)
Takes one list as Takes two arguments,
2 Takes one element as argument
argument position and element.
The length of the list
The length of the list will The length of the list
3 will increase by the
increase by 1. will increase by 1.
length of inserted list.
Output:
Enter the elements: 56,78,98,23,11,77,44,23,65
Enter the element that you want to search : 23
Element found at the position : 4
CHAPTER-8
TUPLE IN
PYTHON
8.1 INTRODUCTION:
Syntax:
Example:
>>> T
>>> T=(3) #With a single element without comma, it is a value only, not a tuple
>>> T
>>> T= (3, ) # to construct a tuple, add a comma after the single element
>>> T
(3,)
>>> T1=3, # It also creates a tuple with single element
>>> T1
(3,)
>>> T2=tuple('hello') # for single round-bracket, the argument must be of sequence type
>>> T2
('h', 'e', 'l', 'l', 'o')
>>> T3=('hello','python')
>>> T3
('hello', 'python')
>>> T=(5,10,(4,8))
>>> T
>>> T
('h', 'e', 'l', 'l', 'o', ' ', 'p', 'y', 't', 'h', 'o', 'n')
>>> T1
('4', '5', '6', '7', '8') # it treats elements as the characters though we entered digits
To overcome the above problem, we can use eval( ) method, which identifies the
data type and evaluate them automatically.
>>> T1
>>> type(T1)
<class 'int'>
>>> T2
(1, 2, 3, 4, 5)
>>> T3
Tuples are very much similar to lists. Like lists, tuple elements are also indexed.
Forward indexing as 0,1,2,3,4……… and backward indexing as -1,-2,-3,-4,………
The values stored in a tuple can be accessed using the slice operator ([ ] and [:]) with
indexes.
tuple-name[start:end] will give you elements between indices start to end-1.
The first item in the tuple has the index zero (0).
Example:
>>> alpha=('q','w','e','r','t','y')
Forward Index
0 1 2 3 4 5
q w e r t y
-6 -5 -4 -3 -2 -1
Backward Index
>>> alpha[5]
'y'
>>> alpha[-4]
'e'
>>> alpha[46]
IndexError: tuple index out of range
>>> alpha[2]='b' #can’t change value in tuple, the value will remain
unchanged TypeError: 'tuple' object does not support item assignment
Tuple: Syntax:
statement
Example:
Method-1
>>> alpha=('q','w','e','r','t','y')
>>> for i in alpha:
print(i)
Output:
q
w
e
r
t
y
Method-2
>>> for i in range(0, len(alpha)):
print(alpha[i])
Output:
q
w
e
r
t
y
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
Joining Operator: It joins two or more tuples.
Example:
>>> T1 = (25,50,75)
>>> T2 = (5,10,15)
>>> T1+T2
(25, 50, 75, 5, 10, 15)
>>> T1 + (34)
TypeError: can only concatenate tuple (not "int") to tuple
>>> T1 + (34, )
Example:
>>> T1*2
>>> T2=(10,20,30,40)
>>> T2[2:4]*3
Slice Operator:
>>>alpha=('q','w','e','r','t','y')
>>> alpha[1:-3]
('w', 'e')
>>> alpha[3:65]
>>> alpha[-1:-5]
()
>>> alpha[-5:-1]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> alpha[1:5:2]
('w', 'r')
Comparison Operators:
Example:
Consider a tuple:
subject=("Hindi","English","Maths","Physics")
S. Function
No.
Description Example
Name
1 len( ) Find the length of a tuple. >>>subject=("Hindi","English","Maths","Physics”)
Syntax: >>> len(subject)
len (tuple-name) 4
2 max( ) Returns the largest value >>> max(subject)
from a tuple. 'Physics'
Syntax:
max(tuple-name)
Error: If the tuple contains values of different data types, then it will give an error
because mixed data type comparison is not possible.
Page 86
tuple- >>> subject.index("Maths")
name.index(element)
2
5 count( ) Return the number of >>> subject.count("English")
times the value appears.
Syntax: 1
tuple-
name.count(element)
Example:
>>> T=(45,78,22)
>>> T
(45, 78, 22)
Example:
>>> a, b, c=T
>>> a
45
>>> b
78
>>> c
22
Note: Tuple unpacking requires that the number of variable on the left side must be equal
to the length of the tuple.
The del statement is used to delete elements and objects but as you know that tuples are
immutable, which also means that individual element of a tuple cannot be deleted.
Page 87
Example:
>> T=(2,4,6,8,10,12,14)
But you can delete a complete tuple with del statement as:
Example:
>>> T=(2,4,6,8,10,12,14)
>>> del T
>>> T
Page 88
CHAPTER-9
DICTIONARY IN
PYTHON
9.1 INTRODUCTION:
Syntax:
Example:
>>> marks
>>> D
{ }
{'Maths': 81, 'Chemistry': 78, 'Physics': 75, 'CS': 78} # there is no guarantee
Page 89
order.
Page 90
Note: Keys of a dictionary must be of immutable types, such as string, number, tuple.
Example:
>>> D1={[2,3]:"hello"}
>>> marks=dict(Physics=75,Chemistry=78,Maths=81,CS=78)
>>> marks
In the above case the keys are not enclosed in quotes and equal sign is used
for assignment rather than colon.
>>> marks
>>> marks=dict(zip(("Physics","Chemistry","Maths","CS"),(75,78,81,78)))
>>> marks
Page 91
In this case the keys and values are enclosed separately in parentheses and are given as
argument to the zip( ) function. zip( ) function clubs first key with first value and so on.
Example-a
>>> marks=dict([['Physics',75],['Chemistry',78],['Maths',81],['CS',78]])
# list as argument passed to dict( ) constructor contains list type elements.
>>> marks
Example-b
>>> marks=dict((['Physics',75],['Chemistry',78],['Maths',81],['CS',78]))
>>> marks
Example-c
>>> marks=dict((('Physics',75),('Chemistry',78),('Maths',81),('CS',78)))
>>> marks
Page 92
9.3 ACCESSING ELEMENTS OF A DICTIONARY:
Syntax:
dictionary-name[key]
Example:
>>> marks["Maths"]
81
KeyError: 'English'
Lookup : A dictionary operation that takes a key and finds the corresponding value, is
called lookup.
9.4 TRAVERSING A
DICTIONARY: Syntax:
statement
Page 93
Example:
OUTPUT:
physics : 75
Chemistry : 78
Maths : 81
CS : 78
DICTIONARY: Syntax:
dictionary-name[key]=value
Example:
>>> marks
>>> marks
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
Page 94
9.6 DELETE ELEMENTS FROM A DICTIONARY:
Syntax:
del dictionary-name[key]
Example:
>>> marks
{'physics': 75, 'Chemistry': 78, 'Maths': 81, 'CS': 84, 'English': 89}
>>> marks
(ii) Using pop( ) method: It deletes the key-value pair and returns the value of
deleted element.
Syntax:
dictionary-name.pop( )
Example:
>>> marks
>>> marks.pop('Maths')
81
Page 95
9.7 CHECK THE EXISTANCE OF A KEY IN A DICTIONARY:
(i) in : it returns True if the given key is present in the dictionary, otherwise False.
(ii) not in : it returns True if the given key is not present in the dictionary, otherwise
False.
Example:
True
False
>>> 78 in marks # in and not in only checks the existence of keys not values
False
However, if you need to search for a value in dictionary, then you can use in operator
with the following syntax:
Syntax:
Example:
>>> 78 in marks.values( )
True
Page 96
To print a dictionary in more readable and presentable form.
For pretty printing a dictionary you need to import json module and then you can use
Example:
OUTPUT:
"physics": 75,
"Chemistry": 78,
"Maths": 81,
"CS": 78
dumps( ) function prints key:value pair in separate lines with the number of spaces
Steps:
Page 97
Program:
import json
L = sentence.split()
d={ }
for word in L:
key=word
if key not in d:
count=L.count(key)
d[key]=count
print(json.dumps(d,indent=2))
S. Function
No.
Description Example
Name
1 len( ) Find the length of a >>> len(marks)
dictionary.
Syntax: 4
len (dictionary-name)
2 clear( ) removes all elements >>> marks.clear( )
from the dictionary
Syntax: >>> marks
dictionary-name.clear( )
{}
Page 98
3. get( ) Returns value of a key. >>> marks.get("physics")
Syntax:
dictionary-name.get(key) 75
Note: When key does not exist it returns no value without any error.
>>> marks.get('Hindi')
>>>
4 items( ) returns all elements as a >>> marks.items()
sequence of (key,value)
tuples in any order. dict_items([('physics', 75), ('Chemistry',
Syntax: 78), ('Maths', 81), ('CS', 78)])
dictionary-name.items( )
Note: You can write a loop having two variables to access key: value pairs.
>>> seq=marks.items()
>>> for i, j in seq:
print(j, i)
OUTPUT:
75 physics
78 Chemistry
81 Maths
78 CS
5 keys( ) Returns all keys in the >>> marks.keys()
form of a list.
Syntax: dict_keys (['physics', 'Chemistry',
dictionary-name.keys( ) 'Maths', 'CS'])
6 values( ) Returns all values in the >>> marks.values()
form of a list.
Syntax: dict_values([75, 78, 81,
dictionary-name.values( )
78])
Page 99
Example:
>>> marks1 = { "physics" : 75, "Chemistry" : 78, "Maths" : 81, "CS":78 }
>>> marks2 = { "Hindi" : 80, "Chemistry" : 88, "English" : 92 }
>>> marks1.update(marks2)
>>> marks1
{'physics': 75, 'Chemistry': 88, 'Maths': 81, 'CS': 78, 'Hindi': 80, 'English': 92}
Page 100
Page 101