Class 12 Computer Science Material Total
Class 12 Computer Science Material Total
CLASS 12
Supporting material
i x
nde
1
1. Basics of Python
What is programming?
An ordered set of instructions to be executed by a computer to carry out a specific task is called a program, and the
language used to specify this set of instructions to the computer is called a programming language.
What is python?
Python is a general purpose, high level, dynamic, interpreted programming language and it supports oops concepts
to develop an applications.
Modes of execution:
There are two modes for using the Python interpreter:
1. Interactive Mode:
In interactive mode (python.exe/py.exe), the result is returned immediately after pressing the
enter key.
2. Script Mode:
In script mode (IDLE), a file must be created and saved before executing the code to get results.
History:
The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in Netherland.In
February 1991, Guido Van Rossum published the code (labeled version 0.9.0)
FEATURES OF PYTHON
▪ Easy-to-Learn: Python has few keywords, simple structure, and a clearly defined syntax. This allows the
student to pick up the language quickly.
▪ Easy-to-read: Python code is more clearly defined and visible to eyes.
▪ Easy-to-maintain: Python’s source code is fairly easy-to-maintaining.
▪ A broad standard library: Python’s bulk of the library is very portable andcross-platform compatible on UNIX,
and Windows.
▪ Interactive Mode: Python has support for an interactive mode which allows interactive testing and
debugging of code.
▪ Portable: Python can run on a wide variety of hardware platforms and has the same interface on all
platforms.
▪ Extendable: You can add low-level modules to the Python interpreter. These modules enable programmers
to add to or customize their tools to be more efficient.
▪ Databases: Python provides interfaces to all major commercial databases.
▪ GUI Programming: Python supports GUI applications that can be created and ported to many system calls,
libraries, and windows system, such as windows MFC, Macintosh, and the X Window system of UNIX.
▪ Scalable: Python provides a better structure and support for large programs than shell scripting.
▪ Dynamically Typed: We need to specify the data type of variable while creation. Python can understand the
data type of variable after storing the value. It is called dynamically typed.
Working with Python Python Code Execution:
Python’s traditional runtime execution model:
Source code you type is translated to byte code, which is then run by the Python Virtual Machine (PVM).
Your code is automatically compiled, but then it is interpreted.
2
Python Character Set:
A set of valid characters recognized by python. Python uses the traditional ASCII character set. The latest
version recognizes the Unicode character set. The ASCII character set is a subset of the Unicode character
set.
Letters: – A-Z, a-z
Digits: – 0-9 Special
Symbols: – Special symbol available over keyboard
White spaces: – blank space, tab, carriage return, new line, form feed
Other characters: - Unicode
1. Keywords:
▪ Keywords are predefined; reserved words used in programming that have special meanings to the
compiler.
▪ Keywords are part of the syntax and they cannot be used as an identifier.
▪ All the keywords except True, False and None are in lowercase.
3
2. Identifiers:
A Python identifier is a name used to identify a variable, function, class, module or other object.
Naming rules for identifier
DO e.g. (valid) DON’T e.g. (invalid)
Can be used a to z a=’hi’ Identifier should not start with digit (0 to 9) 9a=10
Any Length
▪ Starting an identifier with a single leading underscore indicates that the identifier is private.
▪ Starting an identifier with two leading underscores indicates a strong private identifier.
▪ If the identifier also ends with two trailing underscores, the identifier is a language-defined special
name.
Variable
▪ Variable in Python refers to an object — an item or element that is stored in the memory.
▪ Don’t need to specify the data type of variable.
▪ Python automatically get variable data type depending upon the value assigned to the variable.
▪ Variables in python do not have fixed locations.
▪ The location they refer to changes every time their values change.
▪ Variable declaration is implicit in Python, means variables are automatically declared and defined
when they are assigned a value the first time.
▪ Variables must always be assigned values before they are used in expressions as otherwise it will
lead to an error in the program. Wherever a variable name occurs in an expression, the interpreter
replaces it with the value of that particular variable.
name = ‘python' Assigning Values To Variable
a = 23 a = b = c = 10
a=-23 a,b,c=5,10,20
b = 6.2 a,b = 1,2
sum = a + b a,b = b,a
a=09 a,b=10,20
s=None c=a,b
b=0b101 Ad=True
c=0o73 a=bool(1)
k=0x9fe a=00
print(a) output:0
a,b=’Hi’ (unpack the sequence) print(a) ‘H’,
print(b) ‘i’
a='2000' print(a) 2000
4
Everything is an Object
▪ Python treats every value or data item whether numeric, string, or other type as an object in the
sense that it can be assigned to some variable or can be passed to a function as an argument.
▪ Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime of
that object.
▪ This ID is akin to the memory address of the object.
▪ The function id() returns the identity of an object.
A=10 Output:
print(id(A) 140735307844312
3. Literals
Literals in Python can be defined as number, text, or other data that represent values to be stored in
variables.
Literal collections: Literals collections in python includes list, tuple, dictionary, and sets.
Escape sequence:
The backslash “\” is a special character, also called the “escape” character.
It is used in representing certain whitespace characters:
S.No Escape char name Expression Output
1. \' Single Quote print('Who\'s this?') Who's this?
2. \’’ Double quote print('Who\"s this?') Who"s this?
2. \\ Backslash print('Interview\\Bit') Interview\Bit
3. \n New Line print("Hello\nWorld!") Hello
World!
5. \t Tab print('Interview\tBit') Interview Bit
6. \b Backspace print('Interview \bBit') InterviewBit
8. \ooo Octal value print("\110\105\114\114\117") HELLO
9. \xhh Hex value print("\x48\x45\x4C\x4C\x4F") HELLO
10 r sequence ignore print(r"Hello\nWorld") Hello\nWorld
5
4. Operators:
Operators can be defined as symbols that are used to perform operations on operands.
Operator Symbols Example Output
1. Arithmetic +, - ,* , %, /, //, ** print(10/2) 5.0
print(10%2) 5
print(10//2) 0
unary plus X=-10
Y=+(X) print(Y) -10
Unary minus a=-10
b=-a print(b) 10
2. Relational <, >, >=, <=, ==, != print(10> 20) False
print(10==10) True
print(“hello”<”Hello”) True
3. Assignment =, +=, -= ,*=, /=, //=,%=,**= b=50 50
print(a)
a+=5 55
print(a)
b/=b 1.0
print(a)
4. Logical and, or, not 50>10 and 1<4 True
10<5 or 5==6 False
print( not 5) False
5. Bitwise & (and) print (10 & 15) 10
| (or) print (25 | 10) 27
~ (not) print ( ~32) -33
^(XOR) print (5 ^ 3) 6
<< (left shift) 10 << 2 40
>> (right shift) 10 << 1 20
10>>2 2
10>>1 5
6. Membership in, not in print (50 in List) True
List = [10,30,50,70] print ("P" in name) True
name="Sai Priya" print ("p" in name) False
7. Identity is, is not print(id(a) ) 140721739598552
a=10 print(id(b)) 140721739598392
b=5 print (a is b) True
a=b Note: a and b are pointing same address.
Operator Explanation
Arithmetic Arithmetic Operators are used to perform arithmetic operations like addition, multiplication,
division etc.
Relational Relational Operators are used to compare the values.
Assignment Used to assign values to the variables.
Logical Logical Operators are used to perform logical operations on the given two variables or values.
Bitwise Bitwise operators are used to perform bitwise calculations on integers. The integers are converted
into binary format and then operations are performed bit by bit.
Membership The membership operators in Python are used to validate whether a value is found within a
sequence such as such as strings, lists, or tuples.
Identity Identity operators in Python compare the memory locations of two objects.
6
Expression output Expression output
10/5 2.0 10.0//7 1.0
10/3 3.3333333333333335 15//2 7
15/2 7.5 10.0//2 5.0
0/2 0.0
5/0 ZeroDivisionError
10//5 2 10.0%5 0.0
10//7 1 5%10 5
0//5 0 5%5 0
10%5 0
logical operator
Evaluates to either True or False based on the logical operands on either side. Every value is logically either True
or False. By default, all values are True except None, False, 0 (zero), empty collections "", (), [], {}, and few other
special values.
x or y if x is true, then x, else y 10 or 5 10
0 or 5 5
x and y if x is false, then x, else y 10 and 5 5
0 and 10 0
not x if x is false, then True, else False not 10 False
not 'hi' False not None True
not 0.0 True 10 and 20 or not 0 20
not 1.5 False 10 and 20 and not 0 True
not 0.1 False 10 and 20 and 1 1
not 50 False
Expression output Expression output
a='hi' print(a*b) TypeError:
b= 'bye'
print(a+b) 'hibye'
print(a,b) 'hi' 'bye'
a='100' a='100 '
b='10' c=10+int(a)
print(a+b) '10010' print(c) 110
print('hi' * 3) 'hihihi' print('hi' * 'h') TypeError:
2==2.0 True 'hello' or 'hi' 'hello'
2==2.00 True not 'hi' False
7
'hello' and 'hi' 'hi' True+None Error
True+True 2 True/True 1.0
True-True 0 True-False 1
True*True 1 True//True 1
5. Punctuators/Delimiters
These are the symbols that used in Python to organize the structures, statements, and expressions.
Used to implement the grammatical and structure of a Syntax.
, . ‘ “ \ [] { } ( ) @ -= += *= //= **== = << >>
8
Exercise
1. Which of the following is not a keyword?
a) Eval b) assert c) nonlocal d) pass
2. What error occurs when you execute the following Python code snippet?
apple = mango
a) SyntaxError b) NameError c) ValueError d) TypeError
3. What will be the value of X in the following Python expression?
X = 2+9*((3*12)-8)/10
a) 30.0 b) 30.8 c) 28.4 d) 27.2
4. Select all options that print. hello-how-are-you
a. print(‘hello’, ‘how’, ‘are’, ‘you’)
b. print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c. print(‘hello-‘ + ‘how-are-you’)
d. print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
5. Which of the following can be used as valid variable identifier(s) in Python?
a. total b. 7Salute c. Que$tion d. global
6.
What will be the output of the following
expression?float(5 + int(4.39 + 2.1) % 2)
a. 5.0 b. 5 c. 8.0 d. 8
7. What is the value of this expression?
3*1**3
a. 27 b. 9 c. 3 d. 1
8. Which of the following can be used as valid variable identifier(s) in Python?
a. total
b. 7Salute
c. Que$tion
d. global
9. Which of the following statement is correct for an AND operator?
a) Python only evaluates the second argument if the first one is False
b) Python only evaluates the second argument if the first one is True
c) Python only evaluates True if any one argument is True
d) Python only evaluates False if any one argument is False
10. What will be the output of the following statement?
print(14%3**2*4)
11. Which of the following expressions evaluates to False?
(a) not(True) and False (b) True or False
(c) not(False and True) (d) True and not(False)
12. What is the output of the following expression?
print(12 / 4)
a) 3.0 b) 3 c) 4 d) Error
13. What is the output of the following expression?
print(10.0 // 3)
a) 3.33 b) 3.0 c) 3 d) Error
14. print(0 // 8)
a) Error b) 0.0 c) 0 d) None
15. print(10.0 % 4)
a) 2.0 b) 2 c) 0 d) Error
16. Evaluate the expression: (3 < 5 or 7 < 2) and (6 > 1)
a) True b) False c) None d) Error
9
17. What is the output of the following expression?
not 10 > 5 and 2 < 11 or not 10 < 2
a) True b) False c) Error d) None
18. What will be the output of the following expression? 2 == 2.0
a) True b) False c) Error d) None
19. What will be the output of the following Python expression?
10 and 20 and not 0
a) 10 b) 20 c) True d) False
20. Which operator is used to check whether two variables refer to the same object in memory?
a) == b) != c) is d) in
21. What will be the result of the following code?
a = 100
b = 100
print(a is b)
a) True b) False c) Error d) None
10
2. Structure of Python
1. Expression:
▪ An expression is defined as a combination of constants, variables, and operators.
▪ An expression always evaluates to a value.
▪ A value or a standalone variable is also considered as an expression but a standalone operator is
not an expression.
▪ E.g. Expression 6-3*2+7-1 evaluated as 6
Algebraic Expression Python Expression Examples
axb–c a*b–c (i) 100 (iv) 3.0 + 3.14
(m + n) (x + y) (m + n) * (x + y) (ii) num (v) 23/3 -5 * 7(14 -2)
(ab / c) a*b/c (iii) num – 20.4 (vi) "Global" + "Citizen"
11
Types of Expression in Python
Constant Expressions x = 10 + 15
Arithmetic Expressions y=x**3+x-2+5/2
Integral Expressions x=10 y=5.00 result = x + int(y)
Floating Expressions result = float(x) + y
Relational Expressions 10+15>20
Logical Expressions r=x and y
Combinational Expressions result = x + (y << 1)
2. Comments:
Which is readable for programmer but ignored by python interpreter?
Single line comment Which begins with # sign? # this is for adding
Multi line comment either writes multiple lines beginning """this is my first python program"""
(doc-string) with # sign or use triple quoted multiple ''' adding two numbers '''
lines.
3. Statement:
▪ Set of instructions that can be executable by python interpreter.
▪ a statement is a unit of code that the Python interpreter can execute
x=4 #assignment statement
cube = x ** 3 #assignment statement
print (x, cube) #print statement
Empty also known as “Null Statement”, it does nothing.
def function(args):
pass
Simple: Any executable statement is called.
print(“Hi”)
Compound: Group of statements can be executed as single unit. Header and indentation.
Header: if 10%2==0:
_ _ _ _statement_1 print(‘even’)
_ _ _ _ statement_2 else:
print(‘odd’)
12
Built in Functions
Input or output Datatype conversion Mathematical Function Other functions
input() bool() ord() abs() __import__()
print() chr() set() divmod() len()
dict() str() max() range()
float() tuple() min() type()
int() pow()
list() sum()
Built in functions
print() print() Function is used to print output on the screen. print('Hello')
input() input() function is used to take input (data) from the user. name=input('Enter your name')
str() str() function converts the specified value into a string. b=str(input('Enter name'))
int() int() function converts the specified value into an integer b=int(input('Enter age'))
number.
bool() bool() function converts the given value to a Boolean value b=bool(input('Enter yes\no'))
( True or False )
type() type() function is used to get the type of an object. a=int(10.50)
5.Block & indentation: Group of statements is block. Indentation at same level creates a block.
Python Input and Output
input ():
▪ This function first takes the input from the user and converts it into a string.
The type of the returned object always will be <type 'str'>.
▪ It does not evaluate the expression it just returns the complete statement as String. Python
provides a built-in function called input which takes the input from the user.
▪ The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it to
the variable on left-hand side of the assignment operator (=).
▪ When the input function is called it stops the program and waits for the user’s input.
13
▪ When the user presses enter, the program resumes and returns what the user typed.
▪ input ([Prompt])
▪ Prompt is the string we may like to display on the screen prior to taking the input, and it is optional.
▪ name = input ('What is your name?\n')
▪ output: What is your name?
print():
▪ Function prints the message on the screen or any other standard output device.
▪ print(value(s), sep= ' ', end = '\n',)
▪ value(s) : Any value, and as many as you like. Will be converted to string before printed.
▪ sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one. By
default, Python uses a space (' ') as the separator.
▪ end=’end’: (Optional) Specify what to print at the end. Default: ‘\n’
value(s) : Any value, and as many as you like. Will be converted to string before printed.
sep=’separator’ :
The separator between the arguments to print() function in Python is space by default (soft space feature) ,
which can be modified and can be made to any character, integer or string as per our choice.
Default : sep=''
print("Hello", "how are you?", sep="---") Hello---how are you?
print('welcome','Hyd', sep='@') welcome@Hyd
print('09','12','2016', sep='-') 09-12-2016
end=’end’:
Specify what to print at the end. Default: ‘\n’.
By default Python‘s print() function ends with a newline.
print() function comes with a parameter called ‘end‘.
By default, the value of this parameter is ‘\n’, i.e. the new line character.
14
Type Conversion:
▪ The process of converting the value of one data type (integer, string, float, etc.) to another data
type is called type conversion.
▪ int() : int() function take float or string as an argument and return int type object.
▪ float() : float() function take int or string as an argument and return float type object.
▪ str() : str() function take float or int as an argument and return string type object.
▪ variables in Python are implicitly declared.
Implicit Type Python automatically converts one data type to another data- a=10
Conversion type. This process doesn't need any user involvement. name='Ram'
Explicit Type In Explicit Type Conversion, users convert the data type of an c=100
Conversion object to required data type. We use the predefined functions c=str(a)
like int(), float(), str() etc. a=10
b=float(a)
Dynamic Typing:
Data types of a variable depend/change upon the value assigned to a variable on each next statement.
X = 25 # integer type
X = “python” # x variable data type change to string on just next line
Y=X/5 # error!! String cannot be divided
Data Type:
Data type identifies the type of data values a variable can hold and the operations that can be performed
on that data.
Data Types Classes Description
Numeric int, float, complex holds numeric values
String str holds sequence of characters
Sequence list, tuple, range holds collection of items
Mapping dict holds data in key-value pair form
Boolean bool holds either True or False
Set set, frozenset hold collection of unique items
None NoneType Used for missing value
15
1. Number
Number data type stores numerical values only. It is further classified into three different types:
int num1 = int(input("enter a number")) -12,0,125
float num2 = float(input("Enter float a number)")) 2.5,-15.5
complex num3 = num3 = complex(input('Complex number')) 3+4j,2-2j
2. Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
Strings S= 'What are you doing'
Lists L=[10,20,'hi']
Tuples. T=(10,20,'hi')
Set myset = {"apple", "banana", "cherry",52}
3. Set
▪ Set is an unordered collection of items separated by commas and the items are enclosed in curly
brackets { }.
▪ A set is similar to list, except that it cannot have duplicate entries.
▪ Once created, elements of a set cannot be changed.
▪ set1 = {10,20,3.14,"New Delhi"}
▪ print(set1)
4. None
▪ None is a special data type with a single value. It is used to signify the absence of value in a
situation.
▪ None supports no special operations, and it is neither False nor 0 (zero).
▪ E.g a = None
5. Mapping
▪ Mapping is an unordered data type in Python.
▪ Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in curly
brackets { }.
▪ Dictionaries permit faster access to data. Every key is separated from its value using a colon (:) sign.
▪ E.g. d1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price':120}
6. Boolean
▪ Boolean represent one of two values: True or False.
▪ When you compare two values, the expression is evaluated and Python returns the Boolean
answer.
▪ Also, almost any value is evaluated to True if it has some sort of content.
print(10 > 9) True bool(False) False
print(10 == 9) False bool(None) False
print(10 < 9) False bool(0) False
bool("abc") True bool("") False
bool(123) True bool(()) False
bool(["apple","cherry"]) True bool([]) False
bool(1) True bool({}) False
bool(2) True a=bool('hi') True
16
Mutable and Immutable Objects in Python
▪ Everything in Python is an object. So, every variable holds an object instance.
▪ All objects in Python can be either mutable or immutable.
▪ When an object is initiated, it is assigned a unique object id.
▪ Its type is defined at runtime and once set can never change, however its state can be changed if it
is mutable. Generally, a mutable object can be changed after it is created, and an immutable object
can’t.
Mutable objects:
▪ Mutability means the ability to modify or edit a value.
▪ Mutable objects in Python enable the programmers to have objects that can change their values.
▪ They generally are utilized to store a collection of data.
▪ It can be regarded as something that has mutated, and the internal state applicable within an
object has changed.
▪ In mutable data types, we can modify the already existing values of the data types (such as lists,
dictionaries, etc.). Or, we may add new values or remove the existing values from our data types.
▪ Basically, we may perform any operation with our data without having to create a new copy of our
data type. Hence, the value assigned to any variable can be changed.
Immutable Objects
▪ Immutable objects in Python are objects wherein the instances do not change over the period.
▪ Immutable instances of a specific type, once created, do not change, and this can be verified using
the id method of Python
Flow of Execution
The flow of execution basically refers to the order in which statements are executed.
▪ Sequential flow: In sequential flow instructions of a program are executed one after the another
▪ Conditional Flow: In Conditional flow, flow of control of instructions in a program are changed
based on a condition.
▪ Iterative Flow: In iterative flow, a set of instructions are executed repeatedly based on a certain
condition.
▪ Flow control statements are used to control the flow of execution depending upon the specified
condition/logic.
17
I. Decision making / Conditional / Selection
Decision making statement used to control the flow of execution of program depending upon condition.
There are three types of decision-making statement.
1. if statements
2. if-else statements
3. if-elif-else
4. Nested if-else statement
1. if statement
▪ An if statement is a programming conditional statement that, if proved true, performs a function or
displays information.
▪ Syntax:
▪ if (condition):
▪ statement 1
▪ Statement 2
a=10
b=5
if a>b:
print("a is greater")
18
2. if-else statement
▪ If-else statement executes some code if the test expression is true (nonzero) and some other code
if the test expression is false.
▪ Syntax:
▪ if (condition):
▪ statement
▪ else:
▪ statement
a=10
b=5
if a>b:
print("a is greater ")
else:
print("b is greater")
3. if-elif-else
▪ It allows us to check for multiple expressions.
▪ If the condition for if is False, it checks the condition of the next elif block and so on.
▪ If all the conditions are False, the body of else is executed.
▪ Syntax:
▪ if (condition):
statement
▪ elif (condition):
statement
▪ elif (condition):
statement
▪ else:
▪ statement
19
z = 3
if z % 2 == 0:
print("z is divisible by 2")
elif z % 3 == 0:
print("z is divisible by 3")
else:
print("neither div by 2 nor
by 3")
20
II. Transfer statement
The transfer statement in python can be used to change the execution of the statement from its normal
sequence order. These statements are often used in loops for and while. Let’s have a look at the transfer
statements below.
1. break
2. continue
3. pass
1. break statement
The break statement in python can be used to break the loop execution based on some
condition.
2. continue statement
We can use continue statement to skip current iteration and continue next iteration.
3. pass statement
The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up
empty blocks of code which may execute during runtime but has yet to be written.
Output:
3
9
15
30
2. while loop
▪ It is used to execute a block of statement if a given condition is true. And when the condition become false,
the control will come out of the loop.
▪ The condition is checked every time at the beginning of the loop.
▪ Syntax
▪ X=1 variable initialization
▪ while (condition):
▪ statement
▪ X=X+1increment/decrement
n = 1
while n <= 3:
print('hello')
n = n + 1
Output:
hello
hello
hello
22
3. Nested Loops
▪ Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside
the for loop, etc.
▪ In Python, a break statement is used to exit the loop in which it is written. If placed in an outer
loop, it terminates only that outer loop. Any inner loops will also stop running after that point
because they are no longer being called by the outer loop.
4. Infinite Loops
▪ An infinite loop occurs when a condition always evaluates to true and because of this the loop
control doesn't go outside of that loop.
23
range() function :
This function generates a sequence of numbers based on the parameters passed.
Parameters
start: Starting number of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in the sequence.
Using else with While Loop Output Using else with a For Loop Output
count = 0 0 for i in range(5): 0
1 print(i) 1
while count < 5: 2 else: 2
print(count) 3 print("Loop finished") 3
count += 1 4 4
else: Loop is Loop
print("Loop is ended") ended finished
24
Expression Output Expression Output
int(2.5) 2.5 float() 0.0
int('22') 22 float(5) 5.0
int() 0 list('hello') ['h','e','l','l','o']
int(0xF) 15 list(range(3)) [0, 1, 2]
int('hi') ValueError list(10,20) TypeError
int(None) ValueError list() []
int("2.5") ValueError list({'Ram':10,'Siva':20}) ['Ram', 'Siva']
int(2.5+3.5) 6 list(tuple('Hello')) ['H','e','l','l','o']
int(True) 1 tuple({'Ram':10,'Siva':20}) ('Ram','Siva')
str(5.8) '5.8' tuple() ()
str() '' tuple('Hello') ('H','e','l','l','o')
str(True) 'True' bool([10,20]) True
str(None) 'None' dict(a=1, b=2, c=3) {'a':1, 'b':2, 'c':3}
str(55) '55' dict([('a',1),('b',2),('c',3)]) {'a':1,'b':2,'c':3}
dict() {}
25
Worksheet:
1. Write the output of the given Python code:
a = 20
if a >= 22:
print("if")
elif a >= 21:
print("elif")
else:
print("else")
a. Else b. else c. elif d. if
2. Write the output of the given Python code:
Runs = [10, 5, 0]
for i in Runs:
if i == 0:
print('Maiden Over')
else:
print('Not Maiden')
a. Maiden Over, Maiden Over, Maiden Over b. Not Maiden, Not Maiden, Maiden Over
c. Not Maiden, Not Maiden, Not Maiden d. Error
3. Find out the output of the following python program:
for x in range (1,20,3):
print(x)
a. 1, 20, 3 b.1,4,7,10,13,16,19
c. 13,6,9,12,15,18 d.1,3,6,9,12,15,18
4. What is the output of the following Python code?
for i in range(1, 5):
if i % 2 == 0:
print(i, end= “ ”)
a. 1 b. 2 c. 2 4 d. 1 3
5. What will be the value of y after following code fragment is executed?
x=10.0
y=(x<100.0)and x>=10
print(y)
a. 110 b. True c. False d. Error
6. Give the output of the following
Sum = 0
for k in range(5):
Sum = Sum+k
print(Sum)
Sum = 0
for k in range(10 , 1, -2):
Sum = Sum+k
print(Sum)
26
8. Give the output of the following
for k in range(4):
for j in range(k):
print('*', end = '')
print()
9. Give the output of the following
for k in range(5,0, -1):
for j in range(k):
print('*', end='')
print()
10. How many times the following loop will execute? Justify your answer
A = 0
while True:
print(A)
A =A+1
11. Give the output of the following. Also find how many times the loop will execute.
A = 0
while A<10:
print(A, ' ,')
A =A+1
12. Give the output of the following. Also find how many times the loop will execute.
A = 0
while A<10:
print(A, ',')
A =A+1
print('\n', A)
13. What will be the output of the following code?
count = 0
while count < 5:
print(count)
count += 1
if count == 4:
break
else:
print("Loop is ended")
a) 0 1 2 3 b) 0 1 2 3 Loop is ended c) 0 1 2 d) Error
14. What will be the output of the following code?
if 0.0:
print("Inside if")
else:
print("Inside else")
a) Inside if b) Inside else c) 0.0 d) Error
15. What will be the output of the following Python statement?
int("2.5")
a) 2 b) 3 c) 2.5 d) Error
27
3. Strings
Strings:
▪ String is a sequence which is made up of one or more UNICODE characters.
▪ The character can be a letter, digit, whitespace or any other symbol.
▪ Whitespace Characters: Those characters in a string that represent horizontal or vertical space.
▪ Example: space (' '), tab ('\t'), and newline ('\n')
▪ A string can be created by enclosing one or more characters in single(‘ ‘), double (“ “) or triple
quote( “”” “””).
▪ s1 = 'Hello World!'
▪ s2 = "Hello World!"
▪ s3 = """Hello World!"""
2. updating string:
▪ str1 = "Hello World!"
▪ >>> str1[1] = 'a' TypeError: 'str' object does not support item
String is Immutable
28
String Operations
1. Concatenation
2. Repetition
3. Membership
4. Slicing
5. Comparison
6. Determining
7. String travels
8. String functions.
1. Concatenation
▪ Concatenate means to join.
▪ To join two strings using concatenation operator plus which is denoted by symbol +.
▪ str1 = ‘ Hello ' #First string
▪ str2 = ‘ World! ' #Second string
▪ str1 and str2 remain same after this operation
▪ >>> str1 + str2 'HelloWorld!'
▪ s+'22' 'hello22'
2. Repetition
▪ Python allows us to repeat the given string using repetition operator which is denoted by symbol
*.
▪ str1 = 'Hello' Note: str1 still remains the same after the use of repetition operator.
▪ str1 * 2 'HelloHello'
▪ str1 * 5 'HelloHelloHelloHelloHello'
▪ a='hi'
▪ c='bye'
▪ a+c*3 'hibyebyebye'
▪ a*2+c 'hihibye'
▪ '2.000'*2 '2.0002.000'
3. Membership operators
▪ Python has two membership operators 'in' and 'not in'. The 'in' operator takes two strings and
returns True if the first string appears as a substring in the second string, otherwise it returns
False.
▪ str1 = 'Hello World!'
>>>print( 'W' in str1) True >>> print('Wor' in str1) True
>>> 'My' in str1 False 'Hello' not in str1 False
>>>'Hello' not in str1 False
29
4. Slicing
▪ To access some part of a string or substring, we use a method called slicing.
▪ This can be done by Strings specifying an index range.
▪ The slice operation str1[n:m] returns the part of the string
▪ str1 starting from index n and ending at m
▪ We can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1].
▪ The slice operation can also take a third index that specifies the ‘step size’.
▪ For example, str1[n:m:k],
▪ kth character has to be extracted from the string str1 starting from n and ending at m-1.
▪ By default, the step size is one.
5. Comparison
All relational operators are applying to string. (<, > , ==, !=)
>>> 'Hello'=='Hello' True
>>> 'hello'=='Hello' False
>>> "5"<"9" True (int("9") < int("5"))
>>> 'A'<'a' True
>>> 'Hi'<"hi" True
a='Hello' True
b="Hello"
a is b
6. Determining
>>>chr( 69 ) 'E'
>>> ord(‘ a ') 97
>>> ord(‘ A ') 65
30
7. Traversing a String
We can access each character of a string or traverse a string using for loop and while loop.
for Loop while Loop
str1 = 'Hello World!‘ str1 = 'Hello World!'
for k in str1: index = 0
print(k,end = '') while index < len(str1):
print(str1[index],end = '')
index += 1
for i in range(len(str1)):
print(str1[i])
8. String functions
Method Description Example Output
len() Returns the length of the given string str1 = 'Hello World!'
len(str1) 12
title() Returns the string with first letter of every str1 = 'hello WORLD!'
word in the string in uppercase and rest in str1.title() 'Hello World!'
lowercase
lower() Returns the string with all uppercase letters str1 = 'hello WORLD!'
converted to lowercase str1.lower() 'hello world!'
upper() Returns the string with all lowercase letters str1 = 'hello WORLD!'
converted to uppercase str1.upper() 'HELLO WORLD!'
Count Returns number of times substring str occurs Str1='Hello World! Hello Hello'
(str, start, in the given string. If we do not give start
end) index and end index then searching starts str1.count('Hello',12,25) 2
from index 0 and ends at length of the string, str1.count('Hello') 3
Returns 0 if not found.
str1.count('H') 3
str1.count('hi') 0
index(str, Returns the first occurrence of index of str1='Hello World! Hello Hello'
start, end) substring.
Same as find() but raises an exception if the str1.index('Hello') 0
substring is not present in the given string str1.index('Hee') ValueError:
str1.index('W') 6
str1.index('Hello',10) 13
str1.index('Hello',10,20) 13
find(str,start Returns the first occurrence of index of str1 = 'Hello World! Hello Hello‘
, end) substring str occurring in the given string. If
we do not give start and end then searching str1.find('Hello',10,20) 13
starts from index 0 and ends at length of the str1.find('Hello',15,25) 19
string. If the substring is not present in the
given string, then the function returns -1. str1.find('Hello') 0
str1.find('Hee') -1
31
endswith() Returns True if the given string ends with the str1 = 'Hello World!'
supplied substring otherwise returns False
str1.endswith('World!') True
str1.endswith('!') True
str1.endswith('lde') False
str1.endswith(' ') False
startswith() Returns True if the given string starts with the str1 = 'Hello World!'
supplied substring otherwise returns False.
str1.startswith('He') True
str1.startswith('Hee') False
str1.startswith('3') False
str1.startswith(' ') False
isalnum() Returns True if characters of the given string >>> str1 = 'HelloWorld'
are either alphabets or numeric. If >>> str1.isalnum() True
whitespace or special symbols are part of the
given string or the string is empty it returns >>> str1 = 'HelloWorld2'
False >>> str1.isalnum() True
>>> str1 = 'HelloWorld!!‘
>>> str1.isalnum() False
islower() Returns True if the string is non-empty and >>> str1 = 'hello world!'
has all lowercase alphabets, or has at least >>> str1.islower() True
one character as lowercase alphabet and rest
are non-alphabet characters >>> str1 = 'hello 1234'
>>> str1.islower() True
>>> str1 = 'hello ??'
>>> str1.islower() True
>>> str1 = '1234'
>>> str1.islower() False
>>> str1 = 'Hello World!'
>>> str1.islower() False
isupper() Returns True if the string is non-empty and >>> str1 = 'HELLO WORLD!'
has all uppercase alphabets, or has at least >>> str1.isupper() True
one character as uppercase character and
rest are non-alphabet characters >>> str1 = 'HELLO 1234'
>>> str1.isupper() True
>>> str1 = 'HELLO ??'
>>> str1.isupper() True
>>> str1 = '1234'
>>> str1.isupper() False
>>> str1 = 'Hello World!'
>>> str1.isupper() False
isspace() Returns True if the string is non-empty and all >>> str1 = ' \n \t \r'
characters are white spaces (blank, tab, >>> str1.isspace() True
newline, carriage return)
>>> str1 = 'Hello \n'
32
>>> str1.isspace() False
istitle() Returns True if the string is non-empty and >>> str1 = 'Hello World!'
title case, i.e., the first letter of every word in >>> str1.istitle() True
the string in uppercase and rest in lowercase
>>> str1 = 'hello World!'
>>> str1.istitle() False
lstrip() Returns the string after removing the spaces >>> str1 = ' Hello World! '
only on the left of the string >>> str1.lstrip() 'Hello World! '
rstrip() Returns the string after removing the spaces >>> str1 = ' Hello World!'
only on the right of the string >>> str1.rstrip() ' Hello World!'
strip() Returns the string after removing the spaces >>> str1 = ' Hello World!' 'Hello World!'
both on the left and the right of the string >>> str1.strip()
replace(olds Replaces all occurrences of old string with the >>> str1 = 'Hello World!'
tr, newstr) new string >>> str1.replace('o','*') 'Hell* W*rld!'
join() Returns a string in which the characters in the >>> str1 = ('HelloWorld!') 'H-e-l-l-o-W-o-r-
string have been joined by a separator >>> str2 = '-' #separator l-d-!'
>>> str2.join(str1)
split() Returns a list of words delimited by the str1 = 'India is a Great Country'
specified substring. If no delimiter is given
then words are separated by space. >>> str1.split('a') ['Indi', ' is ', ' Gre', 't Country']
>>> str1.split() ['India','is','a','Great',
'Country']
partition() Partitions the given string at the first >>> st1 = 'India is a Great Country'
occurrence of the substring (separator) and
returns the string partitioned into three parts. st1.partition('is') ('India ', 'is', ' a Great
1. Substring before the separator Country')
2. Separator st1.partition('are ('India is a Great Country',' ','
3. Substring after the separator If the ') ')
separator is not found in the string, it returns
the whole string itself and two empty strings str1.partition() TypeError: takes one
argument
str1 = 'India is a Great country, and rich country
str1.partition('country')
('India is a Great ', 'country', ', and rich country')
capitalize() converts the first character of a string to str1 = "python Programming for 11th"
capital (uppercase) letter and rest in str1.capitalize()
lowercase.
'Python programming for 11th'
33
1. split():
• str.split([separator[, maxsplit]])
• separator: The delimiter on which to split the string. It can be any string, and the default is
whitespace (i.e., it splits on spaces, tabs, and newlines).
• maxsplit: The maximum number of splits to do. If not provided or set to -1, it splits all occurrences.
2. len()
• is a built-in function that returns the length of an object. The len() function can be used to get the
length of various data types, such as strings, lists, tuples, dictionaries, and more.
• The len() function in Python counts all characters in a string, including newlines (\n), spaces, and
any other special characters.
Syntax:
len(object)
text = "Hello, World!" Output: 13
length = len(text)
print(length)
my_string = "Hello\n World" Output: 12
length = len(my_string)
print(length)
3.title():
text = "it's a nice day" "It'S A Nice Day"
print(text.title())
text = "hello world 123" Hello World 123
print(text.title())
34
4. count(str, start, end):
The count()
▪ method in Python is used to count the occurrences of a substring or element in a string, list, tuple,
or other iterable objects.
▪ It returns the number of times the specified substring or element appears.
• start (optional): The starting index (default is 0).
• end (optional): The ending index (default is the length of the string).
sentence = "banana" 3
print(sentence.count("a"))
text = "hello world" 12
print( text.count(""))
5.strip()
▪ Method is used to remove any leading and trailing whitespace characters (such as spaces, tabs, or
newline characters) from a string.
▪ It returns a new string with these characters removed.
▪ If no arguments are passed, it will remove spaces or other whitespace by default. You can also pass
a string of characters to the method, and it will remove those specific characters from both ends of
the string.
▪ The strip() method does not modify the original string; it returns a new string. Strings in Python
are immutable, meaning their content cannot be changed directly.
Syntax:
string.strip([chars])
5.lstrip()
▪ Method is used to remove leading whitespace characters (or other specified characters) from the
left side of a string.
▪ It only removes characters from the beginning of the string, not from the end.
Syntax:
string.lstrip([chars])
text = " Hello, World!" "Hello, World!"
clean_text = text.lstrip()
print(clean_text)
text = "###Hello, World!" "Hello, World!"
clean_text = text.lstrip("#")
print(clean_text)
text = "No Leading Spaces" "No Leading Spaces"
35
clean_text = text.lstrip()
print(clean_text)
6. rstrip()
▪ Method is used to remove trailing whitespace characters (or other specified characters) from the
right side of a string.
▪ It only removes characters from the end of the string, not from the beginning.
Syntax:
string.rstrip([chars])
text = "Hello, World! " "Hello, World!"
clean_text = text.rstrip()
print(clean_text)
text = "Hello, World!###" "Hello, World!"
clean_text = text.rstrip("#")
print(clean_text)
text = "No Trailing Spaces " "No Trailing Spaces "
clean_text = text.rstrip()
print(clean_text)
text = "xyHello, World!xyxy" "xyHello, World!"
clean_text = text.rstrip("xy")
print(clean_text)
7.replace()
▪ Method is used to replace occurrences of a specified substring with another substring in a string.
▪ This method returns a new string with the replacements applied, without modifying the original
string (since strings in Python are immutable).
Syntax:
string.replace(old, new, count)
text = "Hello, World!" "Hello, Python!"
new_text = text.replace("World", "Python")
print(new_text)
text = "apple orange apple banana apple" "grape orange grape banana apple"
new_text = text.replace("apple", "grape", 2)
print(new_text)
text = "Hello, World!" "Hello, !"
new_text = text.replace("World", "")
print(new_text)
text = "Hello, world!" 'Hello, world!'
new_text = text.replace("World", "Python")
print(new_text)
36
8. join()
▪ Method is a string method used to join elements of an iterable (such as a list, tuple, or set) into a
single string.
▪ The string that join() is called on is used as the separator between the elements in the iterable.
Syntax:
separator.join(iterable)
▪ separator: The string that will be inserted between the elements of the iterable. It can be any string
(including an empty string).
▪ iterable: An iterable (e.g., list, tuple, set, or even a string) whose elements are to be joined.
9. partition()
▪ partition() method is used to split a string into three parts based on a separator (a substring). It
divides the string into three components:
▪ The method returns a tuple with three parts: (before, separator, after).
▪ If the separator is not found in the string, the first element of the tuple will be the original string,
and the second and third elements will be empty strings ("").
▪ The method only splits at the first occurrence of the separator.
37
MCQs:
1. What will be the output of the following Python code?
a = 'hi'
c = 'bye'
print(a + c * 3)
a) Hibyebyebye
b) Hibyebye
c) hibye3
d) hibye bye bye
7. Following set of commands are executed in Python shell. What will be the output?
>>> str = "hello"
>>> str[:2]
38
a) he
b) lo
c) olleh
d) hello
8. What is the output of the following?
print("xyyzxyzxzxyy".count('yy', 1))
a) 2 b) 0 c) 1 d) none of the mentioned
40
4. LIST
The data type list is an ordered sequence which is mutable and made up of one or more elements.
▪ A list can have elements of different data types.
▪ List items are ordered, changeable, and allow duplicate values.
list=[ ] list1 = list2 = ['a','e','i','o','u'] list3 =
[2,4,6,8,10,12] [100,23.5,'Hello']
L =["apple", "banana", "cherry"] L4=[['Physics',101],['Chemistry',202],['Maths',303]]
Accessing Elements in a List
List1 = [ 2 , 4 , 6 , 8 , 10, 12 ]
Expression Output Expression Output
list1[3] 8 list1[1+4]
list1[15] 12 list1[-n]
list1[-1] b=[20,[1,2,3],[0,5,12],100,100]
b[2] [0, 5, 12]
n = len(list1) b[2][1+1] 12
list1[n-1] b[1][0] 1
Lists are Mutable: It means that the contents of the list can be changed after it has been created.
L = ['Red','Green','Blue','Orange']
Expression Output Expression Output
L[3] = 'Black' ['Red', 'Green', 'Blue', 'Black'] L[3]=[1,2,3] ['Red', 'Green', 'Blue', [1, 2, 3]]
L[-1]=10.0 ['Red', 'Green', 'Blue', 10.0] sh=L[2:4] ['Blue', [1, 2, 3]]
List Operations
1. Concatenation
2. Repetition
3. Membership
4. Relational
5. Identity
6. Slicing
7. List Comprehension: (not in syllabus)
8. Traversing a List:
Description Expression Output Expression Output
Concatenation print(a+b) [1, 2, 3, 4, 5, 6] b=[20,[1,2,3],100,100]
a=[1, 2, 3] print(a+b+c) [1, 2, 3, 4, 5, a=[10, 5, 9] [20, [1, 2, 3], 100, 100, 10,
b=[4, 5, 6] 6,7,8,9] print(b+a) 5, 9]
c = [7, 8, 9]
a+=[10,5] [1, 2, 3, 10, 5]
Repetition ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', a=[10,5,9] [10, 5, 9, 10, 5, 9, 10, 5, 9]
'Hi!'] a*3
Membership 3 in [1, 2, 3] True 3*a [10, 5, 9, 10, 5, 9, 10, 5, 9]
Relational(==): This checks if two lists are equal, i.e., they have the same elements in the same order.
a=[1,2,3] a == b True c == a False
b=[1,2,3] print(a<c) True print (a > c) False
c=[3,2,1]
Identity operator (is )This checks if two lists refer to the same object in memory (i.e., are the same list, not just
equal).
L1 = [1, 2, 3] , L2 = [1, 2, 3] , L3 = L1
41
print(L1 is L2) False print(L1 is L3) True
a = [10, 50, 52, 45] a = [10, 50, 52, 45]
b=a c = [10, 50, 52, 45]
b[1] = 5000
print(a) [10, 5000, 52, 45] print(a is c) False
print(b) [10, 5000, 52, 45] print(a == c) True
6. Slicing
List1=['Red','Green','Blue','Cyan','Magenta','Yellow','Black']
list1[2:6] ['Blue', 'Cyan', 'Magenta', 'Yellow']
list1[2:20] ['Blue', 'Cyan', 'Magenta', 'Yellow','Black']
list1[7:2] []
list1[:5] ['Red','Green','Blue','Cyan','Magenta']
list1[0:6:2] ['Red','Blue','Magenta']
list1[-6:-2] ['Green','Blue','Cyan','Magenta']
list1[-6:-2] ['Green','Blue','Cyan','Magenta']
list1[::2] ['Red','Blue','Magenta','Black']
list1[::-1] ['Black','Yellow','Magenta','Cyan','Blue','Green','Red']
list1= [1,2,3,4,5,6,7,8,9,10]
list1[1:] [2, 3, 4, 5, 6, 7, 8, 9, 10]
list1[2:5] [3, 4, 5]
42
8. Traversing a List:
for while
L = ['Red','Green','Blue','Yellow', 'Black'] L = ['Red','Green','Blue','Yellow', 'Black']
for i in L: i=0
print(i) while i < len(L):
print(L1[i])
i += 1
for i in range (len(L)):
print(L[i])
10.Deleting elements
Function Expression Output
del() e=["apple", "banana", "mango", "cherry",
del list[index] "orange"] ['banana', 'mango', 'cherry']
del e[0] ['apple', 'cherry', 'orange']
del list[start:end] del e[1:3]
del del e # to delete variable NameError: name 'e' is not
variable_name print(e) defined
remove() e = ["apple", "banana", "mango", "cherry"] ['apple', 'mango', 'cherry']
e.remove("banana")
print(e)
e.remove() TypeError
pop() e.pop() 'cherry‘
e.pop(2) #2 is a index here 'mango‘
clear() e.clear() []
43
Nested Lists
When a list appears as an element of another list, it is called a nested list.
▪ To access the element, have to specify two indices list1 [ i ] [ j ].
▪ The first index i the desired nested list and second index j will the desired element.
list1 =[ 1 , 2,‘ a',‘ c', [ 6, 7, 8], 4, 9]
list1[4] [6, 7, 8]
list1[4][1] [7]
44
count() >> list1 = [10,20,30,10,40,10] 3
Returns the number of times a given >>> list1.count(10)
element appears in the list >> list1.count(90) 0
index() >> list1 = [10,20,30,20,40,10]
Returns index of the first occurrence of >> list1.index(20) 1
the element in the list. If the element is >> list1.index(90) ValueError: 90 is not in list
not present, ValueError is generated
remove() >>> list1 = [10,20,30,40,50,30]
Removes the given element from the list. >>> list1.remove(30)
If the element is present multiple times, >>> list1 [10, 20, 40, 50, 30]
only the first occurrence is removed. If the
>>> list1.remove(90) ValueError: list.remove(x): x
element is not present, then ValueError is
not in list
generated
pop() >>> list1 = [10,20,30,40,50,60]
Returns the element whose index is >>> list1.pop(3) 40
passed as parameter to this function and
>>> list1 [10, 20, 30, 50, 60]
also removes it from the list. If no
parameter is given, then it returns and >>> list1 = [10,20,30,40,50,60]
removes the last element of the list >>> list1.pop() 60
>>> list1 [10, 20, 30, 40, 50]
reverse() >>> list1 = [34,66,12,89,28,99]
Reverses the order of elements in the >>> list1.reverse()
given list >>> list1 [ 99, 28, 89, 12, 66, 34]
>>> list1 = [ 'Tiger' ,'Zebra' ,
'Lion' , 'Cat' ,'Elephant' ,'Dog']
>>> list1.reverse() ['Dog', 'Elephant', 'Cat',
>>> list1 'Lion', 'Zebra', 'Tiger']
sort() >>>list1 =
['Tiger','Zebra','Lion', 'Cat', ['Cat', 'Dog', 'Elephant',
list.sort(reverse=False, key=None) 'Elephant' ,'Dog'] 'Lion', 'Tiger', 'Zebra']
Sorts the elements of the given list in >>> list1.sort()
place. >>> list1 =
For descending order reverse = True [34,66,12,89,28,99] [12, 28, 34, 66, 89, 99]
The default is False (ascending order). >>> list1.sort() [99,89,66,34,28,12]
key: A function that serves as a key for >>> list1.sort(reverse = True)
sorting. This allows for custom By default, NTList = [[21, 2, 5], [12, 5, 1],
it is None. [3, 7, 9]]
>>>NTList.sort() [[3, 7, 9], [12, 5, 1], [21, 2, 5]]
print(NTList)
my_list = ['apple', 'fig', 'banana', 'cherry'] ['fig', 'apple', 'banana',
my_list.sort(key=len) 'cherry']
sorted() >>> list1 = [23,45,11,67,85,56]
sorted(iterable, key=None, >>> list2 = sorted(list1)
reverse=False) >>> list1 [23, 45, 11, 67, 85, 56]
It takes a list as parameter and creates a >>> list2 [11, 23, 45, 56, 67, 85]
new list consisting of the same elements my = [4, 2, 9, 1, 5]
arranged in sorted order st = sorted(my, reverse=True)
print(st) [9, 5, 4, 2, 1]
45
min() list1=[34,12,63,39,92]
min(iterable) >>> min(list1) 12
Returns minimum or smallest element of
the list words = ["apple", "banana",
"cherry", "blueberry"]
smallest_word = min(words)
print(smallest_word) apple
max() >>> max(list1) 92
max(iterable) words = ["apple", "banana",
Returns maximum or largest element of "cherry", "blueberry"]
the list largest_word = max(words) "cherry"
print(largest_word)
words = ["apple", "banana",
"cherry", "blueberry"]
longest_word = max(words,
key=len) blueberry
print(longest_word)
sum() >>> sum(list1) 284
sum(iterable, start=0) my_list = [1, 2, 3, 4, 5]
Returns sum of the elements of the list result = sum(my_list, 10) 25
numbers = [-1, -2, -3, -4, 5]
total = sum(numbers)
print(total) -5
empty_list = [] 0
total = sum(empty_list)
print(total)
46
MCQs:
48
5. Dictionary
▪ A dictionary is a collection which is unordered, changeable set of keys and a set of values.
• The key-value pair is called an item.
• A key is separated from its value by a colon (:) and consecutive items are separated
by commas.
• Items in dictionaries are unordered.
• The keys in the dictionary must be unique and should be of any immutable data type, i.e., number,
string or tuple.
• The values can be repeated and can be of any data type.
Creating a Dictionary:
▪ dict1 = { } #dict1 is an empty dictionary created
▪ dict2 = dict() #dict() is function
▪ my_dict = dict(name="Alice", age=25, city="New York")
▪ dict3 = {'Mohan':95,'Ram':89,'Sudha':92,'Sangeeta':85}
▪ X={1:'A',2:'B',3:'c'}
▪ X=dict([('a',3)('b',4)])
▪ X=dict('A'=1,'B'=2)
▪ dict1={"brand":"mrcet","model":"college","year":2004}
▪ stu= {"name":"John","age":25,"courses":["Math","Science","History"]}
▪ my_dict={(1, 2): "tuple key",42: "int key", "name": "John"}
Dt={"person1":{"name": "Alice","age":25},"person2":{"name":"Bob","age":30}}
49
Adding a new item (Mutable):
Expression Output
dt1 ={'Mohan':95,'Ram':89,'Sudha':92,'Sangeeta':85} {'Mohan': 95, 'Ram': 89, 'Sudha': 92,'Sangeeta': 85,
dt1['Meena'] = 78 'Meena': 78}
print (dt1)
{'Mohan': 95, 'Ram': 89, 'Sudha': 92,'Sangeeta': 85, {'Mohan': 95, 'Ram': 89, 'Sudha': 100,'Sangeeta':
'Meena': 78} 85, 'Meena': 78}
dt1['Sudha'] = 100
print( dt1)
dt1['Ram'] +=11 {'Mohan': 95, 'Ram': 100, 'Sudha': 92, 'Sangeeta':
85}
my_dict = {'a': [1, 2], 'b': [3, 4]} {'a': [1, 2, 3, 4], 'b': [3, 4]}
my_dict['a'] += [3, 4]
print(my_dict)
my_dt= {"age":30,"city":"New York"} {'age': 30, 'city': 'New York'}
{'age': 30, 'city': 'New York', 'job': 'Engineer',
my_dt.update({"job":"Engineer", "country":
'country': 'USA'}
"USA"})
Traversing a Dictionary:
Expression output
dict1={'Mohan':95,'Ram':89,'Sudha':92,'Sangeeta':85} Mohan: 95
for k in dict1: Ram: 89
Sudha: 92
print(k,':',dict1[k])
Sangeeta: 85
▪ Dictionarycomprehensionscanbeusedtocreatedictionariesfromarbitrarykeyandvalueexpre
ssions.
▪ Syntax:
<dictionary>={expressionfor<variable>insequence}
Expression output
>>>z= {x:x**2for x in(2,4,6)} {2:4,4:16,6: 36}
>>>print(z)
>>>dict11= {x:x*x for x in range(6)} {0:0,1:1,2:4,3:9,4:16,5:25}
>>>print(dict11)
51
Dictionary Functions/Method:
Method Example Output:
len() dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85}
Syntax: print(len(dict1)) 4
len(dictionary)Returns the length or empty_dict = {}
number of keys: value pairs of the print(len(empty_dict)) 0
dictionary passed as the argument
dict() pa1 = [('M',95),('R',89),('S',92),('Sa',85)]
variable = dict() dict1 = dict(pa1) {'M': 95, 'R': 89,
Creates a dictionary from a sequence of print(dict1) 'S': 92, 'Sa': 85}
key-value pairs empty_dict = dict()
print(empty_dict) #{}
52
print(type(items_view)) <class 'dict_items'>
53
• iterable: An iterable (such as a list, Output:
tuple, or set) that contains the keys {'a': 'vowel', 'u': 'vowel', 'e': 'vowel', 'i': 'vowel', 'o': 'vowel'}
you want in the new dictionary. keys = [1, 2, 4 ]
• value (optional): The default value numbers = dict.fromkeys(keys)
to be assigned to all the keys. If not
provided, the default value is None. print(numbers) {1: None, 2: None, 4:
None}
a={'a', 'b', 'c'} new_dict = dict.fromkeys('abc', 1)
b=1,2,3 print(new_dict) {'a': 1, 'b': 1, 'c': 1}
d=dict.fromkeys(a,b)
print(d)
output: {'c': (1, 2, 3), 'b': (1, 2, 3), 'a': (1, 2,
3)}
max() a={1:3,7:45}
Use the max() function to get the dictionary key >>>max(a) 7
with the max values dict1 = {'a': 1, 'b': 5, 'c': 3}
max_key = max(dict1)
print(max_key) 'c'
dict1 = {'a': 1, 'b': 5, 'c': 3
max_value = max(dict1.values())
print(max_value) 5
min() a={1:3,7:45}
Use the min() function to get the dictionary >>>min(a) 1
key with the min values
dict1 = {'a': 1, 'b': 5, 'c': 3}
min_key = min(dict1) 'a'
sorted() ppl = {3: "Jim", 2: "Jack", 4: "Jane", 1: "Jill"}
sorted() function is to take the keys of the >>> sorted(ppl) [1, 2, 3, 4]
dictionary, sort them, and return a list of a={'a':10,'b':15,'v':115}
the keys only. sa=sorted(a)
print(sa) ['a', 'b', 'v']
sa=sorted(a,reverse=True)
print(sa) ['v', 'b', 'a']
55
MCQs:
1. What is the output of the following Python code?
d = {0: 'a', 1: 'b', 2: 'c'}
for i in d:
print(i)
a) 0 1 2 b) a b c c) 0 a 1 b 2 c d) none of the mentioned
2. What will be the output of the following Python code?
d = {"john": 40, "peter": 45}
print(d["john"])
a) 40 b) 45 c) "john" d) "peter"
3. Given the following dictionary in Python:
dt1 = {'Ram': 20, 'Shyam': 15}
dt1['Ram'] += 11
a) {'Ram': 11, 'Shyam': 15}
b) {'Ram': 31, 'Shyam': 15}
c) {'Ram': '2011', 'Shyam': 15}
d) Error: Unsupported operand type(s) for +=
57
26. What will be the output of the following code?
d = {'x': 100, 'y': 200}
print(d.pop('x'))
a) 100 b) 'x' c) {'y': 200} d) Error
58
6. Tuples
▪ A tuple is an ordered sequence of elements of different data types, such as integer, float, string, list or even a
tuple.
▪ Elements of a tuple are enclosed in parenthesis (round brackets) and are separated by commas.
▪ Like list and string, elements of a tuple can be accessed using index values, starting from 0.
▪ Key Properties of Tuples:
1. Ordered: The items in a tuple have a defined order, and that order will not change.
2. Immutable: Once a tuple is created, you cannot add, remove, or change its elements.
3. Indexed: Tuples are indexed, so you can access elements using their index.
4. Can contain duplicates: Tuples can store multiple occurrences of the same value.
1. Creating tuple: (tuple assignment)
X=( ) # an empty Output
Tuple_X=(1,2,3)
print(Tuple_X) (1, 2, 3)
tuple2 =('Economics',87,'Accountancy',89.6) ('Economics', 87, 'Accountancy', 89.6)
tuple3= (10,20,30,[40,50])
print(Tuple3) (10, 20, 30, [40, 50])
tuple4 = (1,2,3,4,5,(10,20))
print(tuple4) (1, 2, 3, 4, 5, (10, 20))
tuple5 = (20)
print(type(Tuple5)) <class 'int'>
tuple5 = (20,)
print(type(Tuple4)) <class 'tuple'>
seq = 1,2,3 #comma separated elements
print(type(seq)) #treated as tuple <class 'tuple'>
print(seq) (1, 2, 3)
(num1,num2) = (10,20) 10
print(num1) 20
print(num2)
record = ("Pooja",40,"CS")
(name,rollNo,subject) = record
print( name) 'Pooja'
print(rollNo) 40
print(subject) 'CS'
(a,b,c,d) = (5,6,8) ValueError: not enough values to unpack
t=1,5,6
a,b,c=t
print(a) 1
print(c) 6
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list) (1, 2, 3, 4)
print(my_tuple)
my_string = "hello"
my_tuple = tuple(my_string)
print(my_tuple) ('h', 'e', 'l', 'l', 'o')
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_tuple = tuple(my_dict)
print(my_tuple) ('a', 'b', 'c')
59
2. Accessing Elements in a Tuple:
Tuple is Immutable
tuple1 = (1,2,3,4,5) TypeError: tuple2 = (1,2,3,[8,9])
tuple1[4] = 10 tuple2[3][1] = 10 (1, 2, 3, [8, 10])
my_tuple = (1, 2, 3) my_string = "Hello"
print(my_tuple) (1, 2, 3) my_string += "
my_tuple += (4, 5) World" "Hello World"
print(my_tuple) (1, 2, 3, 4, 5) print(my_string)
rebuilding the tuple rather than modifying it in-place
Tuple Operations:
1. Concatenation
2. Repetition
3. Membership
4. Slicing
5. Identity operator
6. Comparison operator
1. Concatenation
60
2. Repetition
3. Membership
4. Slicing
tuple1 = ( 10, 20, 30, 40, 50, 60, 70, 80)
Expression Output
tuple1[2:7] (30, 40, 50, 60, 70)
tuple1[0:len(tuple1)] (10, 20, 30, 40, 50, 60, 70,80)
tuple1[:5] (10, 20, 30, 40, 50)
tuple1[2:] (30, 40, 50, 60, 70, 80)
tuple1[0:len(tuple1):2] (10, 30, 50, 70)
tuple1[-6:-4]
5. Identity
t_1=(10,5,9,15) t_1=(10,5,9,15)
t_2=(10,5,9,15) t_2=(10,5,9,15)
print(t_1 is t_2) False ab=t_2
print(ab is t_1) False
print(ab is t_2) True
6. Comparison operator
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 3)
tuple3 = (3, 2, 1)
tuple4 = (1, 2)
Nested Tuple: A nested tuple is a tuple that contains other tuples as its elements.
nested_tuple = ((1, 2), (3, 4), (5, 6))
61
Methods and Built-in Functions:
len() Returns the length or the number of >>> tuple1 = (10,20,30,40,50)
elements of the tuple passed as the >>> len(tuple1) # Output: 5
argument nested_tuple = (1, (2, 3), (4, 5), 6)
length = len(nested_tuple)
print(length) # Output: 4
tuple() Creates an empty tuple if no argument >>> tuple1 = tuple()
is passed Creates a tuple if a sequence >>> print(tuple1) # Output: ( )
tuple(iterable) is passed as argument >>> tuple1 = tuple('aeiou') #string
>>> print(tuple1) ('a', 'e', 'i', 'o', 'u')
>>> tuple2 = tuple([1,2,3]) #list
>>> print(tuple2) #Output: (1, 2, 3)
>>> tuple3 = tuple(range(5))
>>> print(tuple3) #Output: (0, 1, 2, 3, 4)
>>> single_ele = (5,)
>>> print(single_ele) # Output: (5,)
count() Returns the number of times the given >>> tuple1 = (10,20,30,10,40,10,50)
element appears in the tuple >>> tuple1.count(10) # Output: 3
>>> tuple1.count(90) # Output: 0
index() Returns the index of the first >>> tuple1 = (10,20,30,40,50)
occurrence of the element in the given >>> tuple1.index(30) # Output: 2
tuple >>> tuple1.index(90)
ValueError: tuple.index(x): x not in tuple
sorted() Takes elements in the tuple and >>> tuple1 = ("Rama","Heena","Raj", "Mohsin","Aditya")
returns a new sorted list. It should be >>> sorted(tuple1)
noted that, sorted() does not make any ['Aditya', 'Heena', 'Mohsin', 'Raj', 'Rama']
change to the original tuple
min() Returns minimum or smallest element >>> tuple1 = (19,12,56,18,9,87,34)
max() of the tuple. >>> min(tuple1) #Output: 9
sum() Returns maximum or largest element >>> max(tuple1) #Output: 87
of the tuple. >>> sum(tuple1) #Output: 235
Returns sum of the elements of the
tuple.
62
MCQs:
63
7. Functions
A function is a block of code which only runs when it is called. If data can pass into a function, known as parameters.
A function can return data as a result.
Types of functions:
1.Built in functions
2.Modules (Functions defined in module)
3. User defined
1.Built in functions:
▪ These are the predefined functions are always available for use.
▪ E.g int(),len(),input(),print().
64
divmod (x,y ) Returns both quotient and >>> divmod (14,5) (2,4)
remainder by division through a >>>divmod (2.7, 1.5) (1.0, 1.20000)
(a // b, a % b) tuple, when x is divided by y; >>> divmod(0,1) (0, 0)
where x & y are
variable/expression.
range(start, stop[, It is most often used in for loops. >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
step]) The arguments must be plain >>>range(0, 30, 5) [0, 5, 10,15,20, 25]
integers. If the step argument is >>> range(0, -10, -1) [0,-1,-2, -3, -4, -5, -6, -7, -8, -9]
Step must not be omitted, it defaults to 1. If the >>> range(0) []
zero (or else Value start argument is omitted, it >>> range(1, 0) []
Error is raised). defaults to 0. The full form returns range(10, 15, 0) Error
a list of plain integers [start,start +
step, start + 2 * step, ...].
round( x [, n] ) It returns float x rounded to n >>>round(3.7) 4
digits from the decimal point, >>>round(3.1) 3
round(number, where x and n are numeric >>>round(2.5)) 2
ndigits) expressions. If n is not provided >>>round(3.5)) 4
then x is rounded to 0 decimal >>>round(-2.5)) -2
Nearest even digits. >>>round(-3.5)) -4
number. >>>round(7.9119,2) 7.91
>>>round(7.9179,2) 7.92
>>>round(8.9159,2) 8.92
>>>round(7.9139,2) 7.91
>>>round(7.925,2) 7.92
pow(x,y[,z]) x, y, z may be integer or floating >>> pow(5,2) 25
pow (x ** y) % z point number >>> pow(5,2,4) 1
xy (x raised to the power y) if z is pow(0, 1) 0
provided, then: (xy ) % z pow(0, 1, 1) 0
pow(0, 0) 1
pow(0, 0, 1) 0
pow(1, 0) 1
pow(1, 0, 1) 0
pow(0, 0, 0) ValueError.
2.Modules:
65
1. math
2. random
3. statistics
▪ Module is a file containing Python definitions, functions, variables, classes and statements with .py
extension.
▪ Package is simply a directory of Python module(s).
▪ A library in Python is a collection of various packages. Conceptually, there is no difference between package
and Python library. In Python, a library is used to loosely describe a collection of core or main modules.
▪ import It is simplest and most common way to use modules in our code.
▪ from Statement It is used to get a specific function in the code instead of the complete
module file.
2. from Statement
from math import sqrt
1. from math import sqrt print(sqrt(25))
2. from math import sqrt,sin
3. from math import * from math import sqrt,sin
print(sin(90))
Math module
Function Description Example Output
ceil( x ) It returns the smallest math.ceil(-45.17) -45
integer not less than x, where math.ceil(100.12) 101
x is a numeric expression. math.ceil(100.72) 101
math.ceil(10) 10
math.ceil(1.7) 2
math.ceil(-7) -7
floor( x ) It returns the largest integer math.floor(-45.17) -46.0
notgreaterthan x, where x is a math.floor(100.12) 100.0
numericexpression. math.floor(100.72) 100.0
math.floor(10) 10
math.floor(-10) -10
66
fabs( x ) It returns the absolute value math.fabs(-45.17) 45.17
of x, wherexis a numeric math.fabs(100.12) 100.12
value. math.fabs(100.72) 100.72
math.fabs(10) 10.0
math.fabs(-10) 10.0
exp( x ) It returns exponential of x: e math.exp(-45.17) 2.41500621326e-20
x, where xisa numeric math.exp(100.12) 3.03084361407e+43
expression. math.exp(100.72) 5.52255713025e+43
pi() Pi() returns the value of PI: print (math.pi) 3.141592653589793
3.141592653589793.
e() e() constant returns the math.e() 2.718281828459045.
Eular's number:
log( x ) It returns natural logarithm of math.log(100.12) 4.60636946656
x, for x >0,where x is a math.log(100.72) 4.61234438974
numeric expression.
log10( x ) It returns base-10 logarithm math.log10(100.12) 2.00052084094
of x for x >0,where x is a math.log10(100.72) 2.0031157171
numeric expression.
pow( x, y ) It returns the value of xy, math.pow(100, 2) 10000.0
where xand yare numeric math.pow(100, -2) 0.0001
expressions. math.pow(2, 4) 16.0
math.pow(3, 0) 1.0
pow(2,3,2) 0
pow(2,3) 8
pow(0,0) 1
sqrt (x ) It returns the square root math.sqrt(100) 10.0
of x for x >0,where x is a math.sqrt(7) - 2.6457513110645907
numeric expression.
cos (x) It returns the cosine of x in math.cos(3) 0.9899924966
radians, math.cos(-3) 0.9899924966
where xis a numeric math.cos(0) 1.0
expression math.cos(math.pi) 1.0
sin (x) It returns the sine of x, in math.sin(3) - 0.14112000806
radians,where xmust be math.sin(-3) - 0.14112000806
anumeric value. math.sin(0) -0.0
tan (x) It returns the tangent of x in math.tan(3) 0.142546543074
radians, math.tan(-3) 0.142546543074
Where x must be a numeric math.tan(0) -0.0
value.
degrees (x) It converts angle x from math.degrees(3) 171.887338539
radians to degrees, where x math.degrees(-3) 171.887338539
must be a numeric math.degrees(0) - 0.0
value.
radians(x) It converts angle x from math.radians(3) 0.0523598775598
degrees to math.radians(-3) 0.0523598775598
radians, where x must be a math.radians(0) - 0.0
numeric
value.
67
Random module
Function Description Example Output
random ( ) It returns a random float x, >>random.random( ) 0.281954791393
such that 0 ≤ x
>>>random.random( ) 0.309090465205
randint (a, b) It returns a int x between a >>> random.randint (1,10) 5
and b such that a ≤ x ≤ b >>> random.randint (2,20) 2
import random as rd
>>> rd.randint(5) TypeError:
>>> rd.randint(5,10) 6
>>> rd.randint(-5,10) 7
>>> rd.randint(-10,-5) -5
uniform (a, b) It returns a floating point >>>random.uniform (5, 10) 5.52615217015
number x, such that
a <= x < b
randrange([start,] It returns a random item >>>random.randrange(1,10,3) 9
stop[,step]) from the given range
Statistics module
Name of the Description Example
Function
mean(x) It returns arithmetic mean >>>statistics.mean([11,24,32,45,51]) 32.6
median(x) It returns median (middle >>>statistics.median([11,24,32,45,51]) 32
value) of x >>>statistics.median([7,1,2,3,51,100]) 5.0
Mode(x) It returns a number with statistics.mode([10, 20, 20, 30, 40]) 20
maximum number of statistics.mode([10,20,5,10]) 10
occurrences statistics.mode([10,20,5,10,20]) 10
statistics.mode([20,10,20,5,10]) 20
statistics.mode([20,5,10]) 20
68
3. User Defined Function:
1. Definition:
▪ User-defined functions are functions that we create (define) ourselves to perform specific tasks in our
program.
▪ The keyword def is used to define a function.
▪ After the keyword comes an identifier i.e. name of the function, followedby parenthesized list of parameters
and the colon which ends up the line.
▪ It needs to be defined before you can call the function.
▪ A function name to uniquely identify the function. Function naming follows the same rules of writing
identifiers in Python.
▪ Parameters (arguments) through which we pass values to a function. They are optional.
▪ A colon (:) to mark the end of the function header.
▪ Optional documentation string (docstring) to describe what the function does.
▪ One or more valid python statements that make up the function body. Statements must have the same
indentation level (usually 4 spaces).
▪ An optional return statement to return a value from the function.
▪ Syntax to define a user defined function:
def function_name(parameters):
# function body
# return <value> # optional return statement
69
Main program:
▪ Python names the segment with top-level statements (main program) as _ _main_ _
▪ Python stores this name in a built-in variable called _ _name_ _
▪ print(_ _name _ _)
▪ help():
▪ The Python help function is used to display the documentation of modules, functions, classes,
keywords, etc. object:
▪ help('math')
Advantages of Function:
▪ Reusability of code
▪ Clarity in the program
▪ Easy to debug
▪ Programming becomes modular
Write a user defined function to add 2 numbers and display their sum.
def Add_num():
a = int (input("Enter first number: "))
b = int (input("Enter second number: "))
sum = a + b
print("The sum of ",a,"and ",b,"is ",sum)
Add_num()
Write a function find big that take 2 integers as parameters and returns the largest value.
def find_big(a, b):
if a > b:
return a
else:
return b
x, y = 5, 10
big_value = find_big(x, y)
print(big_value)
Function header The Header of a function specifies the name of the function and the name of each
of its parameters. It begins with the keyword def.
Parameters Variables that are listed within the parenthesis of a function header.
Function Body The block of statements to be carried out, ie the action performed by the function.
Indentation The blank space needed for the python statements. (four spaces convention)
def def is the keyword used to define a function in Python.
find_big() find_big is the name of the function.
(a, b) (a, b) are the parameters.
(x, y) x and y are the arguments
find_big(x, y) Calling the function
return return is a keyword used return statement tells the function to stop its
execution and send back a specific value or result to the caller.
Calling a Function Calling a function means executing the code inside the function’s body.
70
Calling a Function
Calling a function means executing the code inside the function’s body. There are four types of function
calls in Python:
▪ Basic Function Call
▪ Calling with Positional Arguments
▪ Calling with Keyword Arguments
greet("Alice")
greet("Bob")
greet("Charlie")
Calling a Function in a def greet(name):
Loop: print(f"Hello, {name}!")
5. x = 3
6. y = 4
7. check (x, y)
8. print('Hello')
9. check (1.5, 2)
71
2. Arguments and Parameters:
▪ The parameters are the variables that we can define in the function declaration. In fact, we utilized these
variables within the function. Also, the programming language in the function description determines the
data type specification.
▪ These variables facilitate the function’s entire execution. In addition, they are known as local variables
because they are only available within the function.
▪ These are the values passed to user defined functions from the calling function. If you arepassing values of
immutable types (i.e., numbers, strings, etc) to the Called function, thenthe called function cannot alter their
values.
▪ If you are passing values of mutable types (i.e., List, Dictionary, etc.) to the called function, then the called
function can make changes to them.
▪ Zero or more parameters can be taken and name of the parameter and argument may be same or different.
▪ The arguments are the variables given to the function for execution. Besides, the local variables of the
function take the values of the arguments and therefore can process these parameters for the final output.
72
Types of parameters or Passing parameters:
1. Positional or required parameters
2. Default parameters
3. Keyword or named parameters
4. Variable length parameter
5. Combining Positional and Keyword Arguments
# Correct order
format_details("Alice", 25, 170) #Name -> name, Age ->age, Height ->
height
def format_details (name, age, height):
print(f"Name: {name}, Age: {age}, Height: {height} cm")
# Incorrect order
format_details(170, 25, "Alice")
def check (a,b):
print(a+b)
x,y=3,4
check() Output: TypeError: missing 2 required arguments
2. Default parameters
▪ The parameters which are assigned with a value in function header while defining the function are
known as default parameters.
▪ If a user explicitly passes the value in function call, then the value which is passed by the userwill be
taken by the default parameter.
▪ This value is optional for the parameter.
▪ If no value is provided, then the default value willbe taken by the parameter.
▪ Default parameters must be placed after non-default parameters in the function definition.
73
Expression Output
def fun(person,country="Norway"):
print("I am "+person+" from "+country) I am Sai from India
name="Sai"
nation="India"
fun(name, nation)
def fun(person,country="New York"):
print("I am "+person+" from "+country) I am Tony Stark from New York
name="Tony Stark"
fun(name)
greet(name="Alice")
74
4. Variable length parameter
▪ Variable length argument is a feature that allows a function to receive any number
of arguments.
▪ The syntax is to use the symbol * to take in a variable number of arguments;
▪ def Add(*X)
▪ **kwargs allows a function to accept an arbitrary number of keyword arguments (name-
value pairs).
Expression Output
def myFun(*argv): Hello
for ar in argv: Welcome
print (ar) to
Hyd
myFun('Hello', 'Welcome', 'to', ‘Hyd')
def change(*a): 15
for i in a: 20
print(i) 25
print(a) (15,20,25)
change(15,20,25)
print(change)
def print_info(**kwargs): name: Alice
for key, value in kwargs.items(): age: 25
print(f"{key}: {value}") job: Engineer
greet("Bob", age=35)
def register_user(name, email, role="User", country="USA"):
print(f"Name: {name},Email:{email},Role: {role},Country: {country}")
register_user("Alice", "[email protected]")
75
Combining Positional, keyword and Default Parameters:
greet("Alice")
greet("Bob", city="Los Angeles")
greet("Charlie", 25)
Returning a Function:
▪ A return statement is used to end the execution of the function call and “returns” the result (value of the
expression following the return keyword) to the caller.
▪ The statements after the return statements are not executed.
▪ If the return statement is without any expression, then the special value None is returned.
▪ Return statement cannot be used outside the function.
76
Single Return Value Multiple Return Values
▪ A single return value function returns one value ▪ At times, you will be required to return more
from the operations in a function. than one value from a function in Python.
▪ An example of a single return value function is ▪ To achieve this, you can use a tuple or a list to
given below: wrap the return values.
def get_greeting(name): def get_name_and_age():
return "Hello, " + name + "!" return "John", 30
Output: Output:
Name: Alice, Age: 30 X: 10, Y: 20
77
Function returning def Add(): The Sum is:7
some values a=int (input(“Enter First Number”))#3
3. No Argument with b= int (input(“Enter Second Number”))#4
return c=a+b
return c
x= Add()
print (“The Sum is:”, x)
4. With Argument with def Add (a,b): 9
return c=a+b The Sum is:9
return c
a= 20
b= 10
x= add(a,b)
print (“The Sum of inputted Numbers is:”, x)
result = inner_function(3)
return result
xy=outer_function(1, 2)
print(xy)
Output: 6
In the example above, the inner_function is defined within the outer_function. The inner function has access to the
variables of the outer function, allowing it to perform operations on them.
78
Calling function and Called function:
Scope of variables
▪ Scope means in which part(s) of the program, a particular piece of code or data is accessible or
known.
▪ In python there are broadly 2 kinds of Scopes:
1. Global Scope
2. Local Scope
1. Global Scope
▪ A name declared in top level segment(_main_) of a program is said to have global scope and can be
used in entire program.
▪ Variable defined outside of the all functions are global variables.
2. Local Scope
▪ A name declared in a function body is said to have local scope i.e. it can be used only within this
function and the other block inside the function.
▪ The formal parameters are also having local scope.
▪ When dealing with Python functions, you should also consider the scope of the variables. The
code in a function is in its own little world, separate from the rest of the program. Any variable
declared in the function is ignored by the rest of the function. This means that two variables with
the same name can exist, one inside the function and the other outside the function. However,
this is not a good practice. All variable names must be unique regardless of their scope.
Local variable:
▪ A variable that is defined within a function and can only be used within that particular function. With respect
to the local variable, the area in a function is called “local area”.
▪ Local variables are defined inside a function.
▪ These variables are not accessible from outside the function.
▪ Local variables only exist during the execution of the function and are destroyed when the function
exits.
79
Global variable:
▪ A variable that is defined in the main part of the programming and, unlike local variables, can be
accessed via local and global areas.
▪ Global variables are declared at the top level of the program.
▪ Variable defined outside of the all functions are global variables.
▪ These variables are accessible from any part of the program, including inside functions.
▪ However, if you want to modify a global variable inside a function, you need to use the global
keyword.
Example Output
def myfunc(): 300 inside function
x = 300 20 out side function
print(x," inside function")
x=20
myfunc()
print(x,"Out side function")
x = 300 300 inside the function
def myfunc(): 300 outside function
print(x," inside function")
myfunc()
print(x,"Out side function")
def myfunc(): Error: name 'x' is not defined
print(x,"inside")
myfunc()
x = 300
print(x,"outside")
x = 300 200 inside
def myfunc():
x = 200 300 outside
print(x,"inside")
myfunc()
print(x,"outside")
80
a = 5 5
def display(): 15
local_a = a + 10 5
print(local_a)
print(a)
display()
print(a)
a=5 Updating of global variable can’t be
def display():
done in inside the function.
a=a+10
print(a)
UnboundLocalError: local variable 'a'
referenced before assignment
print(a)
display()
print(a)
x = 300
def myfunc():
global x
x = 200# x is global variable now 300 out side x value
print(x,'after global') 200 after global
200 x value from inside function
print(x,'out side x value')
myfunc()
print(x,' x value from inside function ')
x = 10 The value of x is 12
def showX():
global x
x = x + 2
print("The value of x is", x)
showX()
a=[1,2,3,4] [1, 2, 3, 4] a before update
def display(): [1, 2, 3000, 4] a inside function
a[2]=3000 [1, 2, 3000, 4] a after update
print(a," a inside function")
s=List_Fun(2,[22,33])
print(s)
def ab(a,b=[]): 100
print(b)
ab(5,100)
81
my_dict = {"name": "Alice","age": 25} Before: {'name': 'Alice', 'age': 25}
After: {'name': 'Alice', 'age': 26, 'city': 'New
def modify_global_dict(): York'}
my_dict["age"] = 26
my_dict["city"] = "New York"
print("Before:", my_dict)
modify_global_dict()
print("After:", my_dict)
def ab(a,b={1:10}): {1: 10}
print(b) {1: 10, 2: 101}
b[2]=101
print(b)
ab(5)
Lifetime of Variables:
▪ Lifetime is the time for which a variable lives in memory. For global variables the lifetime is entire program
run i.e. as long as program is executing. For local variable, lifetime is their function’s run i.e. as long as
function is executing.
82
Key Differences Between Scope and Lifetime
83
MCQs:
1. What is the output of the following code?
def cube(x):
return x * x * x
x = cube(3)
print(x)
a) 9 b)3 c)27 d) 30 Ans. C) 27
2. Which of the following items are present in the function header?
a) function name b) parameter list c) return value d) Both A and B
3. Predict the output of the following code:
def fun1(num):
return num + 5
print(fun1(5))
print(num)
a) Print value 10 b) Print value 5 c) Name Error d) 25
4. Predict the output of the following code:
def func1(list1):
for x in list1:
print(x.lower(), end="#")
func1(["New", "Dehli"])
x = mul(20, 30)
A) 600 B) None C) No Output D) 0
6. Which of the following function headers is correct?
A) def fun(x=1, y)
B) def fun(x=1, y, z=2)
C) def fun(x=1, y=1, z=2)
D) def fun(x=1, y=1, z=2, w)
7. What is the output of the program given below?
x = 50
def func(x):
x = 2
func(x)
print('x is now', x)
A) x is now 50 B) x is now 2 C) x is now 100 D) Error
8. def update(x=10):
x += 15
print("x =", x)
x = 20
update()
print("x =", x)
84
Answer: D)
x=25
x=20
9. Predict the output of the following code fragment
def display(x=2,y=3):
x=x+y
y+=2
print(x,y)
display( )
display(5,1)
display(9)
Ans.
5 5
6 3
12 5
10. Find the output print(pow(5,4,9))
a) 7 b)0 c)4 d) error
Hint: pow(x, y, z) is equal to xy % z
11. Give the output of the following program
def check(a):
for i in range(len(a)):
a[i]=a[i]+5
return a
b=[1,2,3,4]
c=check(b)
print(c)
a) [6, 8, 8, 9] b) [6,7,8,9]
c) [7, 7, 8, 9] d) [6,7,9,9]
12. Give the output
def abc(x,y=60):
return x+y
a=20
b=30
a=abc(a,b)
print(a,b)
b=abc(a)
print(a,b)
a=abc(b)
print(a,b)
Ans.C)
c) 50 30
50 110
170 110
85
13. Predict the output of the following code snippet:
def Execute(M):
if M%3==0:
return M*3
else:
return M+10;
def Output(B=2):
for T in range (0,B):
print(Execute(T),"*",end="")
print()
Output(4)
Output()
Output(3)
Ans.
0 *11 *12 *9 *
0 *11 *
0 *11 *12 *
14. Find the output of the following program:
def ChangeIt(Text,C):
T=""
for K in range(len(Text)):
if Text[K]>='F' and Text[K]<='L':
T=T+Text[K].lower();
elif Text[K]=='E' or Text[K]=='e':
T=T+C;
elif K%2==0:
T=T+Text[K].upper()
else:
T=T+T[K-1]
print(T)
OldText="pOwERALone"
ChangeIt(OldText,"%")
import random
Arr=[10,30,40,50,70,90,100]
L=random.randrange(1,3)
U=random.randrange(3,6)
for i in range(L,U+1):
print(Arr[i],"@",end="")
86
Ans: 30 @40 @50 @70 @
16. Find the output of the following code
def disp(str):
m=' '
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0:
m=m+str[i-1]
else:
m=m+"@"
print(m.swapcase())
disp('StudyBag$2021')
a) StudyBagG@2@2 b) sTUDYbAGg@2@2 c) StudyBagG$2$2 d) None
Ans : a) StudyBagG@2@2
Note: The swapcase() method returns a string where all the upper
case letters are
lower case and vice versa. Syntax. string.swapcase().
17. What will be the output of the following code
total = 0
def add(a, b):
global total
total = a + b
print(total)
add(6, 6)
print(total)
Ans : a) 12
12
18. Find and write the output of the following Python code:
def makenew(mystr):
newstr = " "
count = 0
for i in mystr:
if count%2 ==0:
newstr = newstr+i.lower()
else:
if i.islower():
newstr = newstr+i.upper()
else:
newstr = newstr+i
count +=1
newstr = newstr+mystr[:3]
print ("The new string is :", newstr)
makenew("cbseEXAMs@2022")
87
Ans. The new string is:
cBsEeXaMs@2022cbs
19. What possible output(s) are expected to be displayed on screen at
the time of execution of the following code? Also specify the
maximum and minimum value that can be assigned to variable X.
import random
L=[10,7,21]
X=random.randint(1,2)
for i in range(X):
Y=random.randint(1,X)
print(L[Y],"$",end=" ")
def prog(name):
for x in name:
if x.isalpha():
print('Alphabet')
elif x.isdigit():
print('Digit')
elif x.isupper():
print('Capital Letter')
else:
print('Hello All')
prog('[email protected]')
a) 0 b) 2 c) 1 d) 3
Ans: b) 2
88
23. Find and write the output of the following Python code:
def changer(p,q=10):
p=p/q
q=p%q
print(p,"#",q)
return p
a=200
b=20
a=changer(a,b)
print(a,"$",b)
a=changer(a)
print(a,"$",b)
Ans.
10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20
24. What will be the output for the below code snippet?
def div(lst,n):
for i in range(0,n):
if lst[i]%5==0:
lst[i]+=5
else:
lst[i]=lst[i]//2
lt=[45,20,23,54,5]
div(lt, len(lt))
for i in lt:
print(i,end='#')
a) 50#25#11.5#27.0#10# b) 50#25#11#27#10#
c) 50#25#1#0#10# d) 225#100#1#0#25#
89
8. Exception Handling in Python
Differences Between Compile-Time Errors and Runtime Errors:
Compile-Time Error (Syntax Error) Runtime Error (Exception)
Detected before execution (during parsing). Detected during execution.
Prevents the program from starting at all. Program starts, but an exception is raised during execution.
Incorrect syntax or structure in the code. Operations performed at runtime lead to exceptions.
SyntaxError ZeroDivisionError, IndexError, FileNotFoundError, TypeError
Must be corrected before the program runs. Can be handled using try/except blocks to avoid crashing.
1. Errors
▪ These are critical issues that cause the program to stop executing.
▪ Errors are usually typos or grammatical mistakes, known as syntax errors.
▪ Syntax errors are detected when we have not followed the rules of the particular programming
language while writing a program.
▪ These errors are also known as parsing errors.
▪ a syntax error is reported by the Python interpreter giving a brief explanation about the error and a suggestion
to rectify it.
▪ On encountering a syntax error, the interpreter does not execute the program unless we rectify the errors.
A syntax error in Python shell mode An syntax error in the script
2. Exceptions
90
▪ These are runtime errors that occur during program execution and disrupt the normal flow of
instructions.
▪ Exceptions are raised when internal events change the normal flow of the program.
▪ Exception in Python is nothing but errors which are encountered at the run time.
▪ An exception is a Python object that represents an error.
▪ When an error occurs during the execution of a program, an exception is said to have been raised.
Such an exception needs to be handled by the programmer so that the program does not terminate
abnormally.
▪ In Python, exceptions are errors that get triggered automatically.
▪ However, exceptions can be forcefully triggered and handled through program code.
▪ Each exception type is represented by its own class, such as ZeroDivisionError, ValueError, SyntaxError,
etc.
▪ When an exception is raised, it contains a description that explains the nature of the error. This
description often includes the error type and additional context, such as the line number where the
error occurred.
▪ A syntax error is indeed a type of exception in Python.
Errors Exceptions
Errors are generally fatal issues that stop program Exceptions are a subset of errors, specifically
execution, while exceptions are more controlled intended for handling and recovery during runtime.
situations that can be handled programmatically.
Errors are the problems in a program due to which exceptions are raised when some internal events
the program will stop the execution. occur which changes the normal flow of the
program.
Eg. Syntax errors e.g ZeroDivisionError
Exception Handling:
91
▪ Every exception has to be handled by the programmer for successful execution of the
program.
▪ To ensure this we write some additional code to give some proper message to the user if
such a condition occurs. This process is known as EXCEPTION HANDLING.
▪ Exception handlers separate the main logic of the program from the error detection and
correction code.
▪ The segment of code where there is any possibility of error or exception, is placed inside
one block. The code to be executed in case the exception has occurred, is placed inside
another block. These statements for detection and reporting the execution do not affectthe
main logic of the program.
STEPS FOR EXCEPTION HANDLING:
try-except-finally:
92
▪ An exception is said to be caught when a code designed for handling that particular
exceptionis executed. In Python, exceptions, if any, are handled by using try-except-finally
block. Whilewriting a code, programmer might doubt a particular part of code to raise an
exception. Suchsuspicious lines of code are considered inside a try block which will always
be followed by anexcept block. The code to handle every possible exception, that may
raise in try block, will bewritten inside the except block.
▪ If no exception occurs during the execution of the program, it will produce the desired output
successfully. However, if an exception is encountered, the further execution of the code inside the
try block will be stopped, and control will be transferred to the corresponding except block.
▪ If another exception occurs that is not specified in the except block, the program will stop unless
a more general except block is present to handle such exceptions.
▪ The compiler or interpreter keeps track of the exact position where the error has occurred.
▪ Exception handling can be done for both user-defined and built-in exceptions.
1. The try block:
▪ The try block contains the code that may raise an exception. It is the first block that is
executed.
▪ If no exception occurs, the code inside the try block will execute completely, and the
program moves to the end of the try block or the finally block (if present).
▪ If an exception occurs, Python stops executing the try block and searches for an appropriate
except block to handle the exception.
2. The except block: lets you handle the error.
▪ The except block is used to handle specific exceptions raised in the try block. When an
exception occurs in the try block, control is transferred to the except block.
▪ If no exception occurs, the except block is skipped.
▪ You can specify different types of exceptions (like ValueError, ZeroDivisionError, etc.)
to handle different errors specifically. Alternatively, you can catch all exceptions using a
general except block.
▪ The except block in Python can handle multiple exceptions at once, and you can specify more than
one exception type.
▪ You can use any number of exceptions,
93
try-except syntax:
try:
# There can be error code in this block
except [exception name]:
# Do this to handle exception;
# executed if the try block throws an error
except NameError :
print("Varibale is not defined...")
OUTPUT:
Varibale is not defined…
Output:
Something went wrong
94
3. Handling Type Error but it has ZeroDivisionError:
try:
c=5/0
except TypeError:
print("You cannot divide")
Output:
ZeroDivisionError: division by zero
4. Handling error:
try:
c=5/0
except:
print('Some "Error" is in the program')
Some "Error" is in the program
95
7. Multiple exception handlers with ‘as’
try:
result = 10 / 0
result = 10 + 'd'
except ZeroDivisionError as e:
print("Error occurred:", e)
except TypeError as e1:
print("Error occurred:",e1)
Output:
Error occurred: division by zero
96
10. No exception occurred
try:
num = int(input("Enter a number: "))
result = 10 / num
print('Result after division is:',result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
Output:
Enter a number: 2
Result after division is: 5.0
Output:
Enter a number: 0
Error: Division by zero is not allowed.
97
13. finally Clause (Exception in program)
try:
print(x) # This will raise an exception, x is not defined
except:
print("Something went wrong") # This will catch the exception
finally:
print("The 'try except' is finished") #will always execute
Output:
Something went wrong
The 'try except' is finished
Output:
10
The 'try except' is finished
15. In Python, an except block should not be empty.
try:
print(x) # This will raise a NameError because 'x' is not defined
except NameError:
98
17. Finally with multiple exception without error
n = int(input("Enter a number: "))
m = int(input("Enter a number: "))
try:
result = n / m
print('Result after division is:',result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
finally:
print('Well done!')
Output:
Enter a number: 10
Enter a number: 2
Result after division is: 5.0
Well done!
18. Finally with multiple exception with devision error
n = int(input("Enter a number: "))
m = int(input("Enter a number: "))
try:
result = n / m
print('Result after division is:',result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
finally:
print('Well done!')
Enter a number: 10
Enter a number: 0
Error: Division by zero is not allowed.
Well done!
19. Finally with multiple exception with value error
try:
n = float(input("Enter a number: "))
m = float(input("Enter a number: "))
result = n / m
print('Result after division is:', result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
finally:
print('Well done!')
99
Output:
Enter a number: 10
Enter a number: div
Error: Please enter a valid number.
Well done!
try:
result = n / m
print('Result after division is:', result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter a valid number.")
finally:
print('Well done!')
Output:
try:
print("Hello, World!")
SyntaxError: expected 'except' or 'finally' block
100
23. Try with final should be used. (exception in the program)
try:
print(10 /2) # This will raise a ZeroDivisionError
finally:
print("Done.")
try:
x = int("abc")
except (ValueError, TypeError):
print("ValueError or TypeError occurred.")
try:
print("Hello, World!")
SyntaxError: expected 'except' or 'finally' block
In Python, when handling exceptions, you must specify the type of exception in the except clause. If
you don't specify the exception type, it will result in a syntax error.
try:
x = 10 / 0 # ZeroDivisionErrorexcept ZeroDivisionError:
print("Cannot divide by zero.")
try:
x = 10 / 0except:
print("Some error occurred.") # This is valid, but not recommended
for precise handling.
In the second example, the exception type is not specified, which is technically allowed (it will
catch all exceptions), but it's generally recommended to specify the type of exception to catch
specific errors more precisely.
So, while you technically don't have to specify the exception type in the except clause (you can
use just except:), it is good practice to always specify the exception type for clarity and to avoid
catching unexpected errors.
101
1. Compiled Language Characteristics
• Compilation to Bytecode: When you run a Python script, the Python interpreter first compiles the
source code into bytecode. This bytecode is a low-level representation that is platform-independent.
• Stored Bytecode: The compiled bytecode can be saved in .pyc files, which can be executed faster in
subsequent runs, as the compilation step is skipped.
• Execution of Bytecode: After compiling the code to bytecode, the Python interpreter executes that
bytecode line by line using the Python Virtual Machine (PVM).
Dynamic Typing and Runtime Checks: Python handles dynamic typing and various runtime checks during
execution, which are characteristic of interpreted languages
Python is considered both a compiled and an interpreted language. Here's how it fits into both
categories:
▪ Python uses a combination of both compilation and interpretation, making it unique compared to
traditional compiled languages (like C) or purely interpreted languages.
▪ compiler checks syntax error but syntax error is reported by interpreter.
Compiler's Role
1. Syntax Checking:
o When you run a Python script, the first step the Python interpreter (which acts like a
compiler) does is check the code for syntax errors during the parsing phase.
o If there are any syntax errors, it will not generate bytecode, and the program will not
execute.
Interpreter's Role
2. Error Reporting:
o While the checking happens during the compilation phase, the actual reporting of the syntax
error (the message you see) is handled by the interpreter.
o The interpreter will produce an error message indicating the nature of the syntax error,
including details about where the error occurred in the code.
The compiler checks the syntax and prevents the program from compiling if there are errors.
The interpreter reports the syntax errors, providing feedback to the user about what went wrong.
102
Exercise:
1. In a try-except block, can there be multiple 'except' clauses?
a. No, there can be only one 'except' clause.
b. Yes, but only if the exceptions are of the same type.
c. Yes, it allows handling different exceptions separately.
d. No, 'except' clauses are not allowed in a try-except block.
2. When might you use the 'finally' block in exception handling?
a. To handle exceptions that are expected to occur frequently.
b. To provide a resolution for every possible error.
c. To close resources that were opened in the 'try' block, regardless of whether an exception
occurred or not.
d. To avoid having to use 'except' blocks.
3. What will be the output of the following code snippet?
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero!")
except ArithmeticError:
print("Arithmetic error occurred!")
else:
print("No error!")
a. Division by zero!
b. Arithmetic error occurred!
c. No error!
d. This code will raise a syntax error.
4. Which of the following is NOT a standard built-in exception in Python?
a. ValueError
b. IndexError
c. NullPointerException
d. KeyError
5. What is an exception in programming?
a. An error that occurs during runtime
b. A warning message from the compiler
c. A comment in the code
d. A statement that terminates the program
6. What is the purpose of the "try" block in a try-except construct?
a. To handle the exception by executing specific code
b. To specify the type of exception to be thrown
c. To define a custom exception class
d. To ensure a specific block of code always executes
7. Which of the following exceptions in Python is not a built-in exception?
a. ValueError
b. KeyError
c. CustomError
d. IndexError
8. Which block is a mandatory block in exception handling process?
103
a. try
b. except
c. finally
d. else
9. Assertion (A): In Python, the "try" block is used to enclose code that might raise an exception.
Reasoning (R): The "try" block is where the program attempts to execute code that might result in
an exception. If an exception occurs, it is handled in the corresponding "except" block.
a. Both A and R are true and R is correct explanation of A
b. Both A and R are true but R is not correct explanation of A
c. A is True but R is False
d. A is false but R is True
Answer: (A) Both A and R are true, and R is the correct explanation of A.
10. Assertion (A): The "finally" block in Python is always executed, regardless of whether an exception
is raised or not.
Reasoning (R): The "finally" block contains code that is guaranteed to execute, whether an
exception occurs within the "try" block or not.
Answer:(A) Both A and R are true, and R is the correct explanation of A
11. Assertion (A): Python allows multiple "except" blocks to be used within a single "try" block to
handle different exceptions.
Reasoning (R): By using multiple "except" blocks with different exception types, Python provides the
flexibility to handle various types of exceptions separately.
Answer: (A) Both A and R are true, and R is the correct explanation of A
12. Assertion (A): Exception handling handles all types of errors and exceptions.
Reasoning (R): Exception handling is responsible for handling anomalous situations during the
execution of a program.
Answer: A is false, but R is true.
13. State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct.
14. State whether the following statement is True or False:
While handling exceptions in Python, the name of the exception has to be compulsorily added with
the except clause.
Answer: False
15. State whether the following statement is True or False:
A try block in Python must always be followed by at least one except block.
Answer: False
16. State whether the following statement is True or False:
A try block can exist without an except block if a finally block is present.
Answer: True
17. State whether the following statement is True or False:
A specific exception handler in Python can handle other types of exceptions.
Answer: False
18. State whether the following statement is True or False:
If an exception is not caught but another built-in exception exists in the program, Python will raise
the first encountered exception.
Answer: True
104
19. State whether the following statement is True or False:
An exception may be raised even if the program is syntactically correct.
20. Which of the following statements is true?
a. The standard exceptions are automatically imported in Python programs.
b. All raised standard exceptions must be handled in Python.
c. When there is deviation from the rules of a programming language, a semantic error is
thrown.
d. If any exception is thrown in try block, else block is executed.
21. Identify the statement(s) from the following options which will raise TypeError exception(s):
a. print('5')
b. print( 5 * 3)
c. print('5' +3)
d. print('5' + '3')
22. What will be the output of the following Python code?
lst = [1, 2, 3]
print(lst[3])
a. NameError b. ValueError c. IndexError d. TypeError
23. What will be the output of the following Python code?
int('65.43')
a. ImportError b. ValueError c. TypeError d. NameErro
24. What will be the output of the following Python code?
print("Hello" + 5)
a."Hello5" b. TypeError c. Hello 5 d. None of the above
105
9. File Handling in Python
File handling:
▪ File handling in Python allows us to store data that can be accessed by our code for various
purposes
like reading, writing, modifying and deleting data from files.
Types of files:
1.Text Files: Text files are structured as a sequence of lines, where each line includes a sequence of
characters.
2. Binary Files: A binary file is any type of file that is not a text file. collection of 0s and 1s.
3. CSV File: CSV (Comma Separated Values) is a file format for data storage which looks like a text file. The
information is organized with one record on each line and each field is separated by comma.
Terminology related to file handling:
File: - File is a named location on a secondary storage media where data are permanently stored for later
access.
Stream: - It refers to a sequence of bytes.
Data: Raw fact
Information: processed data.
1. Text File:
▪ A text file can be understood as a sequence of characters consisting of alphabets, numbers and
other special symbols.
▪ A text file is usually considered as sequence of lines.
▪ Each line is terminated by a special character, known as End of Line (EOL).
▪ From strings \n is newline character.
▪ Files with extensions like .txt, .py, .csv.
▪ open a text file using a text editor (e.g., Notepad),
▪ In ASCII, UNICODE or any other encoding scheme, the value of each character of the text file is
stored as bytes.
▪ A text file consists of human readable characters, which can be opened by any text editor.
106
▪ Contents in a text file are usually separated by whitespace, but comma (,) and tab (\t) are also
commonly used to separate values in a text file.
2. Binary file:
▪ Binary files are stored in terms of bytes (0s and 1s), Represents the actual content such as
image, audio, video executable files, etc.
▪ These files are not human readable. Thus, trying to open a binary file using a text editor will
show some garbage values.
▪ Binary file is not human readable.
▪ Specific software is needed to read or write the contents of a binary file.
▪ It is sequence of bytes. Even a single bit change can corrupt the file and make it unreadable to
the supporting application.
107
TEXT FILE
1. Opening a file
▪ To work with a file, first of all you have to open the file.
▪ To open a file in python, open( ) function is used.
▪ The open () function takes two parameters; filename, and mode.
▪ open () function returns a file object.
▪ This function returns a file object called file handle which is stored in the variable file object.
▪ variable to transfer data to and from the file by calling the functions defined in the Python’s io
module.
File object:
▪ The file object establishes a link between the program and the data file stored in the permanent
storage.
▪ The file object is not the actual data contained in the file, but instead it has a “handle” that it
can use to access the data.
108
Absolute path and Relative path
▪ The absolute paths is the full path to some ▪ Relative Path is the location of file/folder from
place on your computer. the current folder or current working directory
▪ e.g: C:/users/admin/docs/staff.txt (folder)denoted as a dot(.) while its parent
▪ PWD is C:/users/admin/ directory(folder) is denoted with two dots(..).e,g:
▪ PWD + relative path = absolute path. Docs/staff.txt
▪ The relative path is the path to some file with
respect to your current working directory (PWD).
▪ sys.path ▪ os.path.exists("C:/users/admin/docs/staff.txt")
▪ This function shows the PYTHONPATH set in This will return TRUE
the current system.
▪ F=open(“c:\\cs\\main\\cls12.txt”,”w”) ▪ SP= open ("story.txt","rt")
▪ F=open( r “c:\main\cls12.txt”,”w”)
Raw string
File access_mode:
▪ It is an optional argument that represents the mode in which the file has to be accessed by the
program.
▪ It is also referred to as processing mode.
109
‘a’ ‘ab’ ‘a’ ▪ Append - Opens a file for appending,
▪ Creates the file if it does not exist
▪ The file offset position is at the end of the file
▪ New data is added at the end without modifying existing content.
‘r+’ ‘rb+’ ‘r+’ ▪ Opens the file in both read and write mode.
▪ File must exist, otherwise error is raised.
▪ The file offset position is at the beginning of the file.
‘w+’ ‘wb+’ ‘w+’ ▪ Opens the file in read, write and binary mode.
▪ If the file already exists, the contents will be overwritten.
▪ If the file doesn’t exist, then a new file will be created.
▪ Beginning of the file.
‘a+’ ‘ab+’ ‘a+’ ▪ Opens the file in append and read mode.
▪ If the file doesn’t exist, then it will create a new file.
▪ The file offset position is at the end of the file
‘x’ ‘xb’ ‘x’ ▪ Create - Creates the specified file, returns an error if the file exists
3. Closing a file
▪ As reference of disk file is stored in file handle so to close we must call the close() function through
the file handle and release the file.
▪ The system frees the memory allocated to it.
▪ Python makes sure that any unwritten or unsaved data is flushed off (written) to the file before it is
closed.
Syntax:
▪ File_object_name.close( )
▪ F.close()
Note: open function is built-in function used standalone while close() must be called through file
handle.
2.Performing operations (Basic operations with files)
▪ Read the data from a file
▪ Write the data to a file
▪ Append the data to a file
▪ Delete a file
▪ Search
Reading from a Text File
There are 3 ways to read a file:
1. The read([n]) method
2. The readline([n]) method
3.The readlines() method
110
read() readline(): redlines ()
▪ This method is used to read a ▪ This method reads one complete The method reads all the lines
specified number of bytes of line from a file where each line and returns the lines along with
data from a data file. terminates with a newline (\n) newline as a list of strings.
▪ If no argument or a negative character.
number is specified in read (), ▪ It can also be used to read a
the entire file content is read. specified number (n) of bytes of
▪ It returns string data from a file but maximum
up to the newline character (\n).
▪ If no argument or a negative
number is specified, it reads a
complete line and returns string.
▪ It returns an empty string when
EOF is reached.
S=file_Object.read() S=myobject.readline() S=myobject.readlines()
my_obj=open("myfile.txt",'r')
sb= my_bj.read(2) He
print( sb)
sa=my_bj.read(3)
print(“printing 3 letters”,sa) printing 3 letters llo
My_obj.close()
data2 = f.read(19) # Reads next 19 characters everyone
print("data:", data) Writing
ab=f.read(True) f.read(True) is valid but is treated as
f.read(1). o/p H
111
ab=f.read(-5) f.read(-N) is treated as f.read(None),
reading the entire file.
Negative values are ignored—Python does not raise
an error.
The file pointer moves to the end of the file after
reading.
for i in co:
print(i)
except FileNotFoundError:
print("Error: File not found.")
112
readlines(n)
m=open("myfile.txt",'r') Output
print (m.readlines(5)) Hello everyone
print (m.readlines(True)) Hello everyone
print (m.readlines(16)) ['Hello everyone \n', 'Writing multiline strings \n']
print (m.readlines(0)) ['Hello everyone \n', 'Writing multiline strings \n', 'This is the third line\n']
print (m.readlines(None)) ['Hello everyone \n', 'Writing multiline strings \n', 'This is the third line\n']
print (m.readlines(False)) ['Hello everyone \n', 'Writing multiline strings \n', 'This is the third line\n']
print (m.readlines(-4)) ['Hello everyone \n', 'Writing multiline strings \n', 'This is the third line\n']
split() splitlines()
Writing to a Text File: There are 2 way two write the data in file.
113
f = open(“story.txt", 'a+') L=[]
f.write("\nGuntur") f=open("pk1.txt","w")
f.close() n=int(input("number of lines is to be entered :"))
for i in range(n):
print("enter line",i+1,)
Line=input("")
Line=Line+"\n"
L.append(Line)
f.writelines(L)
f.close()
▪ Every file maintains a file pointer which tells the current position in the file where reading and
writing operation will take. When we perform any read/write operation two things happens:
▪ The operation at the current position of file pointer
▪ File pointer advances by the specified number of bytes.
114
tell() seek()
tell() method of python tells us the current seek(offset[, from]) method changes the current file
position within the file position.
• This function returns an integer that • Syntax : file_object.seek(offset [, reference_point])
specifies the current position of the file fileObject.seek(5,0)
object in the file.
• The position so specified is the byte ▪ OffsetThe offset argument indicates the number of
position from the beginning of the file till bytes to be moved. default reference point is 0.
the current position of the file object. ▪ reference_point:
Syntax: file_object.tell() • 0 - beginning of the file
• 1 - current position of the file
• 2 - end of file
f = open("demofile.txt", "r") 1. f = open("a.txt", 'rb+')
print(f.readline()) 2. print(f.tell())
print(f.tell()) 3. print(f.read(7)) # read seven characters
Hello! Welcome to DBS Public School 4. print(f.tell())
Output: 5. f.seek(9) # moves to 9 position from beginning
35 6. print(f.read(5))
file.seek(15,0) 7. f.seek(4, 1) # moves to 4 position from current
s=file.tell() location
Output: 8. f.seek(-5, 2) # Go to the 5th byte before the end
15 9. print(f.read(5))
10. f.close()
closed It returns true if the file is closed and false when print(f.closed) False / True
the file is open.
encoding Encoding used for byte string conversion. print(f.encoding) cp1252
mode Returns file opening mode. print(f.mode) a+
name Returns the name of the file which file object print(f.name) a.txt
holds.
newlines Returns “\r”, “\n”, “\r\n”, None or a tuple print(f.newlines) None
containing all the newline types seen.
115
STANDARD FILE STREAMS
We use standard I/O Streams to get better import sys
performance from different I/O devices. f=open(r"hello.txt")
1. Standard input Stream sys.stdin line1=f.readline()
2. Standard output Stream sys.stdout line2=f.readline()
3. Standard error Stream sys.stderr sys.stdout.write(line1)
sys.stdout.write(line2)
sys.stderr.write("\nNo errors occured\n")
f.close()
Output: Output:
Count of 'to': 6 I want for go for the market.
He decided for stay home.
for be or not for be, that is the question.
She loves for travel for new places.
There is nothing for worry about.
Python program that writes multiple lines to a file using the write() function.
with open('output.txt', 'w') as file: Output:
file.write("Hello, this is line 1.\n") Hello, this is line 1.
file.write("This is line 2.\n") This is line 2.
file.write("And here is line 3.\n") And here is line 3.
116
Exercise
1. If a text file is opened in w+ mode, then what is the initial position of file pointer/cursor?
a. Beginning of file b. End of the file
c. Beginning of the last line of text file d. Undetermined
2. To read the entire remaining contents of the file as a string from a file object myfile, we use
a. myfile.read(2) b. myfile.read() c. myfile.readline() d.
myfile.readlines()
3. Which function of a file object can be used to fetch the current cursor position in terms of number
of bytes from beginning of file?
a. seek( ) b. bytes( ) c. tell( ) d. fetch( )
4. which of the following function returns a list datatype
a. d=f.read() b. d=f.read(10) c. d=f.readline() d. d=f.readlines()
5. The correct syntax of seek() is:
a. file_object.seek(offset [, reference_point]) b. seek(offset [, reference_point])
c. seek(offset, file_object) d. seek.file_object(offset)
6. What will be the output of the following statement in python? (fh is a file handle) fh.seek(-30,2)
Options:- It will place the file pointer:-
a. at 30th byte ahead of current current file pointer position
b. at 30 bytes behind from end-of file
c. at 30th byte from the beginning of the file
d. at 5 bytes behind from end-of file .
7. Which Python function is used to open a text file for reading?
a. open("file.txt", "w") b. open("file.txt", "r") c. read("file.txt") d. write("file.txt")
8. Raman wants to open the file abc.txt for writing the content stored in a folder name sample of his
computer d drive help raman to tell the correct code for opening the file
a myfile=open(“d:\\sample.txt\\abc”,’w’)
b. myfile=open(“d:\\sample\\abc.txt”,’w’)
c. myfile=open(“d:\\sample\abc.txt”,’w’)
d. all of the above
9. What would be the output of following code?
f1 = open('data.txt')
L = f1.readlines()
print(L[2])
a. The third line of data.txt is printed if it exists.
b. The second line of data.txt is printed.
c. An IndexError occurs if data.txt has fewer than 3 lines.
d. The code will always print the last line of data.txt.
10. what is the output of the following code fragment?
out = open('output.txt', 'w')
out.write('hello,world!\n')
out.write('how are you')
out.close()
11. open('output.txt').read()
a. 'hello,world! how are you'
b. 'hello,world!\nhow are you'
c. ['hello,world!\n', 'how are you']
d. 'hello,world!\nhow are you\n'
117
12. Which is correct way of closing the text file?
a. f.close() b. close(f) c. Both a and b d. None
13. Which statement is correct to read n bytes from text file using f as file object?
a. f.read(n) b. f.readline(n) c. Both a and b d. None
14. Which of the following function is used to read all the lines of the text file?
a. readline() b. read() c. readlines() d. readit()
15. What is the return datatype of read () function?
a. string b. List c. Tuple d. Dictionary
16. What is the return datatype of readlines() function?
a. string b. List c. Tuple d. Dictionary
17. Which function is used to write List of strings on to the text file?
a. writelist() b.writeline() c.writelines() d. writeall()
18. In which mode text file should be opened to add the data at the end to the text file?
a)’r’ b)’w’ c)’a’ d)’b’
19. Which of the following command can be used to open the text file in writing as well as reading
mode? a)f=open(“c:\data.txt”,’r’) b)f=open(“c:\data.txt”,’w+’) c)f=open(c:\\data.txt”,’w+)
d)f=open(“c:\\data.txt”,’w’)
20. Which of the following statements is true regarding the opening modes of a file?
a) While opening a file for reading, if the file does not exist, an error occurs.
b) While opening a file for writing ,if the file does not exist, an error occurs.
c) While opening a file for reading, if the file does not exist, a new file is created.
d) None of the above.
21. What is the difference between the read() and readline() methods in Python?
a. The read() method reads all of the data from a file, while the readline() method reads only one
line
of data at a time.
b. The read() method returns a string, while the readline() method returns a list of strings.
c. The read() method does not move the file pointer, while the readline() method moves the file
pointer
to the next line.
d. All of the above
22. If a text file is opened in w+ mode, then what is the initial position of file pointer/cursor?
a. Beginning of file b. End of the file
c. Beginning of the last line of text file Undetermined
23. State True or False
“csv files are special text files”. True
24. State True or False
“text files are slower in processing as they requires translation of special characters” True
25. Assertion(A): File opened in’ w’ mode always places the cursor at the beginning of the file and
never generates an error.
Reason(R): ‘w’ mode creates the file even if the file doesn’t exist.
a)Both A and R are true and R is the correct explanation of A.
b)Both A and R are true but R is not the correct explanation of A.
c)A is true but R is false.
d)R is true but A is false. .
26. Assertion(A):Text file contains data in human readable form.
Reason(R): It executes faster than any other type of the file.
27. Assertion(A): read()and readline() are used to read the data from the text file.
Reasoning(R): readlines() function is used to read all lines from the file in the form of a List.
118
28. What will be the most correct option for possible output of the following code, given that the code executes
without any error.
f = open(‘cricket.txt’) data = f.read(150) print(len(data))
a. It will always be 150 b. 151 c. More than or equal to 150 d. Less than or equal to 150
29. For storing numeric data in a text file, it needs to be converted into …………… using …………… function.
a. integer, int() b. integer, float() c. string, int() d. string, str()
30. Assertion (A): The file access mode used to add or append the data in the file is 'a'.
Reasoning (R): In the access mode, 'a', the text will be appended at the end of the existing file. If the file does
not exist, Python will create a new file and write data to it.
a. Both A and R are true and R is the correct explanation of A.
b. Both A and R are true but R is not the correct explanation of A.
c. A is true but R is false.
d. A is false but R is true.
31. Assertion (A): The binary files are an advanced version of text files and work similar to text files.
Reasoning (R): The data in binary files are stored in the form of binary digits, 0 and 1; and is directly understood
by the computer.
Answer: A is false but R is true.
1. Write a function count_char() that reads a file named “char.txt” counts the number of times
character “a” or “A” appears in it.
2. Write a function count_word() that reads a text file named “char.txt” and returns the number of
times word “ the” exists.
3. Write a function count_line() that reads a text file named “char.txt” and returns the number of lines
that start with a vowel.
4. Write a program in python to count vowels, consonants, digits, spaces, special characters, spaces,
words and lines from a text file named “student.txt”.
5. Write a user-defined function named Count() that will read the contents of a text file named
“India.txt” and count the number of lines which start with either “I” or “T”.
6. Write a method in python to read lines from a text file AZAD.TXT and display those lines, which are
starting with an alphabet ‘T’.
7. Write a program to read contents from the text file mydiary.txt and count number of lines with
ending letter “r”.
8. Write a Python program to count all the line having 'a' as last character.
9. write a method in python to read lines from a text file DIARY.TXT and display those lines which start
with the alphabets P.
10. write a program that copies a text file "source.txt" onto "target.txt" barring the lines starting with
@ sign.
11. Write a program to read the file data.txt and count number of lines present in it.
12. Write a program to read the file story.txt and display second last line of the file.
13. Write a program to read the file letter.txt and display those words which has less than or equal to
four characters.
14. Write a Python function that extracts and prints all email addresses from a text file named
"contacts.txt".
119
1. Write a function count_char() that reads a file named “char.txt” counts the number of times
character “a” or “A” appears in it.
def count_char(filename, char):
file = open(filename, "r")
content = file.read() # Read the file content
file.close() # Manually close the file
count = 0
for c in content:
if c.lower() == char.lower(): # Case insensitive comparison
count += 1
return count
print(count_char("char.txt", "a"))
2. Write a function count_line() that reads a text file named “char.txt” and returns the number of
lines that start with a vowel.
def count_line():
file = open("story.txt", "r")
lines = file.readlines()
file.close() # Close the file
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
count = 0
return count
120
4. Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT,
and display those words, which are less than 4 characters.
def DISPLAYWORDS():
file = open("STORY.TXT", "r")
content = file.read()
file.close()
DISPLAYWORDS()
5. Write a function in python that displays the number of lines starting with word “How” in the file
“Story.txt”.
f=open('Story.txt')
da=f.readline()
c=0
while da:
da=f.readline()
ta=da.split()
if ta[0]=='How':
print(ta[0])
c+=1
if c!=0:
print('no of lines starts with "How" is:',c)
else:
print('no lines starts with "How"')
6. Write a function in python that displays the number of lines ending with word “star” in the file
“Story.txt”.
f=open('Story.txt')
da=f.readlines()
c=0
for i in da:
ta=i.split()
if ta[-1]=='satr' or ta[-1]=='star.':
c+=1
if c!=0:
print("No.of time line ends with 'star':",c)
else:
print("No line ends with 'star':")
121
7. Write a function in python that displays the number of lines starting with ‘T’ in the file “para.txt”.
def countT():
f=open("pk.txt","r")
lines=0
l=f.readlines()
for i in l:
if i[0]=='T':
lines+=1
print("NO of lines are:",lines)
f.close()
countT()
8. Write a Python program to count all the line having 'r' as last character.
def countr():
f=open("pk.txt","r")
lines=0
l=f.readlines()
for i in l:
if i[-2]=='r' or 'r. ':
lines+=1
print("NO of lines are:",lines)
f.close()
countr()
9. Count occurrences of each word in given text file.
text=open("pk1.txt", "r")
d=dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
122
11. Write a program to read text file story.txt and count number of lines starting with letter ‘A’ or ‘a’.
def ser():
F = open("story.txt", 'r')
count = 0
L = F.readlines()
for i in L:
if i[0] == 'A' or i[0] == 'a':
count = count + 1
F.close()
print("no. of lines", count)
ser()
12. Write a program to read a text file and display the count of word “what” and display number of
times it is repeated.
def count(w):
f=open('priya.txt', 'r')
c=0
d=f.read()
s=d.split()
for i in s:
if i==w:
c+=1
return c
w=input("Eneter a word to be searched")#enter What
s=count(w)
print(s,"times present")
123
10.Binary File
▪ Binary files are used to store binary data such as images, video files, audio files etc.
▪ They store data in the binary format (0’s and 1’s). In Binary files there is no delimiter for a line.
Pickle module:
▪ It is used for serializing and de-serializing python object structures.
▪ The process to converts any kind of python objects (list, dict, etc.) .
▪ We can converts the byte stream (generated through pickling) back into python objects by a process
called as un pickling.
1. Serialization(pickling)
▪ It is the process of transforming data or an object in memory (RAM) to a stream of bytes called byte
streams.
▪ These byte streams in a binary file can then be stored in a disk or in a database or sent through a
network.
2. De-serialization (unpickling)
• It is the inverse of pickling process where a byte stream is converted back to Python object.
124
Serialization(pickling) De-serialization (unpickling)
▪ It is the process of transforming data or an object in ▪ It is the inverse of pickling process where a byte
memory (RAM) to a stream of bytes called byte stream is converted back to Python object.
streams.
▪ These byte streams in a binary file can then be stored
in a disk or in a database or sent through a network.
125
1. Creating binary file with roll number, name, marks for n number of students User define function.
import pickle Output:
Enter number of records: 2
def Create_Binary(): Enter Roll No: 101
Enter Name: Ram
D = [] Enter Marks: 15
n = int(input("Enter number of records: ")) Enter Roll No: 105
for i in range(n): Enter Name: Siva
r = int(input("Enter Roll No: ")) Enter Marks: 55
name = input("Enter Name: ") Data saved successfully!
m = int(input("Enter Marks: "))
R = [r, name, m]
D.append(R)
try:
f = open("Bfile.dat", 'wb')
pickle.dump(D, f)
f.close()
print("Data saved successfully!")
except Exception as e:
print("Error occurred while saving:", e)
Create_Binary()
while True:
r=int(input("enter Roll no"))
n=input("Enter name")
m=int(input("Enter marks"))
v=[r,n,m]
data.append(v)
ch=input('want to enter
more(yes/no)')
if ch=='no':
break
pickle.dump(data,f)
print('done')
f.close()
126
import pickle Output:
def append_student_data(): Enter Roll No: 112
data = [] Enter Name: Ishant
try: Enter Marks: 45
with open("Bfile.dat", 'rb') as f: Want to enter more (yes/no)? no
data= pickle.load(f) Data saved successfully!
except EOFError:
pass After append
append_student_data()
read_student_data()
127
2. Search a record in Binary File:
import pickle
def Search_record(): Output:
f = open('Bfile.dat', 'rb') Enter rollno to be
flag = False searched: 101
r_no = int(input("Enter roll no to be searched:
")) [101, 'Ram', 15]
try:
rec = pickle.load(f) # Load all records
for i in rec:
if i[0] == r_no:
print(i)
flag = True
except EOFError:
pass
finally:
f.close() # Ensure the file is closed
return flag
flag = Search_record()
if not flag:
print("No Records found")
flag,da=Update_marks()
if flag==True:
print('data After update',da)
else:
print('Roll number is not found')
128
4. Delete a record from binary file:
import pickle
def deletestudent(): OUTPUT:
try: Enter roll to delete record:111
roll=int(input('Enter roll to delete Record Deleted
record:'))
f1 = open("Bfile.dat", "rb")
Da = pickle.load(f1)
found = 0
lst = []
for i in range(len(Da)):
if Da[i][0] != roll :
lst.append(i)
else:
found = 1
f2 = open("Bfile.dat", "wb")
pickle.dump(lst, f2)
f2.close()
if found == 1:
print("Record Deleted")
else:
print("Record not found")
f1.close()
except (FileNotFoundError, EOFError):
print("File not found or empty.")
deletestudent()
129
Exercise:
1. The process of converting byte stream back to the original structure is known as
a. Pickling b. Unpickling c. Packing d. Zipping
2. Which file mode is used to handle binary file for reading.
a. rb b. rw c. r d. w
3. Which of the following is not a correct statement for binary files?
a. Easy for carrying data into buffer b. Much faster than other file systems
c. Characters translation is not required
d. Every line ends with new line character ‘\n’
4. Which one of the following is correct statement?
a. import – pickle b. pickle import c. import pickle d. All the above
5. Which of the following file mode opens a file for append or read a binary file and moves the files
pointer at the end of the file if the file already exist otherwise create a new file?
a. a b. ab c. ab+ d. a+
6. Which of the following file mode opens a file for reading and writing both as well as overwrite the
existing file if the file exists otherwise creates a new file?
a. w b. wb+ c. wb d. rwb
7. Mr Sharma is working on a binary file and wants to write data from a list to a binary file. Consider list
object as l1, binary file sharma_list.dat, and file object as f. Which of the following can be the correct
statement for him?
a. f = open(‘sum_list’,’wb’); pickle.dump(l1,f)
b. f = open(‘sum_list’,’rb’); l1=pickle.dump(f)
c. f = open(‘sum_list’,’wb’); pickle.load(l1,f)
d. f = open(‘sum_list’,’rb’); l1=pickle.load(f)
8. Every file has its own identity associated with it. This is known as:
a. icon b. extension c. format d. file type
9. EOL in a file stands for :
a. End of Lines b. End of Line c. End of List d. End of Location
10. Which of the following file types allows you to store large data files in the computer memory?
a. Binary Files b. Text Files c. CSV Files d. None of these
11. Which of the following python statement will bring the read pointer to 10th character from the end of a file
containing 100 characters, opened for reading in binary mode.
a) File.seek(10,0) b) File.seek(-10,2) c) File.seek(-10,1) d) File.seek(10,2)
12. Every file has its own identity associated with it. This is known as:
a. icon b. extension c. format d. file type
13. EOL in a file stands for :
a. End of Lines b. End of Line c. End of List d. End of Location
14. Which of the following file types allows you to store large data files in the computer memory?
a. Binary Files b. Text Files c. CSV Files d. None of these
15. Assertion (A): A binary file in python is used to store collection objects like lists and dictionaries that can be
later retrieved in their original form using pickle module.
Reasoning (A): A binary files are just like normal text files and can be read using a text editor like notepad.
• (a) Both A and R are true, and R explains A.
• (b) Both A and R are true, but R does not explain A.
• (c) A is true, but R is false.
• (d) A is false, but R is true.
130
16.Assertion(A): Every open file maintains a file-pointer and keeps track of its position after every operation.
Reason(R): Every read and write operation takes place at the current position of the file pointer.
Answer: (a) Both A and R are true, and R is the correct explanation for A.
17. Assertion (A): The binary files are an advanced version of text files and work similar to text files.
Reasoning (R): The data in binary files are stored in the form of binary digits, 0 and 1; and is directly
understood by the computer.
Answer: A is false but R is true.
18. Assertion (A):For a binary file opened using 'rb' mode, the pickle.dump() method will display an error.
Reason (R):The pickle.dump() method is used to read from a binary file.
(c) A is true, but R is false.
1. Write a python Function Create_student() to create binary file and insert the student data
[Roll_no,Name,Marks].
import pickle
def Create_student():
records = []
while True:
r = int(input("Enter Roll Number: "))
n = input("Enter Name: ")
m = int(input("Enter Marks: "))
data = [r, n, m]
records.append(data)
Create_student()
display_binary()
131
3. A binary file “salary.DAT” has structure [employee id, employee name, salary].
Write a function countrec() in Python that would read contents of the file “salary.DAT” and display
the details of those employee whose salary is above 20000.
def create():
import pickle
L=[]
n=int(input("enter no of records :"))
for i in range(n):
E_id=int(input("Enter id: "))
E_name=input("Enter Name: ")
sal=int(input("enter salary: "))
r=[E_id,E_name,sal]
L.append(r)
f=open("salary.dat","wb")
pickle.dump(L,f)
f.close()
create()
import pickle
def countrec():
try:
fobj=open("salary.dat","rb")
s=pickle.load(fobj)
f=0
for i in s:
if i[2]>25000:
print(i,"whose salary is above 25000")
f=1
if f==0:
print("No employee whose salary is above 25000")
fobj.close()
except EOFError:
print("Error: The file is empty or corrupted.")
countrec()
Output:
[1101, 'Ram', 27000] whose salary is above 25000
[1155, 'Priya', 35000] whose salary is above 25000
132
4. A file sports.dat contains information in following format [event, participant].
Write a program that would read the contents from file and copy only those records from sports.dat
where the event name is “Athletics” in new file named Athletics.dat
# For creating binary file.
import pickle Output:
def createsports(): Enter number of records: 3
try: Enter Event Name: Athletics
records = [] Enter Participant Name: Ram
n = int(input("Enter number of records: ")) Enter Event Name: Cycling
for i in range(n): Enter Participant Name: Ishant
event = input("Enter Event Name: ")
Enter Event Name:
participant = input("Partipant Name: ")
Athletics
records.append([event, participant])
Enter Participant Name: Priya
with open("Sports.dat", "wb") as f: Data successfully saved
pickle.dump(records, f)
except Exception as e:
print(f"An error occurred: {e}")
createsports()
import pickle
def Create_sports():
try:
F1=open("Sports.dat", "rb")
F2=open("athletics.dat", "wb")
flag=False
s=pickle.load(F1)
for i in s:
if i[0]=="Athletics" or i[0]=="athletics":
pickle.dump(i[1],F2)
flag=True
F1.close()
F2.close()
if flag == True:
print('new file is created')
except FileNotFoundError as e:
print(f"An unexpected error occurred: {e}")
Create_sports()
133
5. A binary file “students.dat” has structure (admission_number, Name, Percentage, subject).
Write a function countrec() in Python that would read contents of the file and display the details of
those students whose subject is “Biology” and percentage is below 45%. Also display the number of such
students.
def insertdata(): Output:
try: Enter number of records: 3
import pickle Enter admission no:115
L=[]
Enter name: Ram
n=int(input("Enter number of records: "))
for i in range(n): Enter percentage:75
A_no=int(input("Enter admission_no:")) Enter subject: Biology
n=input("Enter name:") Enter admission no:119
P=float(input("Enter percentage:")) Enter name: Ishant
s=input("Enter subject:") Enter percentage:79
R=[A_no,n,P,s]
Enter subject: Math
L.append(R)
f=open("Admission.dat","wb") Enter admission no:112
pickle.dump(L,f) Enter name: Priya
f.close() Enter percentage:37
except Exception as e: Enter subject: Biology
print(f"An error occurred: {e}")
insertdata()
import pickle
def Search_Bio():
try:
f=open("Admission.dat","rb")
s=pickle.load(f)
count=0
flag=False
for i in s:
if i[3]=="Biology" and i[2]<40:
print(i)
count+=1
flag=True
print("number of students are",count)
except Exception as e:
print(f"An error occurred: {e}")
Search_Bio()
c=0 Output:
f=open("Admission.dat","rb") [112, 'Priya', 37, 'Biology']
s=pickle.load(f) number of students are 1
for list in s:
for j in list:
if j=="Biology" :
print(list)
c=c+1
print("number of students are",c)
134
6. A binary file “Student.DAT” has structure (ROLL Number, NAME).
Write a function Search () for a given roll number and display the name, if not found display
appropriate message.
import pickle
def Create_data():
try:
dck={}
n=int(input("NUMBER OF STUDENTS: "))
for key in range(n):
rollNo=int(input("enter roll no:"))
name=input("Enter name:")
dck[rollNo]=name
file=open("student.bin","wb")
pickle.dump(dck,file)
file.close()
except Exception as e:
print(f"An error occurred: {e}")
def Search(R_no):
try:
file=open("student.bin","rb")
d=pickle.load(file)
for key in d:
if key==R_no:
print("The name of roll no",key,"is",d[key])
break
else:
print("This roll no does not exits")
file.close()
except Exception as e:
print(f"An error occurred: {e}")
Create_data()
R_no=int (input("Enter roll_no to search the name:"))
Search(R_no)
Output:
NUMBER OF STUDENTS: 3
enter roll no:101
Enter name:Ram
enter roll no:105
Enter name:Priya
enter roll no:109
Enter name:Raju
Enter roll_no to search the name:101
The name of roll no 101 is Ram
135
7.A binary file “Student.DAT” has structure (roll_number, name,marks).
Write a function Update () to accept a roll number and update the marks.
import pickle
def Create():
try:
with open("Studata.dat", "wb") as file:
dck = {}
n = int(input("No of Students: "))
for _ in range(n):
rollNo = int(input("Enter Roll number: "))
name = input("Enter name: ")
marks = int(input("Enter marks: "))
dck[rollNo] = {"Name": name, "Marks": marks}
pickle.dump(dck, file)
except Exception as e:
print(f"An error occurred: {e}")
def Update(R_No):
try:
with open("Studata.dat", "rb") as f:
d = pickle.load(f)
if R_No in d:
m = int(input("Enter the new marks: "))
d[R_No]["Marks"] = m
print("Updated Data:", d)
else:
print("The roll number does not exist")
return
136
8. A binary file “salary.DAT” has structure [employee id, employee name, salary].
Write a function countrec() in Python that would read contents of the file “salary.DAT” and enter the name to update
the salary.
def Update(E_Id):
try:
file=open("Studata.bin","rb+")
d=pickle.load(file)
if E_Id in d:
m=int(input("Enter the salary: "))
d[E_Id]["Salary"]=m
print(d)
elif (E_Id not in d):
print("Emp_ID Doesn't exits")
pickle.dump(d,file)
file.close()
except Exception as e:
print(f"An error occurred: {e}")
Create()
E_ID=int(input("Enter emp_id to update salary: "))
Update(E_ID)
137
Binary programs:
9. a. Write a function to input (Candidate_ID, Candidate_Name, Designation, Experience.) the data of a candidate
and append it in a binary file.
b. Write a function to update the data of candidates whose experience is more than 5 years and change their
designation to "Senior Manager".
c. Write a function to read the data from the binary file and display the data of all those candidates who are not
"Senior Manager".
import pickle
def input_candidates():
candidata = []
n = int(input("Enter the number of candidates you want to add: "))
for i in range(n):
candidate_id = int(input("Enter Candidate ID: "))
candidate_name = input("Enter Candidate Name: ")
designation = input("Enter Designation: ")
experience = int(input("Enter Experience (in years): "))
c_data=[candidate_id, candidate_name, designation, experience]
candidata.append(c_data)
with open("candidates.bin",'wb') as f:
pickle.dump(candidata,f)
def update_senior_manager():
try:
with open('candidates.bin', 'rb') as file:
data = pickle.load(file)
print("Original data:\n", data)
updated = False # To check if any updates were made
for i in range (len(data)):
if data[i][3] > 5:
data[i][2] = 'Senior Manager'
updated = True
if updated:
with open('candidates.bin', 'wb') as file:
pickle.dump(data, file)
print("Candidates updated to Senior Manager where applicable.")
else:
print("No candidates were updated.")
# Load and display updated candidates for confirmation
with open('candidates.bin', 'rb') as file:
updated_data = pickle.load(file)
print("Updated data:", updated_data)
except FileNotFoundError:
print("The file 'candidates.bin' does not exist.")
138
def display_non_senior_managers():
try:
with open('candidates.bin', 'rb') as file:
candidat = pickle.load(file)
for i in candidat:
if i[2]=='Senior Manager':
continue
print(i)
except FileNotFoundError:
print("The file 'candidates.bin' does not exist.")
input_candidates()
update_senior_manager()
display_non_senior_managers()
10. A file, PASSENGERS.DAT, stores the records of passengers using the following structure:
[PNR, PName, BRDSTN, DESTN, FARE] ( CBSE B.Qp: 2025)
where:
PNR - Passenger Number (string type)
PName - Passenger Name (string type)
BRDSTN - Boarding Station Name (string type)
DESTN - Destination Station Name (string type)
FARE - Fare amount for the journey (float type)
Write user defined functions in Python for the following tasks :
(i) Create () - to input data for passengers and write it in the binary file PASSENGERS . DAT.
(ii) SearchDestn (D) - to read contents from the file PASSENGERS.DAT and display the details of
those Passengers whose DESTN matches with the value of D.
(iii) UpdateFare () - to increase the fare of all passengers by 5% and rewrite the updated records
into the file PASSENGERS. DAT.
#Program:
import pickle
def Create():
passenger = []
n = int(input("Enter number of passengers to add: "))
for i in range(n):
print(f"\nEntering details for passenger {i+1}:")
PNR = input("Enter PNR: ")
PName = input("Enter Passenger Name: ")
BRDSTN = input("Enter Boarding Station: ")
DESTN = input("Enter Destination Station: ")
FARE = float(input("Enter Fare: "))
pas_data = [PNR, PName, BRDSTN, DESTN, FARE]
passenger.append(pas_data)
139
def SearchDestn(D):
try:
with open("PASSENGERS.DAT", "rb") as file:
found = False
print(f"\nPassengers with destination '{D}':")
while True:
try:
passenger = pickle.load(file)
if passenger[3].lower() == D.lower():
print(passenger)
found = True
except EOFError:
break
if not found:
print("No passengers found with the given destination.")
except FileNotFoundError:
print("PASSENGERS.DAT not found. Please create it first.")
def UpdateFare():
updated_passengers = []
try:
with open("PASSENGERS.DAT", "rb") as file:
while True:
try:
passenger = pickle.load(file)
passenger[4] *= 1.05 # Increase fare by 5%
updated_passengers.append(passenger)
except EOFError:
break
with open("PASSENGERS.DAT", "wb") as file:
for p in updated_passengers:
pickle.dump(p, file)
print("\nFares updated by 5% for all passengers.")
except FileNotFoundError:
print("PASSENGERS.DAT not found. Please create it first.")
def read_after_update():
try:
with open("PASSENGERS.DAT", "rb") as file:
print("\nPassenger records after fare update:")
while True:
try:
passenger = pickle.load(file)
print(passenger)
except EOFError:
break
except FileNotFoundError:
print("PASSENGERS.DAT not found.")
Create()
SearchDestn("Mumbai")
UpdateFare()
read_after_update()
140
11. CSV Files
▪ Comma Separated Values CSV file stores tabular data in plain text.
▪ Each line of the file is a data record. Each record consists of one or more fields, separated by
commas.
▪ CSV is a common data exchange format used by the applications to produce and consume data.
▪ A CSV file is a simple text file where each line contains a
▪ list of values delimited by commas but you will encounter CSV files where data is delimited using tab
(\t) or pipe (|) or any other character.
▪ The first line of the CSV file represents the header containing a list of column names in the file.
• These files are often used for exchanging data between different applications.
• They are used to export data from spreadsheets (ex:- excel file) and databases (Ex:- Oracle, MySQL).
It can be used to import data into a spreadsheet or a database.
csv module:
▪ The csv module in Python is used to handle CSV files — files that store data in rows and columns separated by
commas (,) or other delimiters.
▪ The csv module provides functionality to both read from and write to CSV files using methods like reader,
writer.
csv.reader() This method is used to read data from a CSV file.
Syntax: csv.reader(file_object, delimiter=',')
csv.writer() This method is used to write data to a CSV file.
Syntax: csv.writer(file_object, delimiter=',')
141
1. Opening a file.
2. Performing operations
a) Read
b) Write
c) Search
d) Update
3.Closing the file.
1. Opening a file
▪ To work with a file, first of all you have to open the file.
▪ To open a file in python, open( ) function is used.
▪ The open () function takes two parameters; filename, and mode.
▪ F=open(‘my_file.csv', 'r')
2. Write operation:
csv.writer():
▪ The csv.writer() function returns a writer object that converts the user's data into a delimited string.
▪ This string can later be used to write into CSV files using the writerow() or writerows function.
142
Writing multiple rows with writerows()
import csv
rowlist =[["SN","Movie","Protagonist"],[1,"Lord of
Rings","FrodoBaggins"],
[2, "Harry Potter", "Harry Potter"]]
with open('story.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(csv_rowlist)
import csv
with open('people.csv', 'r') as file:
reader= csv.reader(file)
for k in reader:
print(k)
Write a Program to create csv file with Employee Name, EmpID and Dept for some employees in a csv
file then display records of all the employees.
# Program to write or (to create csv file)
143
# Program to read or (display data from csv file)
import csv
f=open("emp.csv","r")
rec=csv.reader(f)
for i in rec:
print(i)
f.close()
output:
['Ram', '1105', 'HR']
['Ishant', '1109', 'Manager']
['Sai', '1101', 'Clerk']
144
Multiple Choice Questions:
1. CSV stands for :
a. Comma Separated Values
b. Comma Separated Variables
c. Comma Stored Values
d. Comma Stored Variables
10. The opening function of a csv file is similar to the opening of:
a. Binary file
b. Text File
c. Both of them
d. None of them
145
11. The _______argument of open function is to specify how Python handle the newline
characters in csv file
a. newline b. line c. mode d. char
13. To specify a different delimiter while writing into a csv file, argument is used with writer object:
a. newline b. separator c. character d. delimiter
14. Which mode opens the file for exclusive creation, which fails in the case where file
already exists
a. a b. w c. x d. r
15. The file mode to open a CSV file for reading as well as writing is .
a. a+ b. w+ c. r+ d. All the above.
18.How can you read a CSV file in Python using the `csv` module?
a. csv.read(file)
b. csv.reader(file)
c. csv.load(file)
d. csv.load_csv(file)
19.What function is used to write data to a CSV file using the `csv` module in Python?
a. csv.write()
b. csv.writer()
c. csv.write_csv()
d. csv.write_to_file()
146
20.In a CSV file, how are values typically separated?
a. By commas (`,`)
b. By spaces (``)
c. By semicolons (`;`)
d. By tabs (`\t`)
21.How can you write a dictionary to a CSV file using the `csv` module in Python?
a. csv.write_dict()
b. csv.writerows()
c. csv.writer_dict()
d. csv.DictWriter()
22.Which of the following statements is true about reading a CSV file with the `csv` module in Python?
a. Each row is returned as a list of strings
b. Each row is returned as a dictionary
c. Each column is returned as a separate value
d. CSV files cannot be read using the `csv` module
25. Assertion (A): CSV (Comma Separated Values) is a file format for data storage that looks like a text file.
Reason (R): The information is organized with one record on each line and each field is separated by a comma.
Answer: (a) Both A and R are true, and R correctly explains A.
26. Assertion (A): CSV file is a human-readable text file where each line has fields separated by comma or some
other delimiter.
Reason (R): writerow() method is used to write a single row in a CSV file.
Answer: (b) Both A and R are true, but R is not the correct explanation for A (R is a separate fact about writing
CSV).
27. Assertion (A): CSV files can be opened and edited using text editors as well as spreadsheet software.
Reason (R): CSV files are plain text files with data fields separated by commas.
Answer: (a) Both A and R are true, and R is the correct explanation for A.
28. Assertion (A): csv.writer() is used to write data into a CSV file in Python.
Reason (R): csv.writer() automatically adds column headers to the CSV file.
Answer: (c) A is true, but R is false.
147
1. Vedansh is a Python programmer working in a school.
For the Annual Sports Event, he has created a csv file named Result.csv, to store the results of students in
different sports events. The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where St_Id is Student ID (integer) ST_name is Student Name (string) Game_Name is name of game in
which student is participating(string) Result is result of the game whose value can be either 'Won', 'Lost' or
'Tie' For efficiently maintaining data of the event, Vedansh wants to write the following user defined
functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings should
also be added on top of the csv file.
wonCount() – to count the number of students who have won any event. As a Python expert, help him
complete the task.
import csv
def Accept():
n=int(input('Enter no of student'))
L=[]
for i in range(n):
sid=int(input("Enter Student ID "))
sname=input("Enter Student Name")
game=input("Enter name of game")
res=input("Enter Result")
data=[sid, sname, game, res]
L.append(data)
f=open("Result.csv", "w")
csvwriter=csv.writer(f)
csvwriter.writerows(L)
f.close()
def wonCount():
with open("Result.csv", "r") as f:
Data = csv.reader(f)
count = 0
for x in Data:
if len(x) >= 4 and x[3].strip().lower() == "won":
count+=1
print('Number of students who won:', count)
Accept()
wonCount()
Enter no of student2
Enter Student ID 101
Enter Student NameRam
Enter name of gameCricket
Enter ResultWon
Enter Student ID 105
Enter Student NameSiva
Enter name of gamekhokho
Enter Resultloss
Number of students who won: 1
148
2. Write a Program in Python that defines and calls the following user defined functions:
a) ADD() – To accept and add data of an employee to a CSV file ‘record.csv’. Each record consists of a list
with field elements as [empid, name and mobile] to store employee id, employee name and
employee salary respectively.
b) COUNTR() – To count the number of records present in the CSV file named ‘record.csv’.
#Program: Output:
Enter number of records: 3
import csv Enter Employee id : 101
def ADD(): Enter name : Ram
f_add=open('record.csv','w',newline='') Enter mobile number : 9945
wr=csv.writer(f_add) Enter Employee id : 105
h=['EmpId','Name','Mobile'] Enter name : John
wr.writerow(h) Enter mobile number : 44585
n=int(input("Enter number of records: ")) Enter Employee id : 103
for i in range(n): Enter name : Rasheed
empid=int(input('Enter Employee id : ')) Enter mobile number : 44854
name=input('Enter name : ') Total number of records: 3
mobile=int(input('Enter mobile num: '))
E_data=[empid,name,mobile]
wr.writerow(E_data)
f_add.close()
def COUNTR():
with open('record.csv', 'r') as Fh:
data = csv.reader(Fh)
next(data) # skip header
d = list(data)
print("Total number of records:", len(d))
ADD()
COUNTR()
149
3. A csv file "p_record.csv" contains the records of patients in a hospital . Each record of the file contains the
following data :
Name of a patient –
Disease –
Number of days patient is admitted –
Amount –
For example, a sample record of the file may be : ["Gunjan", "Jaundice", 4,15000]
Write the following Python functions to perform the specified operations on this file :
(i) Write a function read_data() which reads all the data from the file and displays the details of all
the 'Cancer' patients.
(ii) (ii) Write a function count_rec() which counts and returns the number of records in the file.
#Program:
import csv
def read_data():
with open("p_record.csv", mode="r", newline='') as file:
reader = csv.reader(file)
print("Cancer Patients:")
headings=['Name','Disease','Days','Aount']
print(headings)
for i in reader:
if i[1].strip().lower() == "cancer":
print(i)
def count_rec():
with open("p_record.csv", mode="r", newline='') as file:
reader = csv.reader(file)
count = 0
for i in reader:
count+=1
return count
read_data()
Total_record=count_rec()
print(f"Total number of records:", Total_record)
Output:
Cancer Patients:
['Name', 'Disease', 'Days', 'Aount']
['Anil', 'Cancer', '5', '25000']
['Seema', 'Cancer', '2', '12000']
Total number of records: 5
150
4. Write a program to perform write operation onto a student.csv file having fields as roll number, name,
stream and percentage. Read the file, search the steam and percentage for given name.
Program:
import csv
def write_students():
students = []
while True:
roll_number = int(input("Enter roll number "))
name = input("Enter name: ")
stream = input("Enter stream: ")
percentage = float(input("Enter percentage: "))
data=[roll_number,name,stream,percentage]
students.append(data)
option=input('do you enter the data(yes or no)')
if option.lower()=='no':
break
with open('student.csv', 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(['roll_number', 'name', 'stream', 'percentage'])
writer.writerows(students)
print("Data written to successfully.")
def search_student():
print("\n=== Search for a Student ===")
name = input("Enter the name of the student to search for: ")
try:
with open('student.csv','r') as file:
reader = csv.reader(file)
header = next(reader) # Read the header
found = False
for row in reader:
if row[1].lower()==name.lower():
print('Stream:', row[2], 'Percentage:', row[3])
found = True
break
if not found:
print("Student named not found.")
except FileNotFoundError:
print("The file does not exist.")
except Exception as e:
print("An error occurred:", str(e))
write_students()
search_student()
151
5. Kiran is a Python programmer working in a shop. For the employee’s tax collection, he has created a csv
file named protax.csv, to store the details of professional tax paid by the employees.
The structure of protax.csv is : [empid, ename, designation, taxpaid]
Where,
empid is employee id (integer) ename is employee name (string) designation is employee
designation(string)
taxpaid is the amount of professional tax paid by the employee(string)
For efficiently maintaining data of the tax, Kiran wants to write the following user defined functions:
Collection() – to accept a record from the employee and add it to the file protax.csv.
Totaltax() – to calculate and return the total tax collected from all the employees.
import csv
def Collection():
n = int(input("How many employee records do you want to add? "))
L=[]
for i in range(n):
print(f"\nEnter details for Employee {i+1}:")
empid = int(input("Enter Employee ID: "))
ename = input("Enter Employee Name: ")
designation = input("Enter Designation: ")
taxpaid = input("Enter Tax Paid: ")
data=[empid, ename, designation, taxpaid]
L.append(data)
with open("protax.csv", "a", newline='') as file:
wtr = csv.writer(file)
wtr.writerows(L)
print(f"\n{n} record(s) added successfully!")
def Totaltax():
total = 0
with open("protax.csv","r", newline='') as file:
reader = csv.reader(file)
for i in reader:
total += float(i[3])
return total
Collection()
Total_Amount=Totaltax()
print("Total tax collected:",Total_Amount )
How many employee records do you want to add? 1
Enter details for Employee 1:
Enter Employee ID: 1001
Enter Employee Name: ram
Enter Designation: manager
Enter Tax Paid: 45000
1 record(s) added successfully!
Total tax collected: 95000.0
152
6. Vedansh is a Python programmer working in a school. For the Annual Sports Event, he has created a csv
file named Result.csv, to store the results of students in different sports events.
The structure of Result.csv is : [St_Id, St_Name, Game_Name, Result]
Where,
St_Id is Student ID (integer)
ST_name is Student Name (string)
Game_Name is name of game in which student is participating(string)
Result is result of the game whose value can be either 'Won', 'Lost' or 'Tie'
For efficiently maintaining data of the event, Vedansh wants to write the following user defined functions:
Accept() – to accept a record from the user and add it to the file Result.csv. The column headings should
also be added on top of the csv file.
wonCount() – to count the number of students who have won any event.
#Program
import csv
def Accept():
Data=[]
n = int(input("Enter number of records to add: "))
for i in range(n):
st_id = int(input("Enter Student ID: "))
st_name = input("Enter Student Name: ")
game_name = input("Enter Game Name: ")
result = input("Enter Result (Won/Lost/Tie): ")
Data.append([st_id, st_name, game_name, result])
def wonCount():
count = 0
with open('Result.csv', mode='r') as file:
reader = csv.reader(file)
next(reader)
for i in reader:
if i[3].lower() == 'won':
count += 1
if count == 0:
print("No student won any event.")
else:
print("Number of students who won any event:", count)
Accept()
wonCount()
153
7. A csv file "Happiness.csv" contains the data of a survey. Each record of the file contains the following
data:
● Name of a country
● Population of the country
● Sample Size (Number of persons who participated in the survey in that country)
● Happy (Number of persons who accepted that they were Happy)
For example, a sample record of the file may be: [‘Signiland’, 5673000, 5000, 3426]
Write the following Python functions to perform the specified operations on this file:
(I) Read all the data from the file in the form of a list and display all those records for which the
population is more than 5000000.
(II) Count the number of records in the file.
def display_large_population():
with open("Happiness.csv", "r") as file:
reader = csv.reader(file)
print("Countries with population > 5,000,000:")
for row in reader:
if int(row[1]) > 5000000:
print(row)
def count_records():
with open("Happiness.csv", "r") as file:
reader = csv.reader(file)
count=0
for i in reader:
count+=1
return count
display_large_population()
print("Total number of records:", count_records())
154
8. A CSV file "P_record.csv" contains records of patients in a hospital.
Each record in the file contains the following data:
• Name of a patient
• Disease
• Number of days patient is admitted
• Amount
For example, a sample record of the file may be:
["Gunjan", "Jaundice", "4", "15000"]
Write the following Python functions to perform the specified operations on this file:
(i) Write a function read_data() which reads all the data from the file and displays the details of all the
cancer patients.
(ii) Write a function count_rec() which counts and returns the number of records in the file.
import csv
def read_data():
with open("P_record.csv", "r") as file:
reader = csv.reader(file)
print("Cancer Patients:")
for row in reader:
if row[1].strip().lower() == "cancer":
print(f"Name: {row[0]}, Days: {row[2]}, Amount: {row[3]}")
def count_rec():
with open("P_record.csv", "r") as file:
reader = csv.reader(file)
count=0
for i in reader:
count+=1
return count
read_data()
no_record=count_rec()
print(f"No of Record: {no_record}")
155
12. Data structures
Data Structure:
▪ Data structure can be defined as a set of rules and operations to organize and store data in an efficient
manner.
▪ Data Structure is a way to organize multiple elements so that certain operations can be performed easily
on whole data as a single unit as well as individually on each element also.
▪ Data structures organize data in the system's memory (RAM) during program execution.
Topics to be covered
1. Stack
2. Operations on stack (push, pop, peek, display)
3.Implementation of stack using list
4.Applications of stack
Types:
156
Application of Stack:
1. Expression Evaluation
2. String Reversal
3. Function Call
4. Browser History
5. Undo/Redo Operations
6.Recursion
7.Backtracking (game playing, finding paths, exhaustive searching).
8. Memory management
Operations of Stack:
The Stack supports following operations:
1. Push: It adds an element to the TOP of the Stack.
2. Pop: It removes an element from the TOP of the Stack.
3. Peek: It is used to know/display the value of TOP without removing it.
4. isEmpty: It is used to check whether Stack is empty.
Overflow: It refers to the condition in which we try to PUSH an item in a Stack which is already FULL.
Underflow: It refers to the condition in which we are trying to POP an item from an empty Stack.
Implementation of Stack:
▪ In Python, List data structure is used to implement Stack.
▪ For PUSH operation we use append() method of List while for POP operation we use pop() method of List.
157
Write a Python program to implement a stack using list.
def stk_push():
n = int(input("Enter a No. : ")) 1.Push
stk.append(n) 2.Pop
3.display
def stk_pop(): 4.Exit
if len(stk) == 0: Enter choice: 1
print("Underflow") Enter a No. : 1011
else: 1.Push
print(stk.pop(), "removed") 2.Pop
3.display
def display(): 4.Exit
if stk == []: Enter choice: 1
print("Underflow") Enter a No. : 1022
else: 1.Push
print("stack is: ") 2.Pop
for i in range(-1, -len(stk)-1, -1): 3.display
print(stk[i]) 4.Exit
Enter choice: 3
stk = [] stack is:
while True: 1022
print("1.Push") 1011
print("2.Pop") 1.Push
print("3.display") 2.Pop
print("4.Exit") 3.display
ch = int(input("Enter choice: ")) 4.Exit
if ch == 1: Enter choice: 2
stk_push() 1022 removed
elif ch == 2: 1.Push
stk_pop() 2.Pop
elif ch == 3: 3.display
display() 4.Exit
elif ch == 4: Enter choice: 3
print("Exiting program.") stack is:
break 1011
else: 1.Push
print("Invalid, Enter a number 1 to 4.") 2.Pop
3.display
4.Exit
158
A Menu Driven Program to store Name and marks out of 100 for some students in a stack and
implementation of stack operations.
def stkpush():
na=input("Enter a Name. : ")
m=int(input("Enter Marks: ")) 1.Push
stk.append([na,m]) 2.Pop
def stkpop(): 3.display
if len(stk)==0: Enter choice: 1
print("Underflow") Enter a Name. : Ram
Enter Marks: 95
else:
1.Push
print(stk.pop()," removed")
2.Pop
def display(): 3.display
if stk==[ ]: Enter choice: 1
print("Underflow") Enter a Name. : Priya
else: Enter Marks: 97
print("stack is: ") 1.Push
2.Pop
for i in range(-1,-len(stk)-1,-1): 3.display
print(stk[i]) Enter choice: 3
stack is:
stk=[] ['Priya', 97]
char=True ['Ram', 95]
while(char): 1.Push
print("1.Push") 2.Pop
print("2.Pop") 3.display
Enter choice: 9
print("3.display")
its ended
ch=int(input("Enter choice: "))
if ch==1:
stkpush()
elif ch==2:
stkpop()
elif ch==3:
display()
else:
char=False
print("its ended")
159
Exercise:
1.Sanya wants to remove an element from empty stack. Which of the following term is related to this?
(a) Empty Stack
(b) Overflow
(c) Underflow
(d) Clear Stack
2.In Stack, all operations takes place at____________.
1. Top
2. Front
3. Rear
4. Any
3.Insertion and Deletion operations of Stack are known as ___________ respectively.
A. Insertion and Deletion
B. Push and Pop
C. Pop and Push
D. Enqueue and Dequeue
5.Which of the following is not an inherent application of Stack?
a) Reversing a String.
b) Evaluation of postfix expression.
c) Implementation of recursion.
d) Job Scheduling.
9.Data structures are:
a) Network structures.
b) Group of data
c) Different types of data
d) Different operations on data
ASSERTION & REASON:
(A): Both A and R are true and R is the correct explanation for A.
(B): Both A and R are true and R is not correct explanation for A.
(C): A is true but R is false.
(D): A is false but R is true.
10. ASSERTION (A): Using append(), many elements can be added at a time.
REASON(R): For adding more than one element, extend() method can be used.
13.ASSERTION (A): A Stack is a Linear Data Structure, that stores the elements in FIFO order.
REASON(R): New element is added at one end and element is removed from that end only.
14. ASSERTION (A): An error occurs when one tries to delete an element from an empty stack.
REASON(R): This situation is called an Inspection.
15. ASSERTION (A): A stack is a LIFO structure.
REASON (R): Any new element pushed into the stack always gets positioned at the index after the last
existing element in the stack.
160
Programs:
1. Write a function in Python POPSTACK (L) where L is a stack implemented by a list of numbers. The function returns
the value deleted from the stack.
A list contains following record of a customer:
[Customer_name, Phone_number, City]
Write the following user defined functions to perform given operations on the stack named ‘status’:
(i) Push_element() - To Push an object containing name and Phone number of customers who live in Goa to the
stack
(ii) Pop_element() - To Pop the objects from the stack and display them. Also, display “Stack Empty” when there are
no elements in the stack.
For example: If the lists of customer details are:
[“Gurdas”, “99999999999”,”Goa”]
[“Julee”, “8888888888”,”Mumbai”]
[“Murugan”,”77777777777”,”Cochin”]
[“Ashmit”, “1010101010”,”Goa”]
Stack Empty
customers =
[ ["Gurdas", "99999999999", "Goa"],
["Julee", "8888888888", "Mumbai"],
["Murugan", "77777777777", "Cochin"],
["Ashmit", "1010101010", "Goa"] ]
status = []
def Push_element():
for customer in customers:
if customer[2].lower() == "goa":
status.append([customer[0], customer[1]]) # Push [name, phone]
def Pop_element():
if status==[]:
print("Stack Empty")
else:
while status:
print(status.pop())
print("Stack Empty after pop operation")
Push_element()
print("Stack after pushing Goa customers:", status)
Pop_element()
161
2. Shalu has created a dictionary containing names and marks as key-value pairs of 6 students. Write a
program, with separate user-defined functions to perform the following operations:
1. Push the keys (name of the student) of the dictionary into a stack, where the corresponding value
(marks) is greater than 75.
2. Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
R={"OM":76, “JAI":45, “BOB":89, "ALI":65, "ANU"90, “TOM":50)
‘The output from the program should be:
TOM ANU BOB OM
R = {"OM": 76, "JAI": 45, "BOB": 89, "ALI": 65, "ANU": 90, "TOM": 50}
def PUSH(S, D):
for name in D:
if D[name] > 75:
S.append(name)
def POP(S):
if S==[]:
print('underflow')
else:
while S:
print(S.pop(), end=' ')
print('\n Stack is empty')
stack = []
PUSH(stack, R)
POP(stack)
3 . Anjeev has a message (string) that has an upper case alphabet in it. Write a program, with separate user-defined
functions to perform the following operations:
1. Push the upper case alphabets in the string into a stack.
2. Pop and display the content of the stack.
For example: If the message is “All the Best, for your Best Performance”
‘The output from the program should be: P B B A
String = "All the Best,for your Best Performance"
def PUSH(Stk,S):
for ch in S:
if ch.isupper():
Stk.append(ch)
def POP(Stk):
if Stk ==[]:
print('Stack Under flow')
else:
print('Fpllowing elements are deleted')
while Stk:
print(Stk.pop())
print('Stack is empty after deletion')
Stack=[]
PUSH(Stack,String)
print('Stack elements ara',Stack)
POP(Stack)
162
4. Ajay has a list containing integers. You need to help him create a program with separate user-defined functions to
perform the following operations based on this list.
1. Traverse the content of the list and push all positive numbers into a stack.
2. Pop and display the content of the stack.
For Example:
If the sample Content of the list is as follows:
N=[-2, 131-34, 56, 21, -379, 98, -22, 35, 38]
Sample Output of the code should be: 38 35 98 21 56 131
N = [-2, 131,-34, 56, 21, -379, 98, -22, 35, 38]
def Push_ele(S,N):
for i in N:
if i > 0:
Stk.append(i)
def Pop_ele(Stk):
if Stk==[]:
print('Stack is empty')
else:
while Stk:
print(Stk.pop())
print('After pop operation stack is empty')
Stk=[]
Push_ele(Stk,N)
Pop_ele(Stk)
163
5. Write the definition of a user defined function PushNV (N) which accepts a list of strings in the parameter N
and pushes all strings which have no vowels present in it, into a list named NoVowel.
• Write a program in Python to input 5 words and push them one by one into a list named All.
a. The program should then use the function PushNV () to create a stack of words in the list NoVowel so that it stores
only those words which do not have any vowel present in it, from the list All.
b. Thereafter, pop each word from the list NoVowel and display the popped word. When the stack is empty display
the message “EmptyStack”
For example: If the words accepted and pushed into the list All are
N=[‘DRY’, ‘LIKE’, “RHYTHM’, ‘WORK’, ‘GYM’]
Then the stack Novowel should store
[‘DRY’, ‘RHYTHM’, ‘GYM’]
And the output should be displayed as
GYM RHYTHM DRY EmptyStack
#All=['DRY', 'LIKE', 'RHYTHM', 'WORK', 'GYM']
def PushNV(N):
for word in N:
for char in word:
if char in 'AEIOUaeiou':
Vowel.append(word)
break
else:
NoVowel.append(word)
All = []
NoVowel = []
Vowel = []
for i in range(5):
word = input(f"Enter word {i+1}: ")
All.append(word)
PushNV(All)
print("All words:", All)
print("Words with no vowels (NoVowel Stack):", NoVowel)
print("Popped words:")
if NoVowel == []:
print('Underflow')
else:
while NoVowel:
print(NoVowel.pop(), end=" ")
print("\nEmptyStack")
164
6. You have a stack named BooksStack that contains records of books. Each book record is represented as
a list containing book_title, author_name, and publication_year. Write the following user-defined
functions in Python to perform the specified operations on the stack BooksStack: (CBSE S.QP 2024-25)
(I) push_book(BooksStack, new_book): This function takes the stack BooksStack and a new book
record new_book as arguments and pushes the new book record onto the stack.
(II) (II) pop_book(BooksStack): This function pops the topmost book record from the stack and
returns it. If the stack is already empty, the function should display "Underflow".
(III) peep(BookStack): This function displays the topmost element of the stack without deleting it.
If the stack is empty, the function should display 'None'.
BooksStack = []
push_book(BooksStack, ["Wings of Fire", "A.P.J. Abdul Kalam", 1999])
push_book(BooksStack, ["1984", "George Orwell", 1949])
push_book(BooksStack, ["The Alchemist", "Paulo Coelho", 1988])
Last_ele = peep(BooksStack)
print("Top book (peep):", Last_ele)
Del_ele = pop_book(BooksStack)
print("Popped book:", Del_ele)
165
7. Write the definition of a user-defined function `push_even(N)` which accepts a list of integers in a
parameter `N` and pushes all those integers which are even from the list `N` into a Stack named
`EvenNumbers`.
a. Write function pop_even() to pop the topmost number from the stack and returns it. If the stack is
already empty, the function should display "Empty".
b. Write function Disp_even() to display all element of the stack without deleting them. If the stack is
empty, the function should display 'None'.
For example: If the integers input into the list `VALUES` are: [10, 5, 8, 3, 12]
Then the stack `EvenNumbers` should store: [10, 8, 12]
def push_even(N):
for num in N:
if num % 2 == 0:
EvenNumbers.append(num)
def pop_even():
if EvenNumbers:
return EvenNumbers.pop()
else:
print("Empty")
return None
def Disp_even():
if EvenNumbers:
print("Stack elements:", EvenNumbers)
else:
print("None")
166
8. A stack, named ClrStack, contains records of some colors. Each record is represented as a tuple containing four
elements – ColorName, RED, GREEN, BLUE. (CBSE B.Q.P 2024-25)
ColorName is a string, and RED, GREEN, BLUE are integers.
For example, a record in the stack may be
('Yellow', 237, 250, 68)
Write the following user-defined functions in Python to perform the specified operations on ClrStack:
(i) push_Clr(ClrStack, new_Clr): This function takes the stack ClrStack and a new record new_Clr as arguments and
pushes this new record onto the stack.
(ii) pop_Clr(ClrStack): This function pops the topmost record from the stack and returns it. If the stack is already
empty, the function should display the message "Underflow".
(iii) isEmpty(ClrStack): This function checks whether the stack is empty. If the stack is empty, the function should
return True, otherwise the function should return False.
def push_Clr(ClrStack, new_Clr):
ClrStack.append(new_Clr)
def pop_Clr(ClrStack):
if ClrStack:
return ClrStack.pop()
else:
print("Underflow")
return None
def isEmpty(ClrStack):
if len(ClrStack) == 0:
return True
else:
return False
ClrStack = []
deleted=pop_Clr(ClrStack)
print("Popped record:", deleted)
Ept=isEmpty(ClrStack)
print("Is stack empty?",Ept)
167
9. Write the following user-defined functions in Python: (CBSE B.Q.P 2024-25)
(i) push_trail(N, myStack) :
Here N and myStack are lists, and myStack represents a stack.
The function should push the last 5 elements from the list N onto the stack myStack.
For example, if the list N is [1, 2, 3, 4, 5, 6, 7], then the function push_trail() should push the elements 3, 4, 5, 6, 7
onto the stack.
Therefore, the value of the stack will be [3, 4, 5, 6, 7].
Assume that N contains at least 5 elements.
(ii) pop_one(myStack) :
The function should pop an element from the stack myStack, and return this element.
If the stack is empty, then the function should display the message 'Stack Underflow', and return None.
(iii) display_all(myStack) :
The function should display all the elements of the stack myStack, without deleting them.
If the stack is empty, the function should display the message 'Empty Stack'.
def pop_one(myStack):
if myStack:
return myStack.pop()
else:
print("Stack Underflow")
return None
def display_all(myStack):
if myStack != []:
print("Stack elements :")
for item in range(-1,-len(myStack)-1,-1):
print(myStack[item])
else:
print("Empty Stack")
push_trail(N, myStack)
display_all(myStack) # Output: Stack elements: [3, 4, 5, 6, 7]
168