You are on page 1of 40

CS Study Material

Term 1 (Session 2021-22)

CHIEF PATRON
Shri B L Morodia, Deputy Commissioner, KVS (RO), Jaipur

PATRON
Shri D R Meena, Assistant Commissioner, KVS (RO), Jaipur

CONTENT COORDINATOR
Shri Manoj Kumar Pandey, Principal - KV Itarana Alwar

CONTENT COMPILATION
Shri Sandeep Sharma (PGT CS), KV 1 Kota
Shri Pankaj Singh (PGT CS), KV Bharatpur
Shri Navneet Sadh (PGT CS), KV Churu

CONTENT PREPARATION
ALL PGT CS OF JAIPUR REGION
Python Revision: Part 1
OR
Python Fundamentals Apart from above standard Python. We have
various Python IDEs and Code Editors. Some of
1. What is Python: them are as under:
(i) Anaconda Distribution: free and open-source
 Python is a general-purpose, high level distribution of the Python, having various inbuilt
programming language. It was created by libraries and tools like Jupyter Notebook, Spyder
Guido van Rossum, and released in 1991. etc
 In order to communicate with a computer (ii) PyCharm (iii) Canopy
system, we need a computer programming (iv) Thonny (v) Visual Studio Code
language. This language may be C, C++, Java, (vi) Eclipse + PyDev (vii) Sublime Text
Python or any other computer language. (viii) Atom (ix) GNU Emacs
Here we will discuss Python. (x) Vim (xi) Spyder and many more . .
 Python is inspired by two languages – (i)
ABC language which was an optional 5. Python Interpreter - Interactive And Script
language of BASIC language. (ii) Modula-3 Mode:
We can work in Python in Two Ways:
2. Why Python: (i) Interactive Mode: it works like a command
interpreter as shell prompt works in DOS
 Platform Independent (Cross-Platform) Prompt or Linux. On each (>>>) symbol we
 Free and Open Source can execute one by one command.
 Simple syntax similar to the English (ii) Script Mode: it used to execute the multiple
language. instruction (complete program) at once.
 Fewer lines than some other programming
languages 6. Python Character Set:
 Interpreted Language. Character Set is a group of letters or signs which
 Python can be treated in a procedural way, are specific to a language. Character set includes
an object-orientated way. (OOL and POL.) letter, sign, number and symbol.

3. What can Python do?  Letters: A-Z, a-z


 Digits: 0-9
It is possible to develop various Apps/ Software’s  Special Symbols: _, +, -, *, /, (, #,@, {, } etc.
with Python like:  White Spaces: blank space, tab, carriage
return, newline, form feed etc.
 Web development  Other characters: Python can process all
 Machine learning characters of ASCII and UNICODE.
 Data Analysis
 Scripting 7. Python Tokens:
 Game development.
 Embedded applications Token is the smallest unit of any programming
language. It is also known as Lexical Unit.
 Desktop applications
Types of token are
4. How To Use Python?
i. Keywords
4.1 Python can be downloaded from
ii. Identifiers (Names)
www.python.org. (Standard Installation)
iii. Literals
4.2. It is available in two versions- iv. Operators
v. Punctuators
• Python 2.x

• Python 3.x (It is in Syllabus)

KVS – Regional Office, JAIPUR | Session 2021-22


7.1 Keywords: Python supports following types of operators -
Keywords are reserved words. Each keyword has a
specific meaning to the Python interpreter. As Unary Operator
Python is case sensitive, these cannot be used as •Unary plus (+)
identifiers, variable name or any other purpose •Unary Minus (-)
keywords must be written exactly as given below: •Bitwise complement (~)
if while True False •Logical Negation (not)
for break continue or . . . . etc
Binary Operator
7.2 Identifiers: •Arithmetic operator (+, -, *, /, %, **, //)
In programming languages, identifiers are names
•Relational Operator(<, >, <=, >=, ==,!= )
used to identify a variable, function, or other
entities in a program. The rules for naming an •Logical Operator (and, or)
identifier in Python are as follows: •Assignment Operator (=, /=, +=, -=, *=, %=,
· The name should begin with an uppercase or a **=, //=)
lowercase alphabet or an underscore sign (_). •Bitwise Operator (& bitwise and, ^ bitwise
· This may be followed by any combination of xor,|bitwise or)
characters a-z, A-Z, 0-9 or underscore (_). Thus, •Shift operator (<< shift left, >> shift right)
an identifier cannot start with a digit. •Identity Operator (is, is not)
· It can be of any length. (However, it is preferred •Membership Operator (in, not in)
to keep it short and meaningful).
· It should not be a keyword or reserved word. 7.5 Punctuators:
· We cannot use special symbols like !, @, #, $, %, Punctuators are symbols that are used in
programming languages to organize sentence
etc. in identifiers.
structure, and indicate the rhythm and emphasis of
expressions, statements, and program structure.
Legal Identifier Names Example:
myvar my_var _my_var myVar Common punctuators are: „ “ # $ @ []{}=:;(),
myvar2
8. Variable:
Illegal Identifier Names Example:- · Variables are containers for storing data
2myvar my-var my var= 9salary values.
· Unlike other programming languages,
7.3 Literals/ Values: Python has no command for declaring a
Literals are often called Constant Values. Python variable.
permits following types of literals · A variable is created the moment you first
a. String literals - “Rishaan” assign a value to it.
b. Numeric literals – 10, 13.5, 3+5i Example:
c. Boolean literals – True or False x=5
y = "John"
d. Special Literal None
print(x)
e. Literal collections print(y)
· Variables do not need to be declared with any
7.4 Operators: particular type and can even change type after
An operator is used to perform specific they have been set.
mathematical or logical operation on values. The x = 4 # x is of type int
values that the operator works on are called x = "Sally" # x is now of type str
operands print(x)
KVS – Regional Office, JAIPUR | Session 2021-22
· String variables can be declared either by using Mutable and Immutable data type
single or double quotes: Mutable: The values stored can be changes, Size of
x = "John" object can be changed, e.g. List, Dictionary
# is the same as Immutable: The value stored can not be changed,
x = 'John' Size can not be changed, e.g. Tuple, String

Variable Names 10. Expression in python:


A variable can have a short name (like x and y) or a An expression is a combination of values, i.e.,
more descriptive name (age, carname, constant, variable and operator.
total_volume). e.g. Expression 6-3*2+7-1 evaluated as 6

Rules for Python variables: 11. Precedence of Arithmetic Operators:


· A variable name must start with a letter or the Precedence helps to evaluate an expression.
underscore character
· A variable name cannot start with a number 12. Comments in python: Comments are non-
executable statements of python. It increases the
· A variable name can only contain alpha-
readability and understandability of code.
numeric characters and underscores (A-z, 0-9,
and _ ) Types of comment:
· Variable names are case-sensitive (age, Age and i. Single line comment (#) – comments only
AGE are three different variables) single line.
e.g. a=7 # 7 is assigned to variable ‘a’
Output Variable: print(a) # displaying the value stored in ‘a’
The Python print statement is often used to output ii. Multi-line comment (‘‘‘………..’’’) – Comments
variables. To combine both text and a variable, multiple line.
Python uses the, character: e.g. ‘‘‘Program -1
x = "awesome" A program in python to store a value in
print("Python is " , x) variable ‘a’ and display the value stored in it.’’’
a=7
Display Multiple variable:- print(a)
x = "awesome“
y=56 13. Input and output in python:
print(“Value of x and y is=" , x, y) input ( ) method - It is used to take input from
user.
9. Data Type: print ( ) method – It is used to display message or
Every value belongs to a specific data type in result in output.
Python. Data type identifies the type of data which Example:-
a variable can hold and the operations that can be Name = input (“Enter your name : ”)
performed on those data. Marks = int(input (“Enter your marks ”))
print(“Your name is ”, Name)
Data Types in Python:
print(“You got ”, Marks, “ marks”)
· Numbers :- int, float and complex.
· List :- [5, 3.4, "New Delhi", "20C", 45]
14. Debugging:- Debugging is a process of locating
· Tuple :- (10, 20, "Apple", 3.4, 'a') and removing errors from program.
· Strings :- str = 'Hello Friend'
· Set:- {2,6,9}
· Dictionary:- {'Fruit':'Apple', 'Climate':'Cold',
'Price(kg)':120}
KVS – Regional Office, JAIPUR | Session 2021-22
Python Control Statements it. If condition evaluates result as false, it will
executes the block given below else.
In any programming language a program may
execute sequentially, selectively or iteratively. Syntax:
Every programming language provides constructs
to support Sequence, Selection and Iteration. In if ( condition):
Python all these construct can broadly categorized Statement(s)
in 2 categories. else:
Statement(s)
Conditional Control Construct
(Selection, Iteration)
Example
Un-Conditional Control Construct
(pass, break, continue, exit(), quit()) age=int(input(“Enter Age: “))
if ( age>=18):
Python have following types of control statements print(“You are eligible for vote”)
1. Selection ( branching) Statement else:
2. Iteration ( looping) Statement print(“You are not eligible for vote”)
3. Jumping (break / continue)Statement
Ladder if else statements (if-elif-else)
Python Selection Statements This construct of python program consist of more
Python have following types of selection than one if condition. When first condition
statements evaluates result as true then executes the block
1. if statement given below it. If condition evaluates result as false,
2. if else statement it transfer the control at else part to test another
3. Ladder if else statement (if-elif-else) condition. So, it is multi-decision making construct.
Syntax:
4. Nested if statement
if ( condition-1):
If statements Statement(s)
This construct of python program consist of one if elif (condition-2):
condition with one block of statements. When Statement(s)
condition becomes true then executes the block elif (condition-3):
given below it. Statement(s)
Syntax: else:
if ( condition):
Statement(s)
Statement(s)
Example:
Example:
age=int(input(“Enter Age: “))
num=int(input(“Enter Number: “))
if ( age>=18):
If ( num>=0):
print(“You are eligible for vote”)
print(“You entered positive number”)
if(age<0):
elif ( num<0):
print(“You entered Negative Number”)
print(“You entered Negative number”)
if - else statements else:
This construct of python program consist of one if print(“You entered Zero ”)
condition with two blocks. When condition
becomes true then executes the block given below
KVS – Regional Office, JAIPUR | Session 2021-22
Nested if statements Python while loop
It is the construct where one if condition take part The while loop is conditional construct that
inside of other if condition. This construct consist executes a block of statements again and again till
of more than one if condition. Block executes when given condition remains true. Whenever condition
condition becomes false and next condition meets result false then loop will terminate.
evaluates when first condition became true. Syntax:
So, it is also multi-decision making construct. Initialization of control variable
Syntax: while (condition):
if ( condition-1):
…………………..
if (condition-2):
Statement(s) ..…………………
else: Updation in control variable
Statement(s)
Example: Sum of 1 to 10 numbers.
Example: num=1
num=int(input(“Enter Number: “)) sum=0
if ( num<=0): while(num<=10):
if ( num<0): sum + = num
print(“You entered Negative number”) num + = 1
else: print(“The Sum of 1- 10 numbers: “, sum)
print(“You entered Zero ”)
else: Python range( ) Function
print(“You entered Positive number”) The range() function returns a sequence of
numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a
Python Iteration Statements specified number.
The iteration (Looping) constructs mean to Syntax:
execute the block of statements again and again
range( start value, stop value, step value )
depending upon the result of condition. This
repetition of statements continues till condition Where all 3 parameters are of integer type
meets True result. As soon as condition meets false ● Start value is Lower Limit
result, the iteration stops. ● Stop value is Upper Limit
● Step value is Increment / Decrement
Python supports following types of iteration Note: The Lower Limit is included but Upper Limit
statements
is not included in result.
1. while
2. for Example
range(5) => sequence of 0,1,2,3,4
Four Essential parts of Looping: range(2,5) => sequence of 2,3,4
i. Initialization of control variable range(1,10,2) => sequence of 1,3,5,7,9
ii. Condition testing with control variable range(5,0,-1) => sequence of 5,4,3,2,1
iii. Body of loop Construct range(0,-5) => sequence of [ ] blank list
iv. Increment / decrement in control variable
(default Step is +1)
range(0,-5,-1) => sequence of 0, -1, -2, -3, -4
range(-5,0,1) => sequence of -5, -4, -3, -2, -1
range(-5,1,1) => sequence of -5, -4, -3, -2, -1, 0

KVS – Regional Office, JAIPUR | Session 2021-22


Python for loop in which it lies. The execution continues from the
A for loop is used for iterating over a sequence statement which find out of loop terminated by
(that is either a list, a tuple, a string etc.) With for break.
loop we can execute a set of statements, and for
loop can also execute once for each element in a Continue Statement
list, tuple, set etc. Continue statement is also a jump statement. With
Example: print 1 to 10 numbers the help of continue statement, some of statements
in loop, skipped over and starts the next iteration.
for num in range(1,11,1): It forcefully stop the current iteration and transfer
print(num, end=” “) the flow of control at the loop controlling
condition.
Output: 1 2 3 4 5 6 7 8 9 10
String in Python: String is a sequence which is
Nested Loop: means when we have one loop in
another loop. made up of one or more UNICODE characters. A
Example: string can be created by enclosing one or more
for I in range (5): characters in single, double or triple quote.
for J in range (5):
print (I,J) For Example:
str = “Manoj” # str is a variable storing a string. .
Un- Conditional Control Construct
(pass, break, continue, exit(), quit()) str = ‘M’ # String can also be enclosed in single
quotes
pass Statement (Empty Statement)
The pass statement do nothing, but it used to Initializing Strings in Python: To initialize string
complete the syntax of programming concept. Pass enclose the character or sequence of characters in
is useful in the situation where user does not Single or Double Quotes as follows:
requires any action but syntax requires a
str = ‘A’ # String enclosed in Single Quotes
statement. The Python compiler encounters pass
statement then it do nothing but transfer the str= “Manoj” #String enclosed in double quotes
control in flow of execution.
Example str = “””This course will introduce the learner to
a=int(input("Enter first Number: ")) text mining and text manipulation basics.
b=int(input("Enter Second Number: ")) The course begins with an understanding of
if(b==0): how text is handled by python”””
pass
else: We can also use str() function to create string:
print("a/b=",a/b)
N = str () #It will create an empty string
Jumping Statements

● break name = str(12345) # This will store string “12345”


● continue

break Statement
The jump- break statement enables to skip over a
part of code that used in loop even if the loop
condition remains true. It terminates to that loop

KVS – Regional Office, JAIPUR | Session 2021-22


Table 8.1 Indexing of characters in string 'Hello String Operations with different Operators:
World!' Concatenation (+)
To concatenate means to join. Python allows us to
+ive join two strings using concatenation operator plus
index 0 1 2 3 4 which is denoted by symbol (+).
str1 = 'Hello' #First string
String >>> str2 = 'World!' #Second string
H e l l o >>> str1 + str2 #Concatenated
strings
-ive Output: 'HelloWorld!'
index -5 -4 -3 -2 -1
Repetition (*)
Python allows us to repeat the given string using
An inbuilt function len() in Python returns the repetition operator which is denoted by symbol *.
length of the string that is passed as parameter. For example:
>>> str1 = 'Hello'
For example: >>> str1 * 2 #repeat the value of
The length of string str1 = 'Hello World!' is 12. str1, 2 times
#gives the length of the string str1 'HelloHello'
>>> len(str1) >>> str1 * 5 #repeat the value of
12 str1 5 times
>>> n = len(str1) #length of the string is 'HelloHelloHelloHelloHello'
assigned to n Membership Operator (‘in’ and ‘not in’)

>>> print(n) Python has two membership operators 'in' and


12 'not in'. The 'in' operator takes two strings and
>>> str1[n-1] #gives the last character of the string returns True if the first string appears as a
'!' substring in the second string, otherwise it returns
>>> str1[-n] #gives the first character of the string False.
'H' >>> str1 = 'Hello World!'
>>> 'W' in str1
String is Immutable: A string is an immutable data True
type, that means the contents of the string cannot be >>> 'Wor' in str1
changed after it has been created. If you try to change, True
it would lead to an error. >>> 'My' in str1
False
For Example:
str1 = "Hello World!" The 'not in' operator also takes two strings and
str1[1] = 'a' #if we try to replace character 'e' returns True if the first string does not appear as a
with 'a' substring in the second string, otherwise returns
TypeError: 'str' object does not support item False.
assignment For Example:

KVS – Regional Office, JAIPUR | Session 2021-22


>>> str1 = 'Hello World!' Code:
>>> 'My' not in str1 string1 = "hello"
True string2 = "hello, world"
Accessing String with slicing operator “[]” string3 = "hello, world"
e.g. string4 = "world"
str='Computer Science' OUTPUT
print(string1==string4) False
OUTPUT print(string2==string3) True
print(string1!=string4) True
print('str-', str) str- Computer Science
print(string2!=string3) False
print('str[0]-', str[0]- C
Escape Sequence Operator “\.”
str[0])
To insert a non-allowed character in the given
input string, an escape character is used. An escape
print('str[1:4]-', str[1:4]- omp
character is a “\” or “backslash” operator followed
str[1:4])
by a non-allowed character. An example of a non-
allowed character in python string is inserting
print('str[2:]-', str[2:]- mputer Sciene'
double quotes in the string surrounded by double-
str[2:])
quotes.
Example of non-allowed double quotes in python
print('str *2-', str str *2- Computer
string:
*2 ) ScieneComputer Sciene
Code:
print("str +'yes'-", str +'yes'- Computer Operator Description
str +'yes') Scieneyes
%d Signed decimal integer
String Comparison by using Operator (“==” & “!=”)
The string comparison operator in python is used %u unsigned decimal integer
to compare two strings.
%c Character
“==” operator returns Boolean True if two strings
are the same and return Boolean False if two %s String
strings are not the same.
%f Floating-point real number
“!=” operator returns Boolean True if two strings string = "Hello world I am from "India""
are not the same and return Boolean False if two print(string)
strings are the same. Output:

These operators are mainly used along with if 2. Example of allowed double quotes with escape
condition to compare two strings where the sequence operator:
decision is to be taken based on string comparison. Code:
string = "Hello world I am from \"India\""

KVS – Regional Office, JAIPUR | Session 2021-22


print(string) Traversing a String:
Output: We can access each character of a string or traverse
String Formatting Operator “%.” a string using for loop and while loop.

String formatting operator is used to format a (A) String Traversal Using for Loop:
string as per requirement. To insert another type >>> str1 = 'Hello World!'
of variable along with string, the “%” operator is >>> for ch in str1:
used along with python string. “%” is prefixed to print(ch,end = '')
another character indicating the type of value we Hello World! #output of for loop
want to insert along with the python string. Please In the above code, the loop starts from the first
refer to the below table for some of the commonly character of the string str1 and automatically ends
used different string formatting specifiers: when the last character is accessed.
Code:
name = "india" (B) String Traversal Using while Loop:
age = 19 >>> str1 = 'Hello World!'
marks = 20.56 >>> index = 0
string1 = 'Hey %s' %(name) #len(): a function to get length of string
print(string1) >>> while index < len(str1):
string2 = 'my age is %d' % (age) print(str1[index],end = '')
print(string2) index += 1
string3= 'Hey %s, my age is %d' % (name, age) Hello World! #output of while loop
print(string3) Here while loop runs till the condition index <
string3= 'Hey %s, my subject mark is %f' % (name, len(str) is True, where index varies from 0 to
marks) len(str1) -1
print(string)

String Methods and Built-in Functions:


Python has several built-in functions that allow us to work with strings. Some of the commonly used
built-in functions for string manipulation.
Built-in Functions Description
String.len() Returns the length of the string.
String.endswith() Returns True if a string ends with the given suffix otherwise returns False
String.startswith() Returns True if a string starts with the given prefix otherwise returns False
String.isdigit() Returns “True” if all characters in the string are digits, Otherwise, It returns “False”.
String.isalpha() Returns “True” if all characters in the string are alphabets, Otherwise, It returns
“False”.
string.isdecimal() Returns true if all characters in a string are decimal.
str.format() It allows multiple substitutions and value formatting.
String.index() Returns the position of the first occurrence of substring in a string
string.uppercase() A string must contain uppercase letters.
string.whitespace() A string containing all characters that are considered whitespace.
string.swapcase() Method converts all uppercase characters to lowercase and vice versa.
KVS – Regional Office, JAIPUR | Session 2021-22
string.isdecimal() Returns true if all characters in a string are decimal
String.isalnum() Returns true if all the characters in a given string are alphanumeric.
string.istitle() Returns True if the string is a titlecased string
String.partition() splits the string at the first occurrence of the separator and returns a tuple.
String.isidentifier() Check whether a string is a valid identifier or not.
String.rindex() Returns the highest index of the substring inside the string if substring is
found.
String.max() Returns the highest alphabetical character in a string.
String.min() Returns the minimum alphabetical character in a string.
String.splitlines() Returns a list of lines in the string.
string.capitalize() Return a word with its first character capitalized.
string.expandtabs() Expand tabs in a string replacing them by one or more spaces
string.find() Return the lowest index in a sub string.
string.rfind() find the highest index.
string.count() Return the number of (non-overlapping) occurrences of substring sub in
string
string.lower() Return a copy of String, but with upper case letters converted to lower case.
string.split() Return a list of the words of the string, If the optional second argument sep
is absent or None
string.rsplit() Return a list of the words of the string s, scanning s from the end.
rpartition() Method splits the given string into three parts
string.splitfields() Return a list of the words of the string when only used with two arguments.
string.join() Concatenate a list or tuple of words with intervening occurrences of sep.
string.strip() It return a copy of the string with both leading and trailing characters
removed
string.lstrip() Return a copy of the string with leading characters removed.
string.rstrip() Return a copy of the string with trailing characters removed.
string.swapcase() Converts lower case letters to upper case and vice versa.
string.translate() Translate the characters using table
string.upper() lower case letters converted to upper case.
string.ljust() left-justify in a field of given width.
string.rjust() Right-justify in a field of given width.
string.casefold() Returns the string in lowercase which can be used for caseless comparisons.

KVS – Regional Office, JAIPUR | Session 2021-22


Python Revision: Part 2

LIST Output
Definition: Enter a set of numbers 4,7,5,6,9,2
A List is a collection of comma separated Tuple is= (4,7,5,6,9,2)
values within a square bracket. Items in a list need List is=[4,7,5,6,9,2]
not to be the same.
List Indexing
Features of list
• A List is used to store sequence of values / Here,
items. List1 = [12, 3, 43, 23, 33, 65]
• All Elements of a list are enclosed in [ ]
square bracket.
• Items / values are separated by comma.
• Lists are mutable (changeable) in python.

Different type of lists

# List of text Accessing elements from a list


Fruit=['Mango','Orange','Apple']
#List of Characters
Grade=['A','B','C']
# List of integers
Marks=[75,63,95]
# List of floats
Amount=[101.11,125.81,99.99]
# List with different data types
Record=[75,'Mango',101.11]
# List within a List
list1=[2,3,[2,3]]
# List with text splitted into chars
list2=list('IP&CS') Traversing of list elements (Iteration/Looping over
#Empty list a list)
list3=list() List1=[12,3,43,23,33,65]

Creation of list from user input Method-1


eval()– this method can be used to accept tuple List1 = [12, 3, 43, 23, 33, 65] both result in same O/P
from user. Which can be converted to list using for i in range(0,len(List1)): 12
list() method. print(List[i]) 3
E.g. 43
T=eval(input(“Enter a set of numbers ”))
print(“Tuple is = ”,T)
Method-2 23
List1 = [12, 3, 43, 23, 33, 65] 33
L=list(T)
print(“List is = ”,L) for x in List1: 65
print(x)

KVS – Regional Office, JAIPUR | Session 2021-22


SLICING: Accessing a part of a list is known as 2. Extend command
slicing. extend( ) is used to add one or more elements
-9 -8 -7 -6 -5 -4 -3 -2 -1 ListF = [44, 55]
ListF # [44, 55]
A M I T J A I N
ListF.extend(77) # Error
0 1 2 3 4 5 6 7 8
ListF.extend([77]) # [44, 55, 77]
List1 = ['A', 'M', 'I', 'T', ' ','J','A', 'I', 'N'] ListF.extend([88, 99]) # [44, 55, 77, 88, 99]

Statement Output MODIFICATION /UPDATION OF ITEM


ListD= [36, 46, 56, 66, 76] Output
print(List1[:]) ['A', 'M', 'I', 'T', ' ', 'J', 'A', 'I', 'N']

print(List1[2:]) ['I', 'T', ' ', 'J', 'A', 'I', 'N'] ListD[2] # 56
ListD[2] = 1000 # 56
print(List1[:6]) ['A', 'M', 'I', 'T', ' ', 'J']
ListD[2] # 1000
print(List1[0:4]) ['A', 'M', 'I', 'T'] ListD # [36, 46, 1000, 66, 76]
print(List1[3:6]) ['T', ' ', 'J'] ListD[2:3]= 400,500 # [36, 46, 400, 500, 66, 76]
DELETION OF ELEMENTS FROM LIST
print(List1[-2:-5]) []
Using del command O/P
print(List1[-5:-2]) [' ', 'J', 'A'] List1=[44,55,66,77,88]
del List1[2]
print(List1[1:7:2]) ['M', 'T', 'J']
print(List1) [44,55,77,88]
del List1[1:3]
print(List1) [44,88]

Using pop(index) method O/P


[Start : End : Step] L1=['K', 'V', '4']
(Select from start index to end-1 index print(L1.pop( )) 4
number with jump of step) print(L1.pop(1)) V
print(L1) [‘K’, ‘4’]
ADDITION OF ELEMENTS IN LIST: print(L1.pop(-1)) 4
Two ways to add an item in the list OPERATORS
E.g. L1=[23,12,43,22,5,34] L2=[4,3,5]
1. Append command
append( ) is used to add only one element at a Sl. No. Operator For List Output
time. L1 & L2
ListF = [44, 55]
1 Concatenation‘+ L1+L2 [23, 12, 43, 22, 5,
ListF # [44, 55] ’ 34, 4, 3, 5]
ListF.append(77)
ListF # [44, 55, 77] 2 Replication/ L2*3 [4,3,5,4,3,5,4,3,5]
Repetition ‘*’
ListF.append(88,88) # Error
3 Membership ‘ in 43 in L1 True
ListF.append([88, 99]) # [44, 55, 77, [88, 99]]
‘ and ‘ not in’ 3 not in L2 False
KVS – Regional Office, JAIPUR | Session 2021-22
METHODS / FUNCTIONS

E.g. L1=[23,12,43,23,5,34]
L2=[‘K’, ‘V’, ‘S’]

Sl. Method / Function Example Output


No. For given list
L1 & L2

1 index(item) L1.index(43) 2
To display index of an item

2 insert(index, item) L2.insert(1, ‘A’) ['K','A','V','S']


To add an item at given index

3 reverse() L2.reverse() [‘S’,‘V’,‘A’,‘K’]


Reverse the order of elements

4 len(List) len(L1) 6
Returns length of list

5 sort() Ascending order ['A','K','S','V']


Arrange the elements in L2.sort()
ascending or descending Order
Descending order ['V','S','K','A']
L2.sort(reverse =True)
6 count(item) L1.count(23) 2
Counts frequency of an item

7 remove(item) L2.remove(‘A’) [‘K’,’V’,’S’]


Remove the item

8 max(list) max(L1) 43
Returns maximum value

9 min(list) min(L1) 5
Returns minimum value

Reference Videos:-
List (Part-1) https://youtu.be/J8NQuV4CEfw
List (Part-2) https://youtu.be/pheM8nHPNG4
List (Part-3) https://youtu.be/GYptLReCqaw

KVS – Regional Office, JAIPUR | Session 2021-22


TUPLE Basic Tuple operations
Definition: Python Tuple is used to store the The operators like concatenation (+), repetition
sequence of immutable Python objects. The tuple (*), Membership (in) works in the same way as
is similar to lists since the value of the items stored they work with the list. Consider the following
in the list can be changed, whereas the tuple is table for more detail.
immutable, and the value of the items stored in the Let's say Tuple t = (1, 2, 3, 4, 5) and
tuple cannot be changed. Tuple t1 = (6, 7, 8, 9) are declared.
Operator Description Example
Creating Tuple
Empty tuple: An empty tuple can be created as Repetition enables the T1*2 = (1, 2, 3,
follows. tuple elements 4, 5, 1, 2, 3, 4, 5)
T1 = () to be repeated
multiple times.
Initialing Tuple with values:
Concatena It concatenates T1+T2 = (1, 2, 3,
Example
tion the tuple on 4, 5, 6, 7, 8, 9)
rgb = ('red', 'green', 'blue') either side of
numbers = (3,) the operator.
‘’’a tuple with one element, you need to include a
Membersh It returns true if print (2 in T1)
trailing comma after the first element’’’ ip a particular prints True.
tuple1 = (10, 20, 30, 40, 50, 60) item exists in
Understanding Index numbers the tuple else
false
Z=(3,7,4,2)
Iteration The for loop is for i in T1:
used to iterate print(i)
over the tuple Output
elements. 1
2
3
4
z = (3, 7, 4, 2) # Access the first item of a 5
tuple at index 0
print(z[0]) #Output 3
List vs. Tuple
z = (3, 7, 4, 2) # Accessing the last item of a
tuple
print(z[3]) #Output 2 SN List Tuple
OR
print(z[-1]) #Output 2 1 The literal syntax The literal syntax of
Tuple slices of list is shown by the tuple is shown by
print(z[0:2]) #output would be 3,7 the []. the ().
print(z[:3]) #Output 3,7,4
2 The List is The tuple is
print(z[-4:-1]) #Output 3,7,4
mutable. immutable.
print(z[-1:-3:-1]) #Output 2,4

KVS – Regional Office, JAIPUR | Session 2021-22


The nested tuple with the elements (200, 201) is
3 The List has a The tuple has the fixed
variable length. length. treated as an element along with other elements
in the tuple 'tup'. To retrieve the nested tuple, we
4 The list provides The tuple provides can access it as an ordinary element as tup[5] as
more less functionality than its index is 5.
functionality than the list.
a tuple. Built-in Tuple Methods

5 The list is used in The tuple is used in


the scenario in the cases where we Method Description
which we need to need to store the read-
store the simple only collections i.e., count() Returns the number of times a
collections with the value of the items specified value occurs in a tuple
no constraints cannot be changed. It
index() Searches the tuple for a specified
where the value can be used as the key
value and returns the position of
of the items can inside the dictionary.
where it was found
be changed.

Some function that are useful to work with


Nested Tuple tuple
A tuple can be defined inside another tuple; called
Nested tuple. In a nested tuple, each tuple is 1. len( (1, 2, 3, [6, 5]) )
considered as an element. Output: 4 # It returned 4, not 5, because the list
The for loop will be useful to access all the counts as 1.
elements in a nested tuple.
2. max()
Read more on Sarthaks.com: It returns the item from the tuple with the highest
https://www.sarthaks.com/1017899/what-is- value.
nested-tuple-explain-with-an-example
Example 1: a=(3,1,2,5,4,6)
max(a)
Toppers = ((“Vinodini” , “XII-F”, 98.7),
(“Soundarya” , “XII-H” , 97.5), (“Tharani” , “XII- F”, Output : 6
95.3), (“Saisri” , “XII-G” , 93.8)) 3. min()
for i in Toppers:
print(i) Like the max() function, the min() returns the
item with the lowest values.
Output: a=(3,1,2,5,4,6)
(‘Vinodini’ , ‘XII-F’, 98.7) min(a)
(‘Soundarya’ , ‘XII-H’ , 97.5) Output: 1
(‘Tharani’ , ‘XII-F’, 95.3)
(‘Saisri’ , ‘XII-G’ , 93.8) 4. sum()
Example 2: This function returns the arithmetic sum of all the
tup = (50,60,70,80,90, (200, 201)) items in the tuple.
The tuple (200, 201) is called a nested tuple as it
a=(3,1,2,5,4,6)
is inside another tuple. sum(a)
Output: 21
KVS – Regional Office, JAIPUR | Session 2021-22
5. tuple() 2. Write a Python program which accepts a
sequence of comma-separated numbers from
# Creating an empty tuple
user and generate a list and a tuple with those
t1 = tuple()
numbers.
# creating a tuple from a list
t2 = tuple([1, 4, 6]) Ans.
# creating a tuple from a string
values = input("Enter some no. separated by , ")
t1 = tuple('Python')
list = values.split(",")
# creating a tuple from a dictionary
tuple = tuple(list)
t1 = tuple({1: 'one', 2: 'two'})
print('List : ',list)
6. count() print('Tuple : ',tuple)
Return the number of times the value X appears in 3. Write a python program to print sum of
the tuple: tuple elements.
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5) Ans.
x = thistuple.count(5)
test_tup = (7, 5, 9, 1, 10, 3)
print(x)
print("The original tuple is : " + str(test_tup))
Output: 2 res = sum(list(test_tup))
# printing result
print("The sum of all tuple elements are : " +
7. index() str(res))
The index() method returns the index of the
specified element in the tuple. 4. Write a python program to Check if the given
Example 1: Find the index of the element element is present in tuple or not.

vowels = ('a', 'e', 'i', 'o', 'i', 'u') Ans.


index = vowels.index('e') test_tup = (10, 4, 5, 6, 8)
print('The index of e:', index) # printing original tuple
index = vowels.index('i') print("The original tuple : " + str(test_tup))
print('The index of i:', index) N = int(input("value to be checked:"))
Output res = False
for ele in test_tup :
The index of e: 1 if N == ele :
The index of i: 2 res = True
break
print("Does contain required value ? : " + str(res))
Programs on Tuples
1. Write a Python program to test if a variable
is a tuple or not. 5. Write a Python program to find the length of
a tuple.
Ans.
Ans
x = ('tuple', False, 3.2, 1)
if type(x) is tuple: #create a tuple
print('x is a tuple') tuplex = tuple("KVS RO JAIPUR")
else: print(tuplex)
print('Not a tuple.') #use the len() to find the length of tuple
print(len(tuplex))
KVS – Regional Office, JAIPUR | Session 2021-22
6. Write a Python program calculate the
product, multiplying all the numbers of a given
tuple.
Ans
nums = (4, 3, 2, 2, -1, 18)
print ("Original Tuple: ")
print(nums)
temp = list(nums)
product = 1
for x in temp:
product *= x
print(product)

7.Write a Python program to calculate the


average value of the numbers in a given tuple
of tuples.
Ans
nums = ((10, 10, 10, 12), (30, 45, 56, 45),
(81, 80, 39, 32), (1, 2, 3, 4))
print ("Original Tuple: ")
print(nums)
result = [sum(x) / len(x) for x in zip(*nums)]
print("\nAverage of numbers:\n",result)

8. Write a Python program to check if a


specified element presents in a tuple of tuples.
Ans:
colors = (
('Red', 'White', 'Blue'),
('Green', 'Pink', 'Purple'),
('Orange', 'Yellow', 'Lime'),
)
print("Original list:")
print(colors)
c1 = 'White'
result = any(c in tu for tu in colors)
print(result)

KVS – Regional Office, JAIPUR | Session 2021-22


DICTIONARY
Key points: -
- Python Dictionaries are a collection of some key:value pairs.
- Python Dictionaries are unordered collection
- Dictionaries are mutable means values in a dictionary can be changed using its key
- Keys are unique.
- Enclosed within brace { }

Working with dictionaries


Creating Python Dictionary # empty dictionary
my_dict = {}
# dictionary with integer keys
dict( ) method my_dict = {1: 'apple', 2: 'ball'}
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
# using dict()
my_dict = dict({1:'apple', 2:'ball'})
Accessing Elements from my_dict = {'name': 'Jack', 'age': 26}
Dictionary print(my_dict['name'])
print(my_dict.get('age'))
get( ) method
# Trying to access keys which doesn't exist returns None
print(my_dict.get('address'))

# KeyError
print(my_dict['address'])

Output: -
Jack
26
None
Traceback (most recent call last):
File "<string>", line 15, in <module>
print(my_dict['address'])
KeyError: 'address'
Changing and Adding Dictionary # Changing and adding Dictionary Elements
elements my_dict = {'name': 'Jack', 'age': 26}

# update value
my_dict['age'] = 27
print(my_dict)

# add item
my_dict['address'] = 'Downtown'
print(my_dict)

Output: -
{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

KVS – Regional Office, JAIPUR | Session 2021-22


Removing elements from # Removing elements from a dictionary
Dictionary squares = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

pop( ) method # remove a particular item, returns its value


print(squares.pop(4))
popitem method( ) print(squares)

clear( ) method # remove an arbitrary item, return (key,value)


print(squares.popitem())
del function print(squares)

# remove all items


squares.clear()
print(squares)

# delete the dictionary itself


del squares

Output: -
16
{1: 1, 2: 4, 3: 9, 5: 25}
(5, 25)
{1: 1, 2: 4, 3: 9}
{}

len() – dict={'Name':'Aman','Age':37}
Finding number of items in print("Length: - ", len(dict))
dictionary OUTPUT
Length:- 2

keys() - x=dict(name=“Aman",age=37,country=“India")
returns all the available keys print(x.keys())
OUTPUT
dict_keys(['country', 'age', 'name'])

values()- x=dict(name=“Aman", age=37, country=“India")


returns all the available values print(x.values())
OUTPUT
dict_values(['India',37,'Aman'])

items()- x=dict(name="Aman",age=37,country="India")
return the list with all dictionary print(x.items())
keys with values. OUTPUT-
dict_items([('country','India'),('age',37),('name','Aman')])

KVS – Regional Office, JAIPUR | Session 2021-22


update()- x=dict(name="Aman",age=37,country="India")
used to change the values of a key d1=dict(age=39)
and add new keys x.update(d1,state="Rajasthan")
print(x)
OUTPUT-{'country':'India','age':39,'name':'Aman','state':'Rajasthan'}

fromkeys()i- is used to create keys={'a','e','i','o','u'}


dictionary from keys value="Vowel"
vowels=dict.fromkeys(keys,value)
print(vowels)
OUTPUT-{'i':'Vowel','u':'Vowel','e':'Vowel','a':'Vowel','o':'Vowel'}

copy()- x=dict(name="Aman",age=37,country="India")
returns a shallow copy of the y=x.copy()
dictionary. print(y)
OUTPUT->{'country':'India','age':37,'name':'Aman'}

Dictionary Membership Test #Membership Test for Dictionary Keys


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
in
print(1 in squares)
not in print(2 not in squares)
print(49 in squares)

Output -
True
True
False

Iterating Through a Dictionary # Iterating through a Dictionary


squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
print(squares[i])

KVS – Regional Office, JAIPUR | Session 2021-22


Multiple choice questions based on Dictionary
1 Which of the statement(s) is/are correct.
i. Python dictionary is an ordered collection of items.
ii. Python dictionary is a mapping of unique keys to values
iii. Dictionary is mutable.
iv. All of these.
2 Which function is used to return a value for the given key.
i. len( ) ii. get( ) iii. keys( ) iv. None of these

3 Keys of the dictionary must be


i. similar ii. unique iii. can be similar or unique iv. All of these

4 Which of the following will delete key-value pair for key=’red’ form a dictionary D1
i. Delete D1(“red”) ii. del. D1(“red”) iii. del D1[“red”] iv. del D1

5 Which function is used to remove all items form a particular dictionary.


i. clear( ) ii. pop( ) iii. delete iv. rem( )

6 In dictionary the elements are accessed through


i. key ii. value iii. index iv. None of these

7 Which function will return key-value pairs of the dictionary


i. key( ) ii. values( ) iii. items( ) iv. get( )
8 To create a dictionary , key-value pairs are separated by…………….
i. (;) ii. ( , ) iii. (:) iv. ( / )
9 Which of the following statements are not correct:
a. An element in a dictionary is a combination of key-value pair
b. A tuple is a mutable data type
c. We can repeat a key in dictionary
d. clear( ) function is used to deleted the dictionary.

i. a,b,c ii. b,c,d iii. b,c,a iv. a,b,c,d


10 Like lists, dictionaries are which mean they can be changed.
i. Mutable ii. immutable iii. variable iv. None of these
11 To create an empty dictionary , we use
i. d=[ ] ii. d =( ) iii. d = {} iv. d= < >
12 To create dictionary with no items , we use
ii. Dict ii. dict( ) iii. d = [ ] iv. None of these
13 What will be the output
>>>d1={‘rohit’:56,”Raina”:99}
>>>print(“Raina” in d1)
i. True ii. False iii. No output iv. Error

KVS – Regional Office, JAIPUR | Session 2021-22


FUNCTIONS
Large programs are often difficult to manage, thus Syntax
large programs are divided into smaller units
known as functions. def <function_name> ( [parameters]) :
DEFINITION [“ “ “ <function’s docstring> “ “ “]
A Function is a subprogram that acts on data and <statement>
often returns a value. [<statement>]
ADVANTAGES OF FUNCTION :
1. To make program handling easier as only a In a syntax language :
small part of the program is dealt with at a
time, thereby avoiding ambiguity. ● Item(s) inside angle brackets < > has to be
2. To reduce program size. provided by the programmer.
3. To reuse the code. ● Item(s) inside square brackets [ ] is
optional, i.e., can be omitted.
TYPES OF FUNCTION ● Item(s)/words/punctuators outside < >
1.Built-in functions and [ ] have to be written as specified.
These are pre-defined functions and are always
available for use. Example –
Example – len( ), type( ), int( ) etc. def sum(a,b):
2. Functions defined in modules s = a+b
These functions are predefined in particular return s
modules and can only be used when the Or
corresponding module is imported.
Example – import math def my_msg( ) :
print(math.sqrt(4)) print(“Learning to create function”)
3. User defined functions
These are defined by the user. Users can create CALLING A FUNCTION
their own functions. To call a function, use the function name followed
by parentheses
USER DEFINED FUNCTION
Following are the rules to define a User Defined print(sum(4,5))
Function in Python 9
Function Header
Function definition begins with the keyword def my_msg()
followed by the function name and parentheses ( ) Learning to create function
and ends with a colon ‘:’.
Parameters FLOW OF EXECUTION IN A FUNCTION CALL
Variables that are listed within the parantheses of The Flow of Execution refers to the order in which
a function header statements are executed during a program run.
Function Body A function body is also a block. In Python, a block is
The block of indented-statements beneath executed in an execution frame.
function header that defines the action performed An execution frame contains:
by the function. *some internal information (used for debugging)
Indentation *name of the function
The blank space in the beginning of a statement *values passed to function
within a block. All statements within same bloc *variables created within function
have same indentation. *information about the next instruction to be
executed.
KVS – Regional Office, JAIPUR | Session 2021-22
Example: positional parameters.
def sum(a,b): #statement 2 Example:
s = a+b #statement 3
return s #statement 4 def Test(x,y,z): #function definition header
__main__ .
print(sum(4,5)) #statement 1 .
Program executes as follows: .
Statement2 --> Statement1 --> Then we can call function using following
Statement2 --> Statement3 --> statements
Statement4 --> Statement1. p,q,r=3,4,6
Test(p,q,r) #3 variables are passed
FUNCTIONS PARAMETERS Test(4,q,r) # 1 literal and 2 variables are passed
A function has two types of parameters: Test(5,6,7) # 3 literals are passed.
1. Actual Parameters So x,y,z are positional parameters and the value
2. Formal Parameters must be provided to these parameters

1.ACTUAL PARAMETERS (ii) Default Parameters


The values being passed through a function-call The parameters which are assigned with a value
statement are called actual parameters (or actual in function header while defining the function
arguments or arguments). are known as default parameters.
At the time of the call each actual parameter is This value is optional for the parameter.
assigned to the corresponding formal parameter in If a user explicitly passes the value in function
the function definition call, then the value which is passed by the user
Example: will be taken by the default parameter. If no
def ADD(x,y): # x, y are formal parametersvalue is provided, then the default value will be
z=x+y
taken by the parameter.
print(“Sum=”,z)
Default parameters will be written in the end of
a=int(input(“Enter first no”)) the function header, means positional
b=int(input(“Enter second no”)) parameter cannot appear to the right side of
ADD(a,b) # a, b are actual parameters default parameter.
Example:
2.FORMAL PARAMETERS def CalcSI(amount, rate, time=5):
The values received in the function #Function definition header
definition/header are called formal parameters .
(or formal arguments or parameters). .
Formal parameters are local variables which are .
assigned values from the arguments when the Then we can call function using following
function is called. statements
Python supports three types of formal CalcSI(5000, 4.5) # Valid , the value of time
parameters: parameter is not provided, so it will take
i. Positional parameters default value 5.
ii. Default parameters CalcSI(5000,4.5, 6) # Valid , the value of time
iii. Keyword (or named) arguments will be 6.
(i) Positional Parameters Valid /Invalid example to define function with
When the function call statement must match default arguments:
the number and order of arguments as defined CalcSI(p, rate=4.5, time=5): #Valid
in the function definition, this is called the CalcSI(p, time=5, rate=4.5): # Valid
KVS – Regional Office, JAIPUR | Session 2021-22
CalcSI(p, rate=4.5, time): #Invalid, Example 2: Storing the return value separately
Positional argument cannot come after default def sum(a,b,c):
argument. return a+5,b+4,c+7
CalcSI(p=5000, rate=4.5, time=5): # Valid
s1,s2,s3=sum(2,3,4)
(iii) Keyword (or named) arguments print(s1,s2,s3)
The named arguments with assigned values passed Output:
in the function call statement are called keyword 7 7 11
arguments.
Here, you can write any argument in any order (b) Function not returning any value (void
provided you name the argument. functions)
Example: def message():
print(“Hello”)
def CalcSI(amount, rate, time):
#Function definition header message()
Then we can call function using following m=message()
statements print(m)
CalcSI(amount=2000 , rate=0.10, time=5)
CalcSI(time=4 , amount=2600 , rate=0.09) Output:
CalcSI(time=2 , rate=0.12 , amount=2000) Hello
Hello
RETURNING VALUES FROM FUNCTIONS None
There are two types of functions according to
return statement: So, now you know that Python can have following
a). Function returning some value (non-void four possible combinations of functions:
function) (i) non-void functions without any
b). Function not returning any value (void arguments
function) (ii) non-void functions with some
NOTE: arguments
The return statement is used to exit a function (iii) void functions without any arguments
and go back to the place from where it was called. (iv) void functions with some arguments
(a) Function returning some value
Syntax: SCOPE OF VARIABLES:
return <expression/value> Scope of a variable is the portion of a program
where the variable is recognized and can be
Example 1: Function returning one value accessed therein.
def my_function(x):
return 5*x There are two types of scope for variables:
1. Local Scope
Example 2: Function returning multiple values 2. Global Scope
def sum(a,b,c):
return a+5,b+4,c+7 1.Local Scope:
A variable declared in a function-body is said to
S=sum(2,3,4) have local scope.
print(S) It can not be accessed outside the function. In
Output: this scope, the lifetime of variables inside a
(7, 7, 11) # it is a tuple function is as long as the function executes.

KVS – Regional Office, JAIPUR | Session 2021-22


2.Global Scope:
A variable declared in top level segment MUTABLE/IMMUTABLE PROPERTIES OF
(__main__) of a program is said to have a global PASSEED DATA OBJECTS
scope. Depending on the mutability/immutability of its
In this scope, lifetime of a variable inside a data type, a variable behaves differently. i.e. if a
program is as long as the program executes. variable is referring to an immutable type then any
Example 1: change in its value will also change the memory
def Sum(x , y) : address it is referring to, but if a variable is
z=x+y referring to mutable type then any change in the
return z value of mutable type will not change the memory
a=4 address of the variable.
b=6 Example:
s = Sum(a , b) 1.Passing immutable type value to a function.
print(s) def myFunc(a) :
In the above program a=a+2
x, y and z are local variables and are destroyed print(“value of ‘a’ in function: ”,a)
once we return from the function. num=3
a, b and s are global variables and remains in print(“value of ‘num’ before function call: ”, num)
the memory until the program executes.
myFunc(num)
Example 2: print(“value of ‘num’ after function call: ”, num)
def my_func( ):
x=10 # local variable Output:
print(“Value inside function:”,x) value of ‘num’ before function call: 3
x=20 # global variable value of ‘a’ in function: 5
my_func( ) value of ‘num’ after function call: 3
print(“Value outside function:”,x)
Output: in the above code the function myFunc() received
Value inside function:10 the passed value in parameter a and then changed
Value outside function:20 the value of a by performing some operation on it.
Inside
Here, we can see that the value of x is 20
initially. Even though the function my_func() 2.Passing mutable type value to a function.
changed t he value of x to 10, it did not affect def myFunc(list) :
the value outside the function. list[1]=5
print(“List within called function, after
change: ”, list)
This is because the variable x inside the function
is different (local to the function) from the one list1=[1,2,3]
outside. Although they have same names, they print(“List before function call: ”,list1)
are two different variables with different scope. myFunc(list1)
print(“List after function call: ”,list1)
On the other hand, variables outside of the
function are visible from inside. They have a Output:
global scope. List before function call: [1,2,3]
List within called function, after change: [1,5,3]
List after function call: [1,5,3]

KVS – Regional Office, JAIPUR | Session 2021-22


Data File Handling
TEXT FILE

Files are collection of bytes stored on storage Operations related to Text files
devices such as hard-disks. Files help in
storing information permanently on a I. File Opening: Files can be opened in
computer. Data files are files that store data python by using the open( ) method as
pertaining to a specific application. Data files follows:
can be stored in following ways:
<file_obj>=open(‘<file_path>’,’access_mode’)
· Text files: These files store information in the
form of a stream of ASCII or UNICODE Here <file_obj> is the file handle which
characters. Each line is terminated by an EOL provides the access to the physical file stored
character. on a computer. The file object is also called the
file pointer. It accesses the contents of the file
· CSV (Comma Separated Values) files: These in a sequential manner. All the operations can
files use a specific character to separate the be performed on the file only through the file
values. pointer. The open( ) method accepts one
required argument which is the path of the file
· Binary files: These files store information in to opened. The second argument
the form of a stream of bytes. No EOL ‘access_mode’ is optional and defines the
character is used and binary files hold operations that can be performed on the file
information in the same format in which it is once it is opened. The default access mode is
held in the memory. ‘read mode’.

Absolute and Relative Paths Note: While specifying the path of the file, one
must either use ‘\’ to escape all the special
Path of a file is a sequence of the directories to characters in the path or make it a raw string
access that file on a computer. by adding ‘r’ in front of the path string.
Different access modes are described in Table
Absolute Path is the full path starting from the
1. For example, in order to open a text file
root directory to locate a particular file in a
named ‘myfile.txt’, the following syntax will be
computer system. Example of an absolute
used:
path is:
f = open(r’D:\MyFolder\myfile.txt’, ‘r’)
‘E:\ClassXII\SectionA\test.py’

Relative Path is the path of the file relative to


the current working directory. For example,
with ‘SectionA’ as current working directory
the relative path of test.py will be

‘.\test.py’

KVS – Regional Office, JAIPUR | Session 2021-22


Table 1: Access Modes for files a+ write, Allows both reading and
read writing operations. It
Acc Suppo Remarks retains the previous
ess rted contents of the file and
Mo Operat creates a new file if it does
de ions not exist at the specified
location.
r read Allows only reading
operation. The file must
exist on the specified II.File Reading: Once the file is opened
location, otherwise raises using the open( ) function, file reading can be
I/O error. performed by using any of the following three
functions:
w write Allows only writing
operation and overwrites a. f.read([n]): This function accepts an
the contents of the file. optional integer argument ‘n’ and returns n-
Unlike read mode, creates a bytes from the file. If ‘n; is not specified by the
file if the specified file does user, then it reads all the contents of the file at
not exist instead of raising once and returns in string format. The
I/O error. examples are as follows:

a append Allows only writing Myfile


operation. Does not raise
I am groot.
I/O error, instead creates a
new file at the specified
location. Unlike write mode, CODE OUTPUT
retains the previous
contents of the file and f=open(r’MyFile’,’r’) I am groot.
appends the new content in data = f.read( )
the file. print(data)
f.close( )
r+ read, Allows read and write
write operation. The file must f=open(r’MyFile’,’r’) I am
exist on the specified data = f.read(4 )
location, otherwise raises print(data)
I/O error. f.close( )
w+ write, Allows writing and reading
read operations. It overwrites b. f.readline([n]): This function accepts an
the previous contents of the optional integer argument and returns n-
file. If the file does not exist bytes after reading from the file.
at the specified location,
creates a new one.

KVS – Regional Office, JAIPUR | Session 2021-22


If ‘n’ is not specified, then it reads only one line III. File Writing: For writing content into
and returns it in string format. The examples text files in python, the file must be opened
are as follows: using the ‘w’ or ‘a’ access mode. File writing
can be performed by using following two
Myfile
functions:
I am groot.
I am Peter. a. f.write(str): This function accepts the
How are you? string str and writes this string into the file.
The examples of the f.write(str) function are
as follows:
CODE OUTPUT
Myfile
f=open(r’MyFile’,’r’)
line1=f.readline( ) I am groot.
print(“Line 1-“,line1) I am groot. I am Peter.
line2=f.readline( ) How are you?
I am Peter.
print(“Line 2-“,line2)
line3=f.readline( ) How are you? CODE OUTPUT
print(“Line 3-“,line3)
f.close( ) f=open(r’MyFile’,’w’)
data = ‘I have a cat.’
f=open(r’MyFile’,’r’) f.write(data)
data = f.readline(5) f.close( )
I am
print(data) f=open(r’MyFile’,’r’)
f.close( ) data = f.read( )
print(data)
I have a cat.
c. f.readlines( ): This function does not accept f.close( )
any argument. It reads all the content of the
text file at once and returns a list containing Note: Opening file in write mode overwritten
all the lines as individual elements. The the file contents,so be carefull. Use append
examples are as follows: mode in such situations.
CODE OUTPUT
b. f.writelines(lst): This function accepts
f=open(r’Myfile’,’r’) [‘I am groot.’, multiple lines in the form of a list and writes
data = f.readlines( ) ‘I am Peter’, all the lines into the file. The examples are:
print(data) ‘How are you?’]
f.close( )

Note: f is the file pointer. All the operations


will be performed in the file referenced by f.

KVS – Regional Office, JAIPUR | Session 2021-22


The with statement combines the following
operations - opening of file, exception
CODE OUTPUT handling and closing of file.
VI. seek( ) and tell( ) methods: The
f=open(r’Myfile’,’a’) seek( ) function allows us to change the
data = [‘I have a dog., position of the file pointer in the opened file as
‘\nI love my cat.’] # It will append follows:
f.writelines(data) the content. f.seek(offset,mode)
f.close( ) The seek() method accepts offset as an
f=open(r’Myfile’,’r’) argument which specifies the offset in the
data = f.read( ) I have a cat.I have a number of bytes. The mode argument is
print(data) dog. optional and has three possible values namely
f.close( ) I love my cat. 0, 1 and 2 which correspond to beginning of
file, current position in file and end of file
Note: Here with append mode the two lines
respectively. The mode argument specifies
were added with the original file but second
the reference point from where the offset will
line was added without a newline.
be calculated to place the file pointer. The
flush(): This function forces python to write
default value of mode is 0.
the contents of memory buffer to the physical
The tell() method returns the current
file immediately instead of waiting to write all
position of the file pointer in the opened file. It
the contents of buffer to file on closing.
is used as follows:
IV. Closing a file: One must always close
f.tell( )
a file when the file is no longer required for
Myfile
any more operations. The file can be closed by
using the close( ) function which can be used I have a cat.I have a dog.
with the file pointer as follows: I love my cat.
<file_handle>.close( )
V. Opening file using ‘with’: Files can
CODE OUTPUT
also be opened by using the ‘with’ statement
as follows:
with open(‘path_of_file’,’access_mode’) as f=open(r'MyFile.txt','r')
<file_handle>: f.seek(7,0)

print("Reading from Reading from


CODE OUTPUT position-7
position-",f.tell())
with open(r’MyFile’,’r’)
data = f.read() a cat.I have a dog.
as f: I have a cat.I have
print(data) I love my cat.
data = f.read( ) a dog. f.close()
print(data) I love my cat.

KVS – Regional Office, JAIPUR | Session 2021-22


Important programs related to text file
handling:
3. Display the size of a file after removing EOL
1. Write a python program to count the characters, leading and trailing white spaces
number of lines in a file starting with the and blank lines.
letter A.
Solution:
Solution:
myfile = open(r’E:\poem.txt’,”r”)
myfile = open(r’E:\poem.txt’,”r”) str1 = “ “
countA = 0 size = 0
lines = myfile.readlines() tsize = 0
for line in lines: while str1:
if line[0]==’A’ or line[0]==’a’: str1 = myfile.readline()
countA += 1 tsize = tsize + len(str1)
size = size + len(str1.strip())
print(“The number of lines starting with A
print(Size of file after removing all EOL
are “, countA)
characters & blank lines:”, size)
print(“the total size of the file is :”, tsize)
2. Write a program to count and display the myfile.close()
number of lines in a file.

Solution: 4. Write a program to display the size of a file


in bytes
myfile = open(r’E:\poem.txt’,”r”)
s = myfile.readlines() Solution:
lc = len(s)
myfile = open(r’E:\poem.txt’,”r”)
print(“The number of lines in the file “, lc)
Str = myfile.read()
myfile.close()
size = len(Str)
print(“Size of the given file poem.txt is “)
print(size, “bytes”)
myfile.close()

KVS – Regional Office, JAIPUR | Session 2021-22


Binary Files
* In binary file data is in unreadable format and to rb+ = Open binary file in read & write mode.
work on a binary file we have to convert the data (file must be existed)
into readable form for read as well as write wb+ = Open binary file in write & read mode.
operation. (new file created, overwritten if existed)
* The binary file stores some objects which have ab+ = Open binary file in append (write &
some structure associated with them. Like list, read) mode. (open if exists otherwise create
nested list, tuple, dictionary etc. new file)
* These objects are first serialized and then stored
in a binary file. BASIC OPERATIONS IN BINARY FILE
* If a binary file (existing) open for reading · Creating a new file
purpose, when the last record is reached (EOF · Reading from file
reached), it may raise an EOFError exception, if not · Writing into file
handled properly. · Appending the file
* Thus a binary file should open for reading · Searching in File
purposes either in “try and except” blocks or using · Deleting data from file
“with statement”. · Creating a copy of file

Serialization or Pickling: OPEN AND CLOSE BINARY FILE


It is the process of transforming a python object to open( ) function:
a stream of bytes called byte streams. These byte Syntax:
streams can then be stored in binary files. File_Object=open(file_name, access mode)
Serialization process is also called pickling. Example:
file_obj= open(“bin_file.dat”,'wb')
De-serialization or un-pickling: This statement opens bin_file.dat binary file in
It is the inverse of the pickling process where a write mode
byte stream is converted back to a Python object. Note : if file mode is not mentioned in open
The pickle module implements the algorithm for function then default file mode i.e 'rb' is used,
serializing and de-sterilizing the python objects
and deals with binary files. The Pickle Module must close() function:
be imported to read and write objects in binary The close( ) method of a file object flushes any
files. unwritten information and close the file
object after which no more writing can be done.
MODES OF BINARY FILES Example
b = Open the binary file file_obj.close( )
rb = Open binary file in read only mode (file
must be existed)
wb = Open binary file in write only mode WRITING INTO FILE- PICKLING
(new file created, overwritten if existed) To write an object into file, the file should
ab = Open binary file in append (write only) be opened in write mode. The dump( ) function of
mode. (open if exists otherwise create new the pickle module is used to write objects into a file.
file)
KVS – Regional Office, JAIPUR | Session 2021-22
Syntax: Expamle:
import pickle # Append the Binary file
File_Handler=open(“Bin_file.dat”,’wb’) import pickle
pickle.dump(python_Obj_to_be_Written, File_obj) stud={}
fwb=open("student.dat","ab")
Expamle: choice='y'
# Write Dictionary Object in Binary file while choice.lower()=='y':
import pickle rno=int(input("Enter Roll No: "))
stud={} name=input("Enter Name: ")
fwb=open("student.dat","wb") marks=float(input("Marks(out of 500): "))
choice='y' per=marks/5
while choice.lower()=='y': if(per>=33):
rno=int(input("Enter Roll No: ")) res="Pass"
name=input("Enter Name: ") else:
marks=float(input("Marks out of 500 ")) res="Fail"
per=marks/5 stud['rollno']=rno
if(per>=33): stud['name']=name
res="Pass" stud['Marks']=marks
else: stud['percent']=per
res="Fail" stud['result']=res
stud['rollno']=rno pickle.dump(stud, fwb)
stud['name']=name print("Record Saved in File")
stud['Marks']=marks choice=input("More Record(Y/N)? ")
stud['percent']=per fwb.close()
stud['result']=res
pickle.dump(stud, fwb) READING FROM BINARY FILE: UN-PICKLING
print("Record Saved in File") While working with a binary file for reading
choice=input("More Record(Y/N)? ") purposes the runtime exception EOFError raised
fwb.close() when it encountered the EOF position. This
EOFError exception can be handled with two ways.
APPENDING RECORD IN BINARY FILE 1. Use of try and except block
Binary file must open in append mode (i.e., "ab'") The try and except statements together, can
to append the records in file. A file opened in handle runtime exceptions. In the try block, i.e.,
append mode will retain the previous records and between the try and except keywords, write the
append the new records written in the file. code that can generate an exception and in the
except block, ie., below the except keyword, write
Syntax: what to do when the exception (EOF - end of file)
import pickle has occurred
File_Handler=open(“Bin_file.dat”,’ab’)
pickle.dump(python_Object_to_be_Written,
File_Handler)
File_object=(“binary File Name”,’access mode’)
KVS – Regional Office, JAIPUR | Session 2021-22
try: print("Searching in file student.dat...")
…………………………………………….………. try:
Write actual code, work in binary file frb=open("student.dat", "rb")
…………………………………………………….. while True:
except EOFError: stud=pickle.load(frb)
…………………………………………………… if stud['percent']>51.0:
Write Code here that can handle the error print(stud)
raised in try block. found+=1
………………………………………………… except EOFError:
if found==0:
print("No Record with marks>51")
2. Use of with statement else:
print(found," Record(s) found")
The with statement is a compact statement frb.close()
which combines the opening of file, processing of
file along with inbuilt exception handling and COPY OF FILE IN ANOTHER FILE
also closes the file automatically after with block import pickle # A COPY OF EXISTING FILE
is over. def fileCopy():
Explicitly, we need not to mention any exception ifile = open("student.dat","rb")
for the “with statement”. ofile = open("newfile.dat","wb")
try:
Syntax: while True:
with open(“File_Name”,’mode’) as File_Handler: rec=pickle.load(ifile)
pickle.dump(rec,ofile)
# Read Records from Binary file except EOFError:
import pickle ifile.close()
stud={} ofile.close()
frb=open("student.dat","rb") print("Copied successfully")
try:
while True: def display1():
stud=pickle.load(frb) ifile = open("student.dat","rb")
print(stud) print("----Records of Student file---")
except EOFError: try:
frb.close() while True:
rec=pickle.load(ifile)
print(rec)
except EOFError:
ifile.close()
SEARCHING RECORD FROM FILE def display2():
import pickle ofile = open("newfile.dat","rb")
stud={} print("----Records of Copy file---")
found=0 try:
KVS – Regional Office, JAIPUR | Session 2021-22
while True: # will place the file pointer at 20th byte from the
rec=pickle.load(ofile) beginning of the file (default)
print(rec) f.seek(20,1) # will place the file pointer at 20th
except EOFError: byte ahead of current file-pointer position (mode =
ofile.close() 1)
fileCopy() f.seek(-20,2)
display1() # will place file pointer at 20 bytes behind
display2() (backward direction) from end-of file (mode = 2)
f.seek(-10,1) # will place file pointer at 10 bytes
RANDOM ACCESS & UPDATING BINARY FILE behind from current file-pointer position (mode =
Python provides two functions that help to 1)
manipulate the position of the file pointer and we Note:
can read and write from the desired position in the ·Backward movement of file-pointer is not possible
file. The Two functions of Python are: tell() and from the beginning of the file (BOF).
seek() · Forward movement of file-pointer is not possible
(i) The tell() Function from the end of file (EOF).
tell() method can be used to get the current
position of File Handle in the file. This method PROGRAM OF tell() and seek()
takes no parameters and returns an integer value. import pickle
Initially the file pointer points to the beginning ofstu={ }
the file(if not opened in append mode). found =False
Syntax # open binary file in read and write mode
fileObject.tell( ) rfile=open(“student.dat”, “rb+”)
This method returns the current position of the file # Read from the file
read/write pointer within the file. try:
(ii) The seek( ) Fuction while True:
In Python, seek() function is used to change the pos=rfile.tell()
position of the File Handle to a given specific stu=pickle.load(rfile)
position in the file. if stu[“marks”] == 81:
Syntax
stu[“Marks”] +=2
fileObject.seek(offset, mode) rfile.seek(pos,0)
where pickle.dump(stu, rfile)
offset is a number-of-bytes found=True
mode is a number from 0 or 1 or 2 except EOFError:
0: sets the reference point at the beginning of the if found==False:
file. print(“Sorry, No Record found”)
1: sets the reference point at the current file else:
position. Print(“Record(s) updated”)
2: sets the reference point at the end of the file. rfile.close()
Example:
f=open(“chapter.dat,’rb’)
f.seek(20)

KVS – Regional Office, JAIPUR | Session 2021-22


DELETE FILE
To delete a file, import the OS module, and run its
os.remove( ) function:

#Remove the file “demofile.txt”


import os
os.remove("demofile.txt")
Check if File exist:
To avoid getting an error, we might want to check
if the file exists before try to delete it:
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")

Delete Folder
To delete an entire folder, use the os.rmdir()
method:
import os
os.rmdir("myfolder")
Note: Only empty folders can be removed.

# file contains dict obj


import pickle
import os
def delete_rec():
f1 = open("student.dat","rb")
f2 = open("temp.dat","wb")
rn=int(input("Enter rollno to delete:"))
try:
while True:
d = pickle.load(f1)
if d["rollno"]!=rn:
pickle.dump(d,f2)
except EOFError:
print("Record Deleted.")
f1.close()
f2.close()
os.remove("student.dat")
os.rename("temp.dat","student.dat")
delete_rec()
KVS – Regional Office, JAIPUR | Session 2021-22
CSV File
• CSV is processed by almost all existing
CSV is s a file format for data storage which looks
applications
like a text file. The information is organized with
one record on each line and each field is separated CSV Disadvantages
by comma. • No standard way to represent binary data
• There is no distinction between text and
● A Comma Separated Values (CSV) file is a
numeric values
plain text file that contains the comma-
separated data. • Poor support of special characters and
● These files are often used for exchanging control characters
data between different applications. • CSVallows to move most basic data only.
● CSV files are usually created by programs Complex configurations cannot be imported
that handle huge amounts of data. They are and exported this way.
used to export data from spreadsheets (ex:- • Problems with importing CSV into SQL (no
excel file) and databases (Ex:- Oracle, distinction between NULL and quotes)
MySQL). It can be used to import data into a
spreadsheet or a database. CSV File Structure
CSV File Characteristics:
## sample.csv file structure
• One line for each record Name, DOB, City
• Comma separated fields Ram, 12-Jul-2001, Delhi
• Space-characters adjacent to commas are Mohan, 23-Jan-2005, Delhi
ignored
Suraj, 17-Dec-2002, Kolkata
• Fields with in-built commas are separated
by double quote characters.
When Use CSV?
• When data has a strict tabular structure Python CSV Module
• To transfer large database between ● CSV Module is available in Python Standard
Library.
programs
● The CSV module contains classes that are
• To import and export data to office used to read and write tabular form of data
applications. into CSV format.
• To store, manage and modify shopping cart ● To work with CSV Files, programmer have
to import CSV Module.
catalogue

Why Use CSV / Advantages


import csv
• CSV is faster to handle Methods of CSV Module :
• CSV is easy to generate · writer( )
· reader( )
• CSV is human readable and easy to edit
manually Both the methods return an Object of writer or
• CSV is simple to implement and parse reader class. Writer Object again have two
methods – writerow( ) , writerows( ).
KVS – Regional Office, JAIPUR | Session 2021-22
writer( ) Methods reader( ) Methods
This function returns a writer object which is This function returns a reader object which will
used for converting the data given by the user be used to iterate over lines of a given CSV file.
into delimited strings on the file object. r_obj = csv.reader( csvfile_obj )

writer( ) Object Methods – To access each row, we have to iterate over this
· w_obj . writerow( <Sequence> ) : Object.
Write a Single Line for i in r_obj:
· w_obj . writerows ( <Nested Sequence> ) : print(i)
Write Multiple Lines
Example:-
Example:- import csv
# writerow() f=open("myfile.csv",'r')
import csv r_obj = csv.reader(f)
row=['Nikhil', 'CEO', '2', '9.0'] for data in r_obj:
f=open("myfile.csv", 'w') print(data)
w_obj = csv.writer(f) f.close()
w_obj.writerow(row)
f.close() If we consider the sample.csv file given above in
the CSV file structure the output of the above
code will be:
# writerows() ## OUTPUT
import csv
rows = [['Nikhil','CEO','2','9.0'], ['Name', 'DOB', 'City']
['Sanchit','CEO','2','9.1']] ['Ram', '12-Jul-2001', 'Delhi']
f=open("myfile.csv",'w') ['Mohan', '23-Jan-2005', 'Delhi']
w_obj = csv.writer(f) ['Suraj', '17-Dec-2002', 'Kolkata']
w_obj.writerows(rows)
f.close()

KVS – Regional Office, JAIPUR | Session 2021-22


KVS – Regional Office, JAIPUR | Session 2021-22

You might also like