Model Paper 2017-2019 Answer Key
Model Paper 2017-2019 Answer Key
2 MARKS:
Algorithm:
Systematic logic approach which is a well defined step by step procedure that allows a computer to solve problem
Example:
Step 1 :start the program
Step 2: verify both values and numeric
Step 3: add both value and store the result into a new variable
Step 4: display the result
Step 4:end the program
Program :
It is exact code written for problem following all the rules of the programming language
Example:
A=int(input(“enter first number:”)
B=int(input(“enter second number:”)
Sum =A+B
Print(“sum:”,sum)
Algorithm:
Step1:declare a function that will find the smallest number
Step2:use min() method and store the value returned by it in a variable
Step3:Returned the variable
Step4:Declare and initialize a list or take input
Step5:Call the function and print the value returned by it
Python has a set of keywords that are reserved words that cannot be used as variable names,function names or any other
identifiers
Keyword Description
1.and
2.break A logical operator
3.def To break out of a loop
4.if To define a function
To make a conditional
statement
A function can be called multiple times to provide reusesability and modularity to the python program the function helps
to programmer to by save the program into the smaller part
N=10
Sum=0
I=1
While I<=n:
Sum=sum+i
I=i+1
Print(“the sum is:”,sum)
Recursion :
Recursion is the process of define something in terms of itself
Ex: def factorial(x):
If x==1:
Return 1
Else:
Return(x*factorial(x-1))
1.the similarity between lists and strings in python is that both are squences
2.the difference between them are that firstly
3.list are mutable but strings are immutable
4.secondly,elements of a list can be of different types where as string only contain characters that are all of string type
Example:
A=”this is a string ”
Print(A)
L=[1,”A”,”string”,1+2]
Print L
8.Give a function that can take a value and return the first key mapping to that value in a dictionary ?
Program:
Test_dict={‘gdh’:1,’is’:2,’best’:3}
Print(“the original dictionary is :”+str(test_dict))
Res=list(Test_dict.key())[0]
Print(“the first key of dictionary is:”+str(res))
Output:
The original dictionary is :{‘best’:3,’gdh’:1,’is’:2}
The first key of dictionary is:best
Priority analysis :This is a theoretical analysis of an algorithm .effieceny of an algorithm is measured by assuming that
all other factors ,ex:processor speed ,a constant have no effect on the implementation
Posterior analysis:this is an empirical analysis of an algorithm
Use of algorithm:algorithms are not language-specific ,they can be implemented in several programming languages no
standard rules guide the writing of algorithms
Use of pseudocode:efficient key principle of an algorithm
Use of flowchart:it is a diagrammatic representation of an algorithm.
13.Compare interpreter and compiler .what type of translator is used for python?
Compiler Interpreter
i)compiler scans the whole program in one go Translate program one statement at a time
ii)it converts the source code into object code It does not convert source code into object code
iii)it does not require source code for later execution It requires source code for later execution
program:
def sum of series(n):
sum=0
for i in range (1,n+1):
sum+=i*i*i
return sum
n=5
print(sum of series(n))
output:
225
Loop statement may have an else clause .it is executed when the for loop terminates through execution of the iterable but not
when the loop is terminated by break statement
For i in range(10):
Print(i,end,””)
Print()
Print(i,end,””)
You can update single on multiple elements of lists by giving the slice on the left handed side of the assignment
operator and you
can add to elements in a list with the append() method
ex: list=[‘physics’,’chemistry’,1997,2000]:
print(“value available at index 2 :”)
print list[2]
list[2]=2001:
print(“new value available at index 2:”)
print list[2]
Python functions can return multiple values.to return multiple values,you can return either a dictionary ,a python tuple of
a list to your main program
Ex :def person():
Return “bob”,32,”boston”
Print(person())
Output:
Result: (‘bob’,32,’boston’)
Import sys
Print(“number of arguments:”,len(sys.argv),’arguments.’)
Print(‘argument list:’,str(sys.argv))
The rename()method:
Import os
Os.rename(“text1.txt”,”text2.txt”)
The remove()method:
Import os
Os.remove(“text2.txt”)
21.Write an algorithm to aaccept two numbers,compute the sum and print the result
Algorithm:
Step1:start the program
Step2:read A,B
Step3:sum=A+B
Step4:print sum
Step5:stop the program
A tuple literal is an expression that defines a tuple by providing a list of expressions,separated by a comma and surrounded
by parentheses()
Example:
Var X: =(15,15,22):
Var y :=tuple of (doublr,double,double):=(1,1,5):
24.Write a python program to accept two numbers,multiply them and print the result?
Print(“sum of”,a,”and”,b,”is”,a+b)
Output:
Enter first number:4
Enter second number:6
Sum of 4 and 6 is 10
25.Write a python program to accept two numbers ,find the greatest and print the result?
4. Program:
5. Print(“enter two numbers:”)
6. num1=int(input())
7. num2=int(input())
8. If num1 >num2:
9. Print(“\n largest number”,num1)
10. Else:
11. Print(“\nl largest number ”,num2)
Output:
Enter two numbers:
30
40
Largest number:40
List is a container to contain different types of objects and is used to iterate objects
LIST TUPLE
Ex:tuples=(‘a’,’b’,’c’,d)
Modularity referes to the concept of making multiple modules first and then linking and combining them to form a
complete system.
Modularity enables reusability and will minimize duplication.
30.List the symbol used in drawing the flowchart?
terminator
Data input or
output
processing
decision
Predefined
process
Connector
Flowline
31. give the python code to find the minimum amo the list of 10 numbers.
List 1= [10,20,4,45,99]
List.sort[]
Output:
3.Outline the logic to swap the contents of two identifiers without using third variable.
X=5
Y=7
Print(“Before swapping:”)
Print(“Value of X:”,X,”and Y:”,Y)
X,Y = Y,X
Print(“After swapping:”)
Print(“Value of X:”,X,”and Y:”,Y)
Output:
Before swapping:
Values of X:5 and Y:7
After swapping:
Values of X:7 and Y:5
33.comment with an example on the use of local and global variable with the same identifier name.
When we print the variable inside too() it outputs global x:5, this is called the global scope of the variable.
Example:
X=5
Def too():
X=10
Print(“Local X:”,X)
Too()
Print(“global X:”,X)
Output:
Local X: 10
Global X: 5
34.how to create a list in python? Illustrative the use of negative indexing of list with example.
Test_list – [5,7,8,2,3,5,1]
K=3
Res=len(test_list) – test_list.index(K)
Output:
Import numpy as np
A=np.array([22,87,5,43,56,73,55,54,11,20,51,5,79,31,27])
Fig,ax=pit.subplots(figsize=(10,7))
Ax.hist(a,bins = [0,25,50,75,100])
Pit.show()
Output:
0
0 1 2 3 4 5
36.categorise the diiferent types of errors arises during programming. Interpret the following python
Code :
Import os
Cwd=os.getCwd()
print Cwd
answer:
import os
Cwd=os.getCwd()
OUTPUT:
TYPES:
Python command line argument are input parameters passed to the script when executing them.Almost all programming
language provide support for command line arguments.
“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the
inverse operation,
whereby a byte stream (from a binary file or bytes-like object) is converted back into an object hierarchy.
It is a way of combining function such that the result of each function is passed as the argument of the next function.
For example,
x is the arugment of g,the result of g is passed as the argument of f and the result of the composition is the result of f.
Example:
step1:start
step6:stop
Properities:
Input specified
output specified
definiteness
finiteness
effectiveness
ITERATION RECURSION
so long as certain
#numberlist Factorial(n):
Numbers=[6,5,3,8,4,2,5,4,11] If n==1:
Sum=0
Return 1
42.Define file.
Files used in computers are similar in features to that of paper documents used in library and office
files.
In a computer operating system,files can be stored on optical drives,hard drives or other types of storage devices.
def factorial(x):
if x==1:
return 1
else:
return(x*factorial(x-1))
print(factorial of(6))
Lambda functions are called anonymous because they are not declared in the standard manner by using the def keyword.
You can use the lambda keyword to create small anonymous functions.
An anonymous function cannot be a direct call to print because lambda requires an expreession.
ANS : GLOBAL VARIABLES CAN BE ACCESSED GLOBALLY IN THE ENTIRE PROGRAM, WHEREAS LOCAL VARIABLES CAN BE
ACCESSED ONLY WITHIN THE FUNCTION OR BLOCK IN WHICH THEY ARE DEFINED .
ANS : A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements
A slice object is used to specify how to slice a sequence. You can specify where to start the slicing ,and where to end . You can
also specify the step ,which allows you to e.g. slice only every other item.
SYNTAX:
Slice(start,end,step)
EXAMPLE:
nums=[1,2,3,4,5,6,7,8,9,10]
portion1=slice(9)
portion2=slice(2,8,2)
List value:[1,2,3,4,5,6,7,8,9]
List value:[3,5,7]
ANS: Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple
variable.
ARGUMENTS PARAMETERS
Arguments are used when a function is called Parameters are used when a function is to be defined
In argument value passed to a function when calling the Parameters is named entirely in a function definition that
function specifies an argument that functions can accept.
Arguments can be constant ,local variables or objects Parameters cannot be constant
There are keyword arguments and positional arguments Keyword parameters is positional parameters
1.Integers
Example:5433
2.Floats
Example:2.445
3.Booleans
4.Lists
Example:[1,6,8,4,3]
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existin
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name
print(newlist)
A dictionary is a collection which is ordered , changeable and does not allow duplicates.
EXAMPLE:
#dictionary with integer keys
Internal assessment - 02
PART-B
Algorithm
Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]
If x doesn’t match with any of elements in arr[] , return -1 or element not found.
Example
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))
Output
element found at index 6
Implementation of Binary search?
Program:
# Iterative Binary Search Function
# It returns index of x in given array arr if present,
# else returns -1
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Element is present at index 3
3) Different conditional statements involved in python with example each.
If statement..
Elif statement.
Nested if statement.
Nested if else statement.
IF statement;
Example
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif statement;
The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition".
Example:
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
Nested if statement;
You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
i = 20;
if (i < 15):
else:
Output:
i is greater than 15
1. default arguments
2. keyword arguments
3. positional arguments
variable-length arguments.
6. Example:
def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
'''
Output:
('numbers', 5)
('colors', 'blue')
('fruits', 'apple')
'''
Default arguments:
Default arguments are values that are provided while defining functions.
If we provide a value to the default arguments during function calls, it overrides the default value.
Example:
keyword arguments;
Functions can also be called using keyword arguments of the form kwarg=value.
During a function call, values passed through arguments need not be in the order of parameters in the function definition. This can
be achieved by keyword arguments. But all the keyword arguments should match the parameters in the function definition.
Example:
def add(a,b=5,c=10):
return (a+b+c)
positional arguments;
During a function call, values passed through arguments should be in the order of parameters in the function definition. This is
Example:
def add(a,b,c):
return (a+b+c)
1. During the function call, all arguments are given as positional arguments. Values passed through arguments are passed to
For arbitrary positional argument, a double asterisk (**) is placed before a parameter in a function which can hold keyword
variable-length arguments.
Example:
def fn(**a):
for i in a.items():
print (i)
fn(numbers=5,colors="blue",fruits="apple")
'''
Output:
('numbers', 5)
('colors', 'blue')
('fruits', 'apple')
'''
For arbitrary positional argument, an asterisk (*) is placed before a parameter in function definition which can hold non-keyword
variable-length arguments. These arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more
print (add(1,2,3,4,5))
#Output:15print (add(10,20))
#Output:30
5).Stringmanipulation(StringLength,StringConcatenation,StringCompare,StringReverse)
In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have a character
data type, a single character is simply a string with a length of 1. Square brackets [] can be used to access elements of the
string.
Example:
# strings
var1 = "Welcome"
var2 = "statistics"
print(var1)
print(var2)
Output
Welcome
Statistics
3. Using % operator
5. Using , (comma)
Using + Operator
It’s very easy to use + operator for string concatenation. This operator can be used to add multiple strings together. However,
the arguments must be a string.
Note: Strings are immutable, therefore, whenever it is concatenated, it is assigned to a new variable.
Example:
Python3
# string concatenation
# Defining strings
var2 = "World"
print(var3)
Output
Hello World
Here, the variable var1 stores the string “Hello ” and variable var2 stores the string “World”. The + Operator combines the
string that is stored in the var1 and var2 and stores in another variable var3.
Python3
var1 = "Hello"
var2 = "World"
print("".join([var1, var2]))
print(var3)
Output
HelloWorld
Hello World
In the above example, the variable var1 stores the string “Hello” and variable var2 stores the string “World”. The join() method
combines the string that is stored in the var1 and var2. The join method accepts only the list as it’s argument and list size can
be anything. We can store the combined string in another variable var3 which is separated by space.
Note: To know more about join() method click here.
Using % Operator
We can use % operator for string formatting, it can also be used for string concatenation. It’s useful when we want to
concatenate strings and perform simple formatting.
Example:
Python3
# string concatenation
var1 = "Hello"
var2 = "World"
# % Operator is used here to combine the string
Output
Hello World
Here, the % Operator combine the string that is stored in the var1 and var2. The %s denotes string data type. The value in both
the variable is passed to the string %s and becomes “Hello World”.
Python3
# string concatenation
var1 = "Hello"
var2 = "World"
print(var3)
Output
Hello World
Hello World
Here, the format() function combines the string that is stored in the var1 and var2 and stores in another variable var3. The curly
braces {} are used to set the position of strings. The first variable stores in the first curly braces and second variable stores in
the second curly braces. Finally it prints the value “Hello World”.
Using , (comma)
“,” is a great alternative to string concatenation using “+”. when you want to include a single whitespace.
Example:
# string concatenation
var1 = "Hello"
var2 = "World"
print(var1, var2)
Output
Hello World
Python
# len() method
# Length of below string is 5
string = "geeks"
print(len(string))
# with tuple
tup = (1,2,3)
print(len(tup))
# with list
l = [1,2,3,4]
print(len(l))
Output:
5
3
4
Python string comparison is performed using the characters in both strings. The characters in both strings are compared one by
one. When different characters are found then their Unicode value is compared. The character with lower Unicode value is
considered to be smaller.
fruit1 = 'Apple'
print(fruit1 == 'Apple')
print(fruit1 != 'Apple')
print(fruit1 < 'Apple')
print(fruit1 > 'Apple')
print(fruit1 <= 'Apple')
print(fruit1 >= 'Apple')
Output:
True
False
False
False
True
True
Both the strings are exactly the same, hence they are equal. So equality operator is returning True in this case.
Let’s look at another example where we will get inputs from the user and then compare them.
# using loop
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print (s)
print (reverse(s))
Output:
The original string is : Geeksforgeeks
The reversed string(using loops) is : skeegrofskeeG
Explanation :
In above code, we call a function to reverse a string, which iterates to every element and intelligently join each
character in the beginning so as to obtain the reversed string.
6).List aliasing&cloning
To provide a new name to this list, we can simply use assignment operator as:
y=x
In this case, we are having only one list of elements but with two different names 'x' and 'y'. Here, 'x' is the original name and 'y' is
the alias name for the same list. Hence, any modifications done to 'x' will also modify 'y' and vice versa. Observe the following
statements where an element x[1] is modified with a new value.
x = [10,20,30,40,50]
y = x #x is aliased as y
y = x[:] #x is cloned as y
Hence, if the programmer wants two independent lists, he should not go for aliasing. On the other hand, he should use cloning or
copying.
Obtaining exact copy of an existing object (or list) is called 'cloning'. To clone a list, we can take help of the slicing operation as:
When we clone a list like this, a separate copy of all the elements is stored into 'y'. The lists 'x' and 'y' are independent lists. Hence,
any modifications to 'x' will not affect 'y' and vice versa. Consider the following statements:
x = [10,20,30,40,50]
y = x[:] #x is cloned as y
We can observe that in cloning, modifications to a list are confined only to that list. The same can be achieved by copying the
elements of one list to another using copy() method. For example, consider the following statement:
y = x.copy() #x is copied as y
When we copy a list like this, a separate copy of all the elements is stored into 'y'. The lists 'x' and 'y' are independent. Hence, any
modifications to 'x' will not affect 'y' and vice versa.
Introduction
Tuples are basically a data type in python. These tuples are an ordered collection of elements of different data types. Furthermore, we
represent them by writing the elements inside the parenthesis separated by commas. We can also define tuples as lists that we cannot
change. Therefore, we can call them immutable tuples. Moreover, we access elements by using the index starting from zero. We can
create a tuple in various ways. Here, we will study tuple assignment which is a very useful feature in python.
Tuple Assignment
In python, we can perform tuple assignment which is a quite useful feature. We can initialise or create a tuple in various ways. Besides
tuple assignment is a special feature in python. We also call this feature unpacking of tuple.
The process of assigning values to a tuple is known as packing. While on the other hand, the unpacking or tuple assignment is the
process that assigns the values on the right-hand side to the left-hand side variables. In unpacking, we basically extract the values of the
tuple into a single variable.
Moreover, while performing tuple assignments we should keep in mind that the number of variables on the left-hand side and the
number of values on the right-hand side should be equal. Or in other words, the number of variables on the left-hand side and the
number of elements in the tuple should be equal. Let us look at a few examples of packing and unpacking.
We can create a tuple in various ways by using different types of elements. Since a tuple can contain all elements of the same data type
as well as of mixed data types as well. Therefore, we have multiple ways of creating tuples. Let us look at few examples of creating
tuples in python which we consider as packing.
>>>tup
>>>tup2
>>>tup3
>>>tup3
If there is only a single element in a tuple we should end it with a comma. Since writing, just the element inside the parenthesis will be
considered as an integer.
For example,
>>>tup=(90)
>>>tup
90
>>>type(tup)
<class 'int'>
Correct way of defining a tuple with single element is as follows:
>>>tup=(90,)
>>>tup
(90,)
>>>type(tup)
<class 'tuple'>
Moreover, if you write any sequence separated by commas, python considers it as a tuple.
For example,
>>>seq
(22, 4, 56)
>>>type(seq)
<class 'tuple'>
Functions can return tuples as return values. This is very useful — we often want to know some batsman’s highest and lowest
score, or we want to find the mean and the standard deviation, or we want to know the year, the month, and the day, or if we’re
doing some ecological modeling we may want to know the number of rabbits and the number of wolves on an island at a given
time. In each case, a function (which can only return a single value), can create a single tuple holding multiple elements.
For example, we could write a function that returns both the area and the circumference of a circle of radius r.
def circleInfo(r):
c = 2 * 3.14159 * r
a = 3.14159 * r * r
return (c, a)
print(circleInfo(10))
In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems.
Consider a python list, In-order to access a range of elements in a list, you need to slice a list. One way to do this is to use the
simple slicing operator i.e. colon(:)
With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list
from the existing list.
Syntax:
Lst[ Initial : End : IndexJump ]
If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.
Indexing
1. Positive Indexes
# Initialize list
# Display list
print(Lst[::])
Output:
[50, 70, 30, 20, 90, 10, 50]
2. Negative Indexes
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]
# Display list
print(Lst[-7::1])
Output:
[50, 70, 30, 20, 90, 10, 50]
3. Slicing
As mentioned earlier list slicing is a common practice in Python and can be used both with positive indexes as well as
negative indexes.
# Initialize list
# Display list
print(Lst[1:5])
Output:
[70, 30, 20, 90]
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
output:
[‘apple,’banana’,’mango’]
['apple', 'banana', 'mango']
,9.Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from
unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked
and moved to the sorted subarray.
Following example explains the above steps:
alist=[]
for i in range(1,num):
alist.append(temp)
print("Unsorted:",alist)
minvalue=min(alist[idx:])
alist.remove(minvalue)
alist.insert(idx,minvalue)
print("Inter:",alist)
print("sorted:",alist)
OUTPUT:
Example
def linearsearch(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
arr = ['t','u','t','o','r','i','a','l']
x = 'a'
print("element found at index "+str(linearsearch(arr,x)))
Output
element found at index 6
The Insertion sort is a straightforward and more efficient algorithm than the previous bubble sort algorithm. The
insertion sort algorithm concept is based on the deck of the card where we sort the playing card according to a particular
card. It has many advantages, but there are many efficient algorithms available in the data structure.
While the card-playing, we compare the hands of cards with each other. Most of the player likes to sort the card in the ascending
order so they can quickly see which combinations they have at their disposal.
The insertion sort implementation is easy and simple because it's generally taught in the beginning programming lesson. It is
an in-place and stable algorithm that is more beneficial for nearly-sorted or fewer elements.
The insertion sort algorithm is not so fast because of it uses nested loop for sort the elements.
The array spilled virtually in the two parts in the insertion sort - An unsorted part and sorted part.
The sorted part contains the first element of the array and other unsorted subpart contains the rest of the array. The first element in
the unsorted array is compared to the sorted array so that we can place it into a proper sub-array.
It focuses on inserting the elements by moving all elements if the right-side value is smaller than the left side.
It will repeatedly happen until the all element is inserted at correct place.
To sort the array using insertion sort below is the algorithm of insertion sort.
o If the current element is smaller than the next element, compare to the element before, Move to the greater elements one
position up to make space for the swapped element.
We will consider the first element in the sorted array in the following array.
[10, 4, 25, 1, 5]
[10, 4, 25, 1, 5]
Now we take the first element from the unsorted array - 4. We store this value in a new variable temp. Now, we can see that the
10>4 then we move the 10 to the right and that overwrite the 4 that was previously stored.
Here the 4 is lesser than all elements in sorted subarray, so we insert it at the first index position.
Now check the number 25. We have saved it into the temp variable. 25> 10 and also 25> 4 then we put it in the third position and
add it to the sorted sub array.
Again we check the number 1. We save it in temp. 1 is less than the 25. It overwrites the 25.
Now, we have 4 elements in the sorted subarray. 5<25 then shift 25 to the right side and pass temp = 5 to the left side.
[1, 4, 10, 25, 25] put temp = 5
Now, we get the sorted array by simply putting the temp value.
Python Program
Output:
Python provides inbuilt functions for creating, writing and reading files. There are two types of files that can be handled in
python, normal text files and binary files (written in binary language, 0s and 1s).
Text files: In this type of file, Each line of text is terminated with a special character called EOL (End of Line), which is
the new line character (‘\n’) in python by default.
Binary files: In this type of file, there is no terminator for a line and the data is stored after converting it into machine
understandable binary language.
In this article, we will be focusing on opening, closing, reading, and writing data in a text file.
File Access Modes
Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once its opened.
These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the
data has to be read or written in the file. There are 6 access modes in python.
1. Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning of the file. If the file does not
exists, raises I/O error. This is also the default mode in which file is opened.
2. Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises
I/O error if the file does not exists.
3. Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and over-written. The handle is
positioned at the beginning of the file. Creates the file if the file does not exists.
4. Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data is truncated and over-written. The
handle is positioned at the beginning of the file.
5. Append Only (‘a’) : Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of
the file. The data being written will be inserted at the end, after the existing data.
6. Append and Read (‘a+’) : Open the file for reading and writing. The file is created if it does not exist. The handle is
positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Opening a File
It is done using the open() function. No module is required to be imported for this function.
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full address of the file should be written on place of
filename.
Note: The r is placed before filename to prevent the characters in filename string to be treated as special character. For
example, if there is \temp in the file address, then \t is treated as the tab character and error is raised of invalid address. The r
makes the string raw, that is, it tells that the string is without any special characters. The r can be ignored if the file i s in same
directory and address is not being placed.
file1 = open("MyFile.txt","a")
file2 = open(r"D:\Text\MyFile2.txt","w+")
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used at the time when the file is no longer
needed or if it is to be opened in a different file mode.
File_object.close()
file1 = open("MyFile.txt","a")
file1.close()
Writing to a file
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the text file.Used to insert multiple strings at a single
time.
File_object.writelines(L) for L = [str1, str2, str3]
Writing a File
To write to an existing file, you must add a parameter to the open() function:
Example
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Program :
file1 = open("myfile.txt","w")
file1.write("Hello \n")
file1.writelines(L)
file1 = open("myfile.txt","r+")
print(file1.read())
print()
file1.seek(0)
print(file1.readline())
print()
file1.seek(0)
print(file1.read(9))
print()
file1.seek(0)
print(file1.readline(9))
file1.seek(0)
# readlines function
print()
file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
Hello
Hello
Th
Hello
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
12:Exceptions in Python
Python has many built-in exceptions that are raised when your program encounters an error (something in the program goes
wrong).
When these exceptions occur, the Python interpreter stops the current process and passes it to the calling process until it is
handled. If not handled, the program will crash.
For example, let us consider a program where we have a function A that calls function B, which in turn calls function C. If an
exception occurs in function C but is not handled in C, the exception passes to B and then to A.
If never handled, an error message is displayed and our program comes to a sudden unexpected halt.Python Exception Handling
Using try, except and finally statement
The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written
in the except clause.
We can thus choose what operations to perform once we have caught the exception. Here is a simple example.
Program:
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
Output
The entry is a
Oops! <class 'ValueError'> occurred.
Next entry.
The entry is 0
Oops! <class 'ZeroDivisionError'> occured.
Next entry.
The entry is 2
The reciprocal of 2 is 0.5
In this program, we loop through the values of the randomList list. As previously mentioned, the portion that can cause an
exception is placed inside the try block.
If no exception occurs, the except block is skipped and normal flow continues(for last value). But if any exception occurs, it is
caught by the except block (first and second values).
Here, we print the name of the exception using the exc_info() function inside sys module. We can see
that a causes ValueError and 0 causes ZeroDivisionError.
In python, you can also use the else clause on the try-except block which must be present after all the except clauses. The code
enters the else block only if the try clause does not raise an exception.
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Finally Keyword
Python provides a keyword finally, which is always executed after try and except blocks. The finally block always executes after
normal termination of try block or after try block terminates due to some exception.
Example: Let’s try to throw the exception in except block and Finally will execute either exception will generate or not
# working of try()
try:
# Part as Answer
result = x // y
except ZeroDivisionError:
else:
finally:
divide(3, 2)
divide(3, 0)
Output:
Question no : 13
You can count number of words in a text file in Python by following a sequence of steps
In this Python Example, we will read a text file and count the number of words in it. Consider the following text file.
Text File
Welcome to pythonexamples.org. Here, you will find python programs for all general use cases.
Python Program
Output
Number of words in text file : 14
You can count number of words in a text file, by first reading the text to a variable, and then counting the characters. We shall go through the
sequence of steps required to count the characters.
In this Python Example, we will read a text file and count the number of characters in it. Consider the following text file.
Text File
Welcome to www.pythonexamples.org. Here, you will find python programs for all general use cases.
Python Program
#open file in read mode
file = open("C:\data.txt", "r")
To open a file pass file path and access mode r to the open() function.
For example, fp= open(r'File_Path', 'r') to read a file.
2. Use for loop with enumerate() function to get a line and its number.
The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by
the open() function to the enumerate(). The enumerate() function adds a counter to each line.
We can use this enumerate object with a loop to access the line number. Return counter when the line ends.
We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file.
Example
Consider a file “read_demo.txt.” See an image to view the file’s content for reference.text file
# open file in read mode
with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
for count, line in enumerate(fp):
pass
print('Total Lines', count + 1)
Output:
Total Lines 8
1.What is an algorithm?
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the desired
output.
2.Write a pseudo-code to accept two numbers add the numbers and print the result.
BEGIN
READ num1
READ num2
Sum = num1+num2
WRITE Sum
END
The normal mode is the mode where the scripted and finished.py files are run in the python interpreter.
Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously
fed statements in active memory.
This operators are used to perform mathematical operations like addition ,subtraction, multiplication and division.
Example:
A=9
B=4
Add = A+B
Sub = A-B
Mul = A*B
Div = A/B
Comparision operators:
Comparision of relational operators compares the values. It either returns True of False according to the condition.
A =13
B = 33
print(A>B)
print(A<B)
print(A==B)
5.Write a Python program to accept two numbers, find the greatest and print the result.
Program:
Num1=int(input(“Enter Number1:”)
if Num1>Num2:
else:
Output:
Enter Number1: 30
Enter Number2:40
Largest Number:40
6.What is Recursion?
Recursive functions are functions that calls itself. It is always made up of two portions, the base case and the recursive case. The
base case is the condition to stop the recursion. The recursive case is the part where the function calls on itself.
List:
Lists are used to store multiple items in a single variable enclosed within square brackets.
Example:
Alist = [“apple”,”mango”,”orange”]
print(Alist)
Using extend():
Llist1 = [1,”a”]
List2 = [1,2,3]
List2.extend(List1)
print(List2)
Output:
[1,2,3,1,’a’]
An exception can be string, a class or an object. It can be defined as an unusual condition in a program resulting in the
interuption in the flow of the program.
Example:
Marks = 10000
A = Marks/0
Print(A)
10.Write the syntax for opening a file in python for reading only.
Part-B
11.A) Explain with an example the bolding blocks of an
Alogorithim?
An Algorithm is a step by step process that describes how to solve a problem in a way that always gives a correct
answer. When there are multiple algorithms for a particular problem (and there often are!), the best algorithm is typically
As computer programmers, we are constantly using algorithms, whether it's an existing algorithm for a common problem,
like sorting an array, or if it's a completely new algorithm unique to our program. By understanding algorithms, we can
make better decisions about which existing algorithms to use and learn how to make new algorithms that are correct and
efficient.
An algorithm is made up of three basic building blocks: sequencing, selection, and iteration.
Sequencing: An algorithm is a step-by-step process, and the order of those steps are crucial to ensuring the correctness of
an algorithm.
Here's an algorithm for translating a word into Pig Latin, like from "pig" to "ig-pay":
1. Append "-".
3. Append "ay"
Try following those steps in different orders and see what comes out. Not the same, is it?
Selection: Algorithms can use selection to determine a different set of steps to execute based on a Boolean expression.
Here's an improved algorithm for Pig Latin that handles words that starts with vowels, so that "eggs" becomes "eggs-yay"
1. Append "-"
a. Append "yay"
4. Otherwise:
b. Append "ay"
c. Remove first letter
Iteration: Algorithms often use repetition to execute steps a certain number of times or until a certain condition is met.
We can add iteration to the previous algorithm to translate a complete phrase, so that "peanut butter and jelly" becomes
a. Append hyphen
c. Append "yay"
d.Otherwise:
a. Append "ay"
By combining sequencing, selection, and iteration, we've successfully come up with an algorithm for Pig Latin translation.
11.b) Draw a flow chart to print the first “n” prime numbers?
11.b) explain with revelant diagram and algorithim the Tower of hanoi problem
ALGORITHM:
Step 1 : Start the program.
Step 2 : Move Disc1 from source to destination
Step 3 : Move Disc2 from source to acceleration
Step 4 : Move Disc1 from destination to acceleration
Step 5 : Move Disc3 from source to destination
Step 6 : Move Disc1 from acceleration to source
Step 7 : Move Disc2 from acceleration to destination
Step 8 : Move Disc1 from source to destination
Step 9 : Stop the program
12 a)
i. Explain with an example the structure of python program.
In General Python Program Consists of so many text files, which contains python statements. Program is designed as single main,
high file with one or more supplement files.
In python high level file has Important path of control of your Program the file, you can start your application. The library tools
are also know as Module files. These tools are implemented for making collection of top-level files. High level files use tools
which are defined in Module files. And module files will Implement files which are Defined in other Modules. Coming to our
point in python a file takes a module to get access to the tools it defines. And the tools made by a module type. The final thing is
we take Modules and access attributes to their tools. In like manner this shows Programming structure of Python
The structure Python Program consists of three files such as : a.py,b.py and c.py. The file model a.py is chosen for high level file .
it is known as a simple text file of statements. And it can be executed from bottom to top when it is launched. Files b.py and c.py
are modules. They are calculated as better text files of statements as well. But they are generally not started Directly. Identically
this attributes define Programming structure of Python.
Modules :
If we take this as a part , python serves as biggest company structure. Modules are having top end of code. By coding components
in module files.used in any program files.If we take an example function b.spam is regular purpose tool. We can again implement
that in a different program. This is simply known as b.py from any other program files.
Python has large collection of modules known as standard library.it contains 200 modules at last count. It is platform independent
common programming works. Such as GUI Design, Internet and network scripting. Text design matching, Operating system
Interfaces. So, Comparatively all the Above will explain Programming structure of Python.
# This program adds two numbers
num1 = 1.5
num2 = 6.3
12. a).
Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic,
logical, bitwise computations. The value the operator operates on is known as Operand.
Here, we will cover Assignment Operators in Python. So, Assignment Operators are used to assigning values to variables.
Assign: This operator is used to assign the value of the right side of the expression to the left side operand.
Syntax:
x= y+z
Add and Assign: This operator is used to add the right side operand with the left side operand and then assigning the result to
the left operand.
Syntax:
x += y
Subtract and Assign: This operator is used to subtract the right operand from the left operand and then assigning the result to
the left operand.
Syntax:
x -= y
Multiply and Assign: This operator is used to multiply the right operand with the left operand and then assigning the result to
the left operand.
Syntax:
x *= y
Divide and Assign: This operator is used to divide the left operand with the right operand and then assigning the result to the
left operand.
Syntax:
x /= y
Modulus and Assign: This operator is used to take the modulus using the left and the right operands and then assigning the
result to the left operand.
Syntax:
x %= y
Exponent and Assign: This operator is used to calculate the exponent(raise power) value using operands and then assigning
the result to the left operand.
Syntax:
x **= y
Divide (floor) and Assign: This operator is used to divide the left operand with the right operand and then assigning the
result(floor) to the left operand.
Syntax:
x //= y
Bitwise AND and Assign: This operator is used to perform Bitwise AND on both operands and then assigning the result to the
left operand.
Syntax:
x &= y
Data types are an essential concept in the python programming language. In Python, every value has its own python data
type. The classification of data items or to put the data value into some sort of data category is called Data Types. It helps to
understand what kind of operations can be performed on a value.
In the Python Programming Language, everything is an object.
Data types in Python represents the classes. The objects or instances of these classes are called variables. Let us now discuss the
different kinds of data types in Python.
3. Python Tuple
A Tuple is a sequence of items that are in order, and it is not possible to modify the Tuples. The main difference list and tuples are
that tuple is immutable, which means it cannot be altered. Tuples are generally faster than the list data type in Python because it
cannot be changed or modified like list datatype. The primary use of Tuples is to write-protect data. Tuples can be represented by
using parentheses (), and commas are used to separate the items.
Tuples can look like this:
>>> t = (6,’tuple’,4+2r)
In the case of a tuple, one can use the slicing operator to extract the item, but it will not allow changing the value. Data Frames in
Python
Python Set
The Collection of Unique items that are not in order is called Set. Braces {} are used to defined set and a comma is used to
separate values. One will find that the items are unordered in a set data type.
Duplicates are eliminated in a set and set only keeps unique values. Operations like intersection and union can be performed on
two sets.
Python set will look like this:
>>> a = {4,5,5,6,6,6}
>>> a
{4, 5, 6}
The slicing operator does not work on set because the set is not a collection of ordered items, and that is why there is no meaning
to the indexing of set.
Boolean Type
There can be only two types of value in the Boolean data type of Python, and that is True or False.
It can look like this:
>>> type(True)
<class ‘bool’>
>>> type(False)
<class ‘bool’>
The true value in the Boolean context is called “truthy”, and for false value in the Boolean context, it is called “falsy”. Truthy is
defined by the objects in boolean, which is equal to True, and in the same way, Falsy is defined by the objects equal to falsy. One
can also evaluate Non-Boolean objects in a Boolean context.
13.(a)i)Python Program using While loop to print the frist n numbers divisible by 5
Program:
def factorial(num):
if num==1:
return num
else:
return num*factorial(num-1)
num=int(input(“Enter the number:”))
print(f“Factorial of’{num}’is”,factorial(num))
Output:
Enter the number:4
Factorial of ‘4’ is 24
Program:
# Iterative Binary Search Function
# It returns index of x in given array arr if present,
# else returns -1
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Element is present at index 3
there are various ways in which we can access the elements of a tuple,they are,
1.Indexing
2.Negative Indexing
1.Indexing:
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[0])
print(my_tuple[5])
Output:
'p'
't'
2.Negative Indexing:
my_tuple = ('p','e','r','m','i','t')
print(my_tuple[-1])
print(my_tuple[-6])
Output:
't'
'p'
Unlike lists,tuples are immutable.However two tuples can be added and it can be sliced. apparently, a list in a tuple can
be modified too.
tup2=('abc','xyz')
tup3=tup1+tup2
print(tup3)
Output:
(912,13.46,'abc','xyz')
SLICING:
my_tuple = ('p','r','o','g','r','a','m')
print(my_tuple[1:4])
Output:
('r','o','g')
LIST IN A TUPLE:
my_tuple = (4,2,3,[6,5])
my_tuple[3][0] = 9
print(my_tuple)
Output:
(4,2,3,[9,5])
my_tuple = (12,34,'test',45,22,33,19)
n=2
print(my_tuple)
Output:
(12,34,45,22,33,19)
(b) Write a python program to sort an integer list using selection sort.
alist=[]
for i in range(1,num):
alist.append(temp)
print("Unsorted:",alist)
minvalue=min(alist[idx:])
alist.remove(minvalue)
alist.insert(idx,minvalue)
print("Inter:",alist)
print("sorted:",alist)
OUTPUT:
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from
unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
15. a) Describe in detail how exceptions are handled in python? with example.
An exception can be defined as an unusual condition in a program resulting in the interruption in the flow of the program.
Whenever an exception occurs, the program stops the execution, and thus the further code is not executed. Therefore, an exception
is the run-time errors that are unable to handle to Python script. An exception is a Python object that represents an error
If the Python program contains suspicious code that may throw the exception, we must place that code in the try block.
The try block must be followed with the except statement, which contains a block of code that will executed if there is some
exception in the try block.
Example :
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")
Output:
Enter a:10
Enter b:0
Can’t divide with zero
1. try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using Exception with except statement. If we print(Exception) it will return exception class
except Exception:
print("can't divide by zero")
print(Exception)
1. else: try:
2. a = int(input("Enter a:"))
3. b = int(input("Enter b:"))
4. c = a/b
5. print("a/b = %d"%c)
6. # Using Exception with except statement. If we print(Exception) it will return exception class
7. except Exception:
8. print("can't divide by zero")
9. print(Exception)
10. else:
11. print("Hi I am else block")
Output:
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
Output:
Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>
15. b)write a python program to copy the content from one file to another file.
PROGRAM
of1=open('file1.txt','r')
of2=open('file2.txt','w+')
content=of1.read()
of2.write(content)
of1.close()
of2.close()
import shutil
shutil.copyfile('file2.txt','file3.txt')
PART B
11)a)i)Draw a flowchart to accept three distinct numbers,find the greatest and print the result.
Input : a = 4, b = 2, c = 6
Output : c is the largest numb
11)ii)Draw a flowchart to find the sum of the series1+2+3+4+5+………+100.
11. b) Outline the tower of hanoi problem suggest the solution to the tower of Hanoi problem with relevent diagram.
Numeric Literals:
Integers:
In Python, integers are zero, positive or negative whole numbers without a fractional part and having
unlimited precision,
Eg:
>>>type(100)
<class 'int'> # type of x is int
Floating:
In Python, floating point numbers (float) are positive and negative real numbers with a fractional part denoted by
the decimal symbol . or the scientific notation E or e.
Eg:
>>> f=1.2
>>> f
1.2
>>> type(f)
<class 'float'>
Complex:
A complex number is a number with real and imaginary components.
Eg:
>>> a=5+2j
>>> type(a)
<class 'complex'>
Arithmetic operator are used to performing mathematical operations like addition,subtraction, multiplication ,and division
There are 7 arithmetic operators in python:
Addition(+)
Subraction(-)
Multiplication(*)
Division(/)
Modulus(%)
Exponentiation(**)
FLOOR DIVISION(//)
1. Addition Operator : In Python, + is the addition operator. It is used to add 2 values.
Example :
val1 = 2
val2 = 3
print(res)
Output :
5
2. Subtraction Operator : In Python, – is the subtraction operator. It is used to subtract the second value from the first value.
Example :
val1 = 2
val2 = 3
print(res)
Output :
-1
3. Multiplication Operator : In Python, * is the multiplication operator. It is used to find the product of 2 values.
Example :
val1 = 2
val2 = 3
print(res)
Output :
6
4. Division Operator : In Python, / is the division operator. It is used to find the quotient when first operand is divided by the
second.
Example :
val1 = 3
val2 = 2
print(res)
Output :
1.5
5. Modulus Operator : In Python, % is the modulus operator. It is used to find the remainder when first operand is divided by
the second.
Example :
val1 = 3
val2 = 2
print(res)
Output :
1
6. Exponentiation Operator : In Python, ** is the exponentiation operator. It is used to raise the first operand to power of
second.
Example :
val1 = 2
val2 = 3
print(res)
Output :
8
7. Floor division : In Python, // is used to conduct the floor division. It is used to find the floorof the quotient when first
operand is divided by the second.
Example :
val1 = 3
val2 = 2
print(res)
Output : 1
Operator precedence: This is used in an expression with more than one operator with different precedence to dretermine which
operation to perfrom first.
Operator Associativity :if an expression contains two or more operator with the same precedence then operator associativity is
used to determine.
It can either be left to right or from right to left.
** Exponent Right-to-left
* Multiplication Left-to-right
/ Division
% modulus
+ Addition Left-to-right
- Subtraction
a = 20
b = 10
c = 15
d=5
e=0
e = (a + b) * c / d #( 30 * 15 ) / 5
print "Value of (a + b) * c / d is ", e
e = ((a + b) * c) / d # (30 * 15 ) / 5
print "Value of ((a + b) * c) / d is ", e
output:
Value of (a + b) * c / d is 90
Value of ((a + b) * c) / d is 90
12)b)ii)Write a python program to exchange the values of two variables.
x=5
y = 10
Output
The value of x after swapping: 10
The value of y after swapping: 5
12)b)iii)Write a python program using function to find the sum of first ‘n’ even numbers and print the result.
PROGRAM:
def even_num():
total=0
if (number%2==0):
print(number)
total=total+number
even_num()
OUTPUT:
10
Nested if statement:
There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you
can use the nested if construct.
In a nested if construct, you can have an if...elif...else construct inside another if...elif...else construct.
Syntax
Example
#!/usr/bin/python
var = 100
if var < 200:
print "Expression value is less than 200"
if var == 150:
print "Which is 150"
elif var == 100:
print "Which is 100"
elif var == 50:
print "Which is 50"
elif var < 50:
print "Expression value is less than 50"
else:
print "Could not find true expression"
output:
Expression value is less than 200
Which is 100
Good bye!
Elif ststement:
the elif condition is used to include multiple conditional expressions after the if condition or between the if and else
conditions. The elif block is executed if the specified condition evaluates to True . In the above example, the elif conditions are
applied after the if condition
Syntax:
if test expression:
Body of if
Body of elif
else:
Body of else
Example:
Num=3.4
If num>=”
Print(“positive number”)
Elif num==0:
Print(“zero”)
Else:
Print(“negative number”)
Output:
Positive number
2) Explain with an example while loop, break statement and continue statement in python
While loop
• The body of the loop is entered only if the testexpression evaluates to True. After one iteration, the test expression is
checked again. This process continues until the test_expression evaluates to False.
• Body starts with indentation and the first unintended line marks the end.
• Python interprets any non-zero value as True. None and 0 are interpreted as False.
Example:
i=1
while i<6:
print(i)
i+=1
Output:
Break statement:
• Control of the program is transferred to the statement which is present immediately after
• If break statement is inside a nested loop (loop inside another loop), break will
syntax:
break
Example:
If val ==”I””
Break
Print(val
Print(“the end”)
Output:
The end
continue Statement
• The continue statement is used to skip the rest of the code inside a loop for the current
iteration only.
• Loop does not terminate but continues on with the next iteration.
Syntax:
Continue
Example:
If val ==”I”:
Continue
Print(val)
Print(“The end”)
Output:
The end
13 b)Write the python program to find the factorial of the given number without recursion and with recursion.
With Recursion:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 7
if num < 0:
if num == 0:
else:
Without recursion:
fact=1
if n<0:
else:
for i in range(1,n+1):
fact=fact*i
13.b 2) Write a python program to find first ‘n’ Fibonacci numbers. Note:The Fibonacci numbers are
0,1,1,2,3,5,8,13,21,34,…… where each number is the sum of the preceding two.
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
elif nterms == 1:
print(n1)
else:
print("Fibonacci sequence:")
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
and values
be immutable.
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Clear():
Removes all the elements from the dictionary
Syntax
dictionary.clear()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.clear()
print(car)
Output: {}
Copy():
Syntax:
dictionary.copy()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.copy()
print(x)
Output:
Fromkeys():
The fromkeys() method returns a dictionary with the specified keys and the specified value
Syntax:
dict.fromkeys(keys, value)
Example:
y=0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Output:
['key1': 0, 'key2': 0, 'key3': 0]
Get():
The get() method returns the value of the item with the specified key
Syntax:
dictionary.get(keyname, value)
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.get("model")
print(x)
Output:
Mustang
Items():
The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.
The view object will reflect any changes done to the dictionary, see example below.
Syntax:
dictionary.items()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = car.items()
print(x)
Output:
Keys():
The keys() method returns a view object. The view object contains the keys of the dictionary, as a list.
The view object will reflect any changes done to the dictionary, see example below.
Syntax:
dictionary.keys()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.keys()
print(x)
Output:
pop():
The pop() method removes the specified item from the dictionary.
The value of the removed item is the return value of the pop() method, see example below.
Syntax:
dictionary.pop(keyname, defaultvalue)
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.pop("model")
print(car)
Output:
{'brand': 'Ford', 'year': 1964}
popitem():
The popitem() method removes the item that was last inserted into the dictionary. In versions before 3.7, the popitem() method
removes a random item.
The removed item is the return value of the popitem() method, as a tuple.
Syntax:
dictionary.popitem()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.popitem()
print(car)
Output:
setdefault():
The setdefault() method returns the value of the item with the specified key.
If the key does not exist, insert the key, with the specified value.
Syntax:
dictionary.setdefault(keyname, value)
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
Output:
Mustang
update():
The specified items can be a dictionary, or an iterable object with key value pairs.
Syntax:
dictionary.update(iterable)
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Output:
The values() method returns a view object. The view object contains the values of the dictionary, as a list.
The view object will reflect any changes done to the dictionary.
Syntax:
dictionary.values()
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x)
Output:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
for x in thisdict:
print(x)
Output:
brand
model
year
Python Code:
found = False
for i in num_list:
if search == i:
found = True
print("Element found")
break
if not found:
# Main Program
num_list = []
num_list.append(item)
linearsearch(num_list, search)
Output:
(ii).Write a python program to store ‘n’ numbers in a list and sort the list using selection sort.
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from
unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked
and moved to the sorted subarray.
Python code:
# Selection Sort
import random
alist=[random.randint(9,99) for i in range (9)]
print("Unsorted: ",alist)
for idx in range(len(alist)):
minvalue=min(alist[idx:])
alist.remove(minvalue)
alist.insert(idx,minvalue)
print("Inter: ",alist)
print("sorted: ",alist)
Output:
Unsorted: [58, 62, 14, 42, 74, 71, 60, 47, 70]
Inter: [14, 58, 62, 42, 74, 71, 60, 47, 70]
Inter: [14, 42, 58, 62, 74, 71, 60, 47, 70]
Inter: [14, 42, 47, 58, 62, 74, 71, 60, 70]
Inter: [14, 42, 47, 58, 62, 74, 71, 60, 70]
Inter: [14, 42, 47, 58, 60, 62, 74, 71, 70]
Inter: [14, 42, 47, 58, 60, 62, 74, 71, 70]
Inter: [14, 42, 47, 58, 60, 62, 70, 74, 71]
Inter: [14, 42, 47, 58, 60, 62, 70, 71, 74]
Inter: [14, 42, 47, 58, 60, 62, 70, 71, 74]
sorted: [14, 42, 47, 58, 60, 62, 70, 71, 74]
15.A) Tabulate the different modes for opening a file and explain the same.
A file is some information or data which is stored (save) in the computer storage devices. Python provides basic functions and
methods necessary to manipulate files by default. You can do most of the file manipulation using a file object. Python language
supports two types of files. First one is text file that store data in the form of text file and readable by human and computer.
Second one is binary file that store binary data and readable by computer only. Python has a built-in function open() to open a
file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
The access_mode is an optional string that specifies the mode in which the file is opened. By default, it is set to read-only "r". In
this mode, we get data in text form after reading from the file. On the other hand, binary mode returns bytes. It's preferable for
accessing the non-text files like an image or the exe files.
Different modes of opening a file are
w - Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be
created
b - binary mode
A text file can be opened in any one of the above said modes by specifying the option "t" along with "r", "w", "rw", and "a", so
that the preceding modes become "rt", "wt", "rwt", and "at". A binary file can be opened in any one of the above said modes by
specifying the option "b" along with "r", "w", "rw", and "a" so that the preceding modes become "rb", "wb", "rwb", "ab".
15.b) i) Appraise the use of try block and except block in python with syntax.
A try and except block is used for error handling in Python.
• Try: Helps to test the code. If the code inside the try block is error free it is executed. Otherwise the error gets caught
and control goes to the except block.
• Except: Except displays the error message.
Type of error messages
There are two types of error that can occur:
• Syntax Error/Parsing Error: When the Python parser is unable to understand a line of code.
• Exception: When the error is detected during execution, e.g.,ZeroDivisionError.
List of exception errors
The following are the list of exception error that arises:
• IOError: When a file can’t be opened
• KeyboardInterrupt: When an unrequired key is pressed by the user
• ValueError :When a built-in function receives a wrong argument
• EOFError :When one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without
reading any data
• ImportError: When a module is not found
As contents of an Argument can vary depending upon different types of Exceptions in Python, Variables can be supplied
to the Exceptions to capture the essence of the encountered errors. Same error can occur of different causes, Arguments
helps us identify the specific cause for an error using the except clause.
It can also be used to trap multiple exceptions, by using a variable to follow the tuple of Exceptions.
Example 1:
try:
b = float(100 + 50 / 0)
Output:
This is the Argument
division by zero
Example 1:
class MyError(Exception):
# Constructor or Initializer
self.value = value
def __str__(self):
return(repr(self.value))
try:
Output:
This is the Argument
'Some Error Data'
PROBLEM SOLVING AND PYTHON PROGRAMING (ND 2019)
PART-B
11.a)i)what is programming language?what are its types?explain them in detail with their Advantages and disadvantages.
programming language is a formal language that specifies a set of instructions that can be used to produce various kinds
of output.
• Programming languages can be used to create programs that implement specific algorithms.
PROGRAMMING LANGUAGE
1. Machine language
2. Assembly language
Machine language:
• The computer can understand only machine language which uses 0’s and 1’s.
• In machine language the different instructions are formed by taking different combinations of 0’s and 1’s.
Arithmetic, Logical, Data transfer, and Branches (also called flow control), as follows:
• Logical: and, or, srl (shift right logical), ssl (shift left logical)
• Data Transfer: lw (load word), sw (store word), lui (load upper immediate)
• Branches:
• Conditional: beq (branch on equal), bne (branch on not-equal), slt (set on less-than),
Advantages:
Disadvantages:
Assembly language:
• An assembly language is a low-level programming language designed for a specific type of processor.
• It may be produced by compiling source code from a high-level programming language (such as C/C++) but can also be written
from scratch.
Advantages:-
Disadvantages:-
it is long and tedious to write initially.
it is quite bug-prone.
your bugs can be very difficult to chase.
your code can be fairly difficult to understand and modify, i.e. to maintain.
the result is non-portable to other architectures, existing or upcoming
• The specified rules are to be followed while writing program in high level language.
• The interpreter or compilers are used for converting these programs in to machine readable form.
Advantages:-
ii)Fibonacci sequence:
# Program to display the Fibonacci sequence up to n-th term
2. To solve such problems which are naturally recursive such as tower of Hanoi.
Disadvantages of recursion
2. It may require a lot of memory space to hold intermediate results on the system stacks.
5. The computer may run out of memory if the recursive calls are not properly check.
Compare it with iterative function:
A program is called recursive when an entity calls itself. A program is call iterative when there is a loop (or repetition).
# Python3 program to find factorial of given number
# ----- Recursion -----
# method to find factorial of given number
def factorialUsingRecursion(n):
if (n == 0):
return 1;
# recursion call
return n * factorialUsingRecursion(n - 1);
# ----- Iteration -----
# Method to find the factorial of a given number
def factorialUsingIteration(n):
res = 1;
# using iteration
res *= i;
return res;
# Driver method
num = 5;
factorialUsingRecursion(5));
factorialUsingIteration(5));
Output:
12a)i)python program to rotate a list by right n times with and without slicing techniques.
output_list = []
for item in range(len(my_list) - num, len(my_list)):
output_list.append(my_list[item])
output_list.append(my_list[item])
return output_list
# Driver Code
A=list()
for i in range(int(n)):
p=int(input("n="))
A.append(int(p))
print (A)
python54.py
Output
n= 11
[11]
n= 22
[11, 22]
n= 33
n= 44
n= 55
n= 66
A=list()
for i in range(int(ni)):
p=int(input("ni="))
A.append(int(p))
print (A)
n=3
print("After Rotation",A)
Output
ni= 11
[11]
ni= 22
[11, 22]
ni= 33
ni= 44
ni= 55
ni= 66
keyword argument:
Keyword arguments (or named arguments) are values that, when passed into a function, are identifiable by specific parameter
names. A keyword argument is preceded by a parameter and the assignment operator, = .
Keyword arguments can be likened to dictionaries in that they map a value to a keyword.
1234
Default argument:-
Default arguments in Python functions are those arguments that take default values if no explicit values are passed to these
arguments from the function call. Let's define a function with one default argument.
def find_square(integer1=2):
return result
b)i)python program print the maximum among ‘n’ randomly generate ‘d’ numbers by storing them in a list.
import random
*mylist = []
for i in range(0,100):
x = random.randint(1,10)
mylist.append(x)
print(mylist)
ii)float(4+int(2.39)%2)=
iii)2**2**3=64
ARRAY LISTS
An array is a collection of elements Linked List is an ordered collection
of a similar data type. of elements of the same type in
which each element is connected to
the next using pointers.
Random accessing is not possible in
Array elements can be accessed
linked lists. The elements will have
randomly using the array index.
to be accessed sequentially.
New elements can be stored
anywhere and a reference is created
Data elements are stored in for the new element using pointers.
contiguous locations in memory. Insertion and Deletion operations are
fast and e
# anagram or not
if(sorted(s1)== sorted(s2)):
else:
# driver code
s1 ="listen"
s2 ="silent"
check(s1, s2)
Output
14a)i)Dictionary in python:
Dictionaries are Python's implementation of a data structure that is more generally known as an associative array. A dictionary
consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value
# Using fromkeys()
# Initialize keys
# Using fromkeys()
# printing result
ii)compare two dictrionarties nwith master keys list and print missing keys
Compare keys
if key match
compare values
break
else:
"Naples"
Illinois
Chicago
Naperville
"Missing key and value/s on Second_Dict"
Arizona
Phoenix
Tucson
break
else:
print(value)
# initializing dictionary
res = list(test_dict.keys())[0]
intersect = []
if item in another_dict.keys( ):
intersect.append(item)
return(dict2.update(dict1))
# Driver code
print(Merge(dict1, dict2))
print(dict2)
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name.
Without list comprehension you will have to write a for statement with a conditional test inside:
Example
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with
different qualities and usage.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
They are both heterogeneous data types means that you can store any kind of data type
They are both ordered means the order in which you put the items are kept.
They are both sequential data types so you can iterate over the items contained.
Items of both types can be accessed by an integer index operator, provided in square brackets, [index]
left = alist[start:mid]
right = alist[mid:end]
k = start
i=0
j=0
alist[k] = left[i]
i=i+1
else:
alist[k] = right[j]
j=j+1
k=k+1
i=i+1
k=k+1
else:
alist[k] = right[j]
j=j+1
k=k+1
merge_sort(alist, 0, len(alist))
print(alist)
while loop:
It continually executes the statements(code) as long as the given condition is TRUE. It first checks the condition and then
jumps into the instructions.
Syntax:
while condition:
statements(code)
Inside the while loop, we can have any number of statements. The condition may be anything as per our requirement.
The loop stops running when the condition fails (become false), and the execution will move to the next line of code. It
first checks the condition, executes the conditional code if the condition is TRUE, and checks the condition again.
Program control exits the loop if the condition is FALSE.
for loop:
A for loop is used to iterate over a sequence like lists, type, dictionaries, sets, or even strings. Loop statements will be
executed for each item of the sequence
statements(code)
Takes the first item of the iterable, executes the statement, and moves the pointer to the next item until it reaches the last
item of the sequence.
Nested loops:
Nested loops mean using a loop inside another loop. We can use any type of loop inside any type of loop. We can use a
while loop inside for loop, a for loop inside a while loop, a while loop inside a while loop, or a for loop inside a for loop.
Break:
The break statement terminates the loop containing it. Control of the program flows to the statement immediately after
the body of the loop.
Exmaple:
if val == "i":
break
print(val)
print("The end")
Continue:
The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not
terminate but continues on with the next iteration.
Example:
if val == "i":
continue
print(val)
print("The end")
ALGORITHM
Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in a certain order to get the
desired output.
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and their inputs/outputs
should be clear and must lead to only one meaning.
Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.
Step1: Start
Step5: Stop
12.a) Describe about the concept of Precedence and Associativity of Operators with example.
The combination of values, variables, operators, and function calls is termed as an expression. The Python interpreter can evaluate
a valid expression.
For example:
>>> 5 - 7
-2
To evaluate these types of expressions there is a rule of precedence in Python. It guides the order in which these operations are
carried out.
But we can change this order using parentheses () as it has higher precedence than multiplication.
The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence
Operators Meaning
() Parentheses
** Exponent
+, - Addition, Subtraction
^ Bitwise XOR
| Bitwise OR
==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators
Or Logical OR
Suppose we're constructing an if...else block which runs if when lunch is either fruit or sandwich and only if money is more
than or equal to 2.
money = 0
Output
Ad
This program runs if block even when money is 0. It does not give us the desired output since the precedence of and is higher
than or.
We can get the desired output by using parenthesis () in the following way:
money = 0
Output
We can see in the above table that more than one operator exists in the same group. These operators have the same precedence.
When two operators have the same precedence, associativity helps to determine the order of operations.
Associativity is the order in which an expression is evaluated that has multiple operators of the same precedence. Almost all the
For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the
# Left-right associativity
# Output: 3
print(5 * 2 // 3)
Output
3
0
We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.
2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.
global = 1
Output
a@ = 0
Output
ii) what are statements .how are they constructed from variable and expressions in python
A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far
are 2 (the result when we added 1 + 1), and 'Hello, World!'.
These values belong to different types: 2 is an integer, and 'Hello, World!' is a string, so-called because it contains a "string" of
letters. You (and the interpreter) can identify strings because they are enclosed in quotation marks.
The print statement also works for integers.
>>> print 4
4
If you are not sure what type a value has, the interpreter can tell you.
Not surprisingly, strings belong to the type str and integers belong to the type int. Less obviously, numbers with a decimal point
belong to a type called float, because these numbers are represented in a format called floating-point.
>>> type(3.2)
<type 'float'>
What about values like '17' and '3.2'? They look like numbers, but they are in quotation marks like strings.
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
They're strings.
When you type a large integer, you might be tempted to use commas between groups of three digits, as in 1,000,000. This is not a
legal integer in Python, but it is a legal expression:
Well, that's not what we expected at all! Python interprets 1,000,000 as a comma-separated list of three integers, which it prints
consecutively. This is the first example we have seen of a semantic error: the code runs without producing an error message, but it
doesn't do the "right" thing.
2.2 Variables
One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that
refers to a value.
The assignment statement creates new variables and gives them values:
This example makes three assignments. The first assigns the string "What's up, Doc?" to a new variable named message. The
second gives the integer 17 to n, and the third gives the floating-point number 3.14159 to pi.
Notice that the first statement uses double quotes to enclose the string. In general, single and double quotes do the same thing, but
if the string contains a single quote (or an apostrophe, which is the same character), you have to use double quotes to enclose it.
A common way to represent variables on paper is to write the name with an arrow pointing to the variable's value. This kind of
figure is called a state diagram because it shows what state each of the variables is in (think of it as the variable's state of mind).
This diagram shows the result of the assignment statements:
In each case the result is the value of the variable. Variables also have types; again, we can ask the interpreter what they are.
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
Programmers generally choose names for their variables that are meaningful they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter. Although
it is legal to use uppercase letters, by convention we don't. If you do, remember that case matters. Bruce and bruce are different
variables.
The underscore character (_) can appear in a name. It is often used in names with multiple words, such
as my_name or price_of_tea_in_china.
76trombones is illegal because it does not begin with a letter. more$ is illegal because it contains an illegal character, the dollar
sign. But what's wrong with class?
It turns out that class is one of the Python keywords. Keywords define the language's rules and structure, and they cannot be used
as variable names.
You might want to keep this list handy. If the interpreter complains about one of your variable names and you don't know why,
see if it is on this list.
2.4 Statements
A statement is an instruction that the Python interpreter can execute. We have seen two kinds of statements: print and assignment.
When you type a statement on the command line, Python executes it and displays the result, if there is one. The result of a print
statement is a value. Assignment statements don't produce a result.
A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the
statements execute.
For example, the script
print 1
x=2
print x
1
2
An expression is a combination of values, variables, and operators. If you type an expression on the command line, the
interpreter evaluates it and displays the result:
>>> 1 + 1
2
Although expressions contain values, variables, and operators, not every expression contains all of these elements. A value all by
itself is considered an expression, and so is a variable.
>>> 17
17
>>> x
2
Confusingly, evaluating an expression is not quite the same thing as printing a value.
When the Python interpreter displays the value of an expression, it uses the same format you would use to enter a value. In the
case of strings, that means that it includes the quotation marks. But if you use a print statement, Python displays the contents of
the string without the quotation marks.
In a script, an expression all by itself is a legal statement, but it doesn't do anything. The script
17
3.2
'Hello, World!'
1+1
produces no output at all. How would you change the script to display the values of these four expressions?
Operators are special symbols that represent computations like addition and multiplication. The values the operator uses are
called operands.
The following are all legal Python expressions whose meaning is more or less clear:
The symbols +, -, and /, and the use of parenthesis for grouping, mean in Python what they mean in mathematics. The asterisk (*)
is the symbol for multiplication, and ** is the symbol for exponentiation.
When a variable name appears in the place of an operand, it is replaced with its value before the operation is performed.
Addition, subtraction, multiplication, and exponentiation all do what you expect, but you might be surprised by division. The
following operation has an unexpected result:
>>> minute = 59
>>> minute/60
0
The value of minute is 59, and in conventional arithmetic 59 divided by 60 is 0.98333, not 0. The reason for the discrepancy is
that Python is performing integer division.
When both of the operands are integers, the result must also be an integer, and by convention, integer division always
rounds down, even in cases like this where the next integer is very close.
>>> minute*100/60
98
Again the result is rounded down, but at least now the answer is approximately correct. Another alternative is to use floating-point
division, which we get to in Chapter 3.
When more than one operator appears in an expression, the order of evaluation depends on the rules of precedence. Python
follows the same precedence rules for its mathematical operators that mathematics does. The acronym PEMDAS is a useful way
to remember the order of operations:
Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since
expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make
an expression easier to read, as in (minute * 100) / 60, even though it doesn't change the result.
Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27.
Multiplication and Division have the same precedence, which is higher than Addition and Subtraction, which also have
the same precedence. So 2*3-1 yields 5 rather than 4, and 2/3-1 is -1, not 1 (remember that in integer division, 2/3=0).
Operators with the same precedence are evaluated from left to right. So in the expression minute*100/60, the
multiplication happens first, yielding 5900/60, which in turn yields 98. If the operations had been evaluated from right to
left, the result would have been 59*1, which is 59, which is wrong.
In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. The following are illegal
(assuming that message has type string):
Interestingly, the + operator does work with strings, although it does not do exactly what you might expect. For strings,
the + operator represents concatenation, which means joining the two operands by linking them end-to-end. For example:
fruit = 'banana'
bakedGood = ' nut bread'
print fruit + bakedGood
The output of this program is banana nut bread. The space before the word nut is part of the string, and is necessary to produce the
space between the concatenated strings.
The * operator also works on strings; it performs repetition. For example, 'Fun'*3 is 'FunFunFun'. One of the operands has to be a
string; the other has to be an integer.
On one hand, this interpretation of + and * makes sense by analogy with addition and multiplication. Just as 4*3 is equivalent
to 4+4+4, we expect 'Fun'*3 to be the same as 'Fun'+'Fun'+'Fun', and it is. On the other hand, there is a significant way in which
string concatenation and repetition are different from integer addition and multiplication. Can you think of a property that addition
and multiplication have that string concatenation and repetition do not?
2.9 Composition
So far, we have looked at the elements of a program variables, expressions, and statements in isolation, without talking about
how to combine them.
One of the most useful features of programming languages is their ability to take small building blocks and compose them. For
example, we know how to add numbers and we know how to print; it turns out we can do both at the same time:
>>> print 17 + 3
20
In reality, the addition has to happen before the printing, so the actions aren't actually happening at the same time. The point is
that any expression involving numbers, strings, and variables can be used inside a print statement. You've already seen an
example of this:
You can also put arbitrary expressions on the right-hand side of an assignment statement:
This ability may not seem impressive now, but you will see other examples where composition makes it possible to express
complex computations neatly and concisely.
Warning: There are limits on where you can use certain expressions. For example, the left-hand side of an assignment statement
has to be a variable name, not an expression. So, the following is illegal: minute+1 = hour.
2.10 Comments
As programs get bigger and more complicated, they get more difficult to read. Formal languages are dense, and it is often difficult
to look at a piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing. These
notes are called comments, and they are marked with the # symbol:
In this case, the comment appears on a line by itself. You can also put comments at the end of a line:
Everything from the # to the end of the line is ignored it has no effect on the program. The message is intended for the
programmer or for future programmers who might use this code. In this case, it reminds the reader about the ever-surprising
behavior of integer division.
This sort of comment is less necessary if you use the integer division operation, //. It has the same effect as the division operator *
Note, but it signals that the effect is deliberate.
The integer division operator is like a comment that says, "I know this is integer division, and I like it that way!"
2.11 Glossary
value
A number or string (or other thing to be named later) that can be stored in a variable or computed in an expression.
type
A set of values. The type of a value determines how it can be used in expressions. So far, the types you have seen are
integers (type int), floating-point numbers (type float), and strings (type string).
floating-point
A format for representing numbers with fractional parts.
variable
A name that refers to a value.
statement
A section of code that represents a command or action. So far, the statements you have seen are assignments and print
statements.
assignment
A statement that assigns a value to a variable.
state diagram
A graphical representation of a set of variables and the values to which they refer.
keyword
A reserved word that is used by the compiler to parse a program; you cannot use keywords like if, def, and while as
variable names.
operator
A special symbol that represents a simple computation like addition, multiplication, or string concatenation.
operand
One of the values on which an operator operates.
expression
A combination of variables, operators, and values that represents a single result value.
evaluate
To simplify an expression by performing the operations in order to yield a single value.
integer division
An operation that divides one integer by another and yields an integer. Integer division yields only the whole number of
times that the numerator is divisible by the denominator and discards any remainder.
rules of precedence
The set of rules governing the order in which expressions involving multiple operators and operands are evaluated.
concatenate
To join two operands end-to-end.
composition
The ability to combine simple expressions and statements into compound statements and expressions in order to
represent complex computations concisely.
comment
Information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on
the execution of the program.
13.a.i)analyse string slicing .illustrate how it is done with example
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end. Python
slicing can be done in two ways (i.e.) slice() Constructor and Extending Indexing.
slice() Constructor:
The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step).
Exmaple:
String ='ASTRING'
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Output:
String slicing
AST
SR
GITA
Extending indexing:
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way to slice a
string both syntax wise and execution wise.
Syntax: string[start:end:step]
Example:
String ='ASTRING'
print(String[:3])
print(String[1:5:2])
print(String[-1:-12:-2])
Output:
AST
SR
GITA
A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function.
A function can return data as a result.
Creating a Function:
In Python a function is defined using the def keyword.
Example:
def my_function():
print("Hello from a function")
Calling a Function:
To call a function, use the function name followed by parenthesis:
Example:
def my_function():
print("Hello from a function")
my_function()
Arguments:
Information can be passed into functions as arguments. Arguments are specified after the function name, inside the
parentheses. When the function is called, we pass along a first name, which is used inside the function to print the full
name:
Example:
def my_function(fname):
print(fname + " Refsnes")
my_function("Emil")
my_function("Tobias")
my_function("Linus")
14.i)demonstrate with code the various operations that can be performed on tuples
Tuples in Python
Tuples are a lot like lists, and that's why we can define them in a pretty similar way as we did to define the lists. Simply put, a
tuple is a sequence of data.
What makes them different from lists is that tuples are immutable, i.e., the data inside the tuples can't be modified, which is
opposite in the case of lists.
Defining a Tuple
To define a tuple, we just have to assign a single variable with multiple values separated by commas, and that variable will be
known as a Tuple.
>>> myTuple = 1, 2, 3, 4
Output:
Output:
(1, 2, 3, 4)
You can see in the above example, that myTuple variable is actually a collection of integers 1, 2, 3 and 4. Also, note
those circular brackets which appears while printing, around the integers, these will actually help you to distinguish between lists
and tuples. Because in case of lists, we have square brackets around the list elements.
Output:
(1, 2, "python", 4)
An empty tuple can be created using the tuple() function or by just using an empty bracket ().
Output:
The above statements will create tuples with no elements in it. And the compiler would know
that emptyTuple and anotherTuple are tuples, with no elements in them.
Indexing in Tuples
Indexing in tuples is also pretty similar to that in lists, the first element has index zero, and it keeps on increasing for the next
consecutive elements. Also, backward indexing is also valid in tuples, i.e., the last element can be accessed using the index -
1 and the consecutive previous numbers by -2, -3 and so on. Let's take an example,
Output:
'apple'
In the table below we have marked the tuple elements for both forward and backward indexing:
apple 0 -5
orange 1 -4
banana 2 -3
berry 3 -2
mango 4 -1
Adding Elements to a Tuple
As we know, that tuples are immutable, hence the data stored in a tuple cannot be edited, but it's definitely possible to add more
data to a tuple. This can be done using the addition operator. Suppose there is a tuple,
>>> t = (1, 2, 3, 4, 5)
Output:
In case you want to add another element, 7 to the tuple, then you can do it as follows:
>>> t = t + (7,)
Output:
As you can see, we used the addition operator to add(7,) to the tuple t.
Output:
(1, 2, 3, 4, 5, 7)
Hence, we can add any kind of element to a tuple, using the + operator.
If we try to think, what else can we do with the + operator, we might realize that it can be used to combine two tuples as well. For
example:
Output:
(1, 2, 5, 8, 2, 9, 4)
Deleting a Tuple
In order to delete a tuple, the del keyword is used. In order to delete a tuple named myTuple(which we defined earlier), follow the
example below:
Output:
Slicing in Tuples
Slicing in tuples, works exactly the same like in the case of lists. Let's start with an example:
>>> t = (1, 2, 3, 4)
>>> print(t[2:4])
Output:
(3, 4)
Here, t[2:4] means, slice the tuple starting from index 2 upto the index 4, and take that slice out.
Slicing can be done backwards as well using the negative indexes for traversing the tuple from backward direction.
The various operations that we can perform on tuples are very similar to lists. In fact, you just saw the + operator with tuples, it
works with tuples just like it works with a list. Some other operators for tuples include:
Multiplication
Multiplying a tuple by any integer, x will simply create another tuple with all the elements from the first tuple being
repeated x number of times. For example, t*3 means, elements of tuple t will be repeated 3 times.
>>> t = (2, 5)
Output:
(2, 5, 2, 5, 2, 5)
Addition
Using the addition operator, with two or more tuples, adds up all the elements into a new tuple. For example,
Output:
(2, 5, 0, 1, 3, 4)
in keyword
in keyword, can not only be used with tuples, but also with strings and lists too. It is used to check, if any element is present in the
sequence or not. It returns True if the element is found, otherwise False. For example,
>>> t = (1, 2, 3, 6, 7, 8)
>>> 2 in t
>>> 5 in t
Output:
True
False
len() function
As you might have already guessed, this function is used to get the number of elements inside any tuple.
>>> t = 1, 2, 3
Output:
cmp() function
This is used to compare two tuples. It will return either 1, 0 or -1, depending upon whether the two tuples being compared are
similar or not.
The cmp() function takes two tuples as arguments, where both of them are compared. If T1 is the first tuple and T2 is the second
tuple, then:
To find the maximum value in a tuple, we can use the max() function, while for finding the minimum value, min() function can be
used.
>>> t = (1, 4, 2, 7, 3, 9)
Output:
14.ii)write a algorithm and program for sorting the numbers in ascending order using merge sort
Algorithm:
n1 = m - l + 1
n2 = r - m
L = [0] * (n1)
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
L[i] = arr[l + i]
R[j] = arr[m + 1 + j]
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# are any
arr[k] = L[i]
i += 1
k += 1
# are any
arr[k] = R[j]
j += 1
k += 1
if l < r:
# large l and h
m = l+(r-l)//2
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
n = len(arr)
for i in range(n):
mergeSort(arr, 0, n-1)
for i in range(n):
15.a.explain about the file reading and writing operations using format operator with python code
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling
options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is
either complicated or lengthy, but like other concepts of Python, this concept here is also easy and short. Python treats file
differently as text or binary and this is important. Each line of code includes a sequence of characters and they form text file. Each
line of a file is terminated with a special character, called the EOL or End of Line characters like comma {,} or newline character.
It ends the current line and tells the interpreter a new one has begun. Let’s start with Reading and Writing files.
Before performing any operation on the file like read or write, first we have to open that file. For this, we should use Python’s
inbuilt function open()
But at the time of opening, we have to specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data then it will be overridden.
3. a: open an existing file for append operation. It won’t override existing data.
4. r+: To read and write data into the file. The previous data in the file will not be deleted.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won’t override existing data.
Take a look at the below example:
Python3
print (each)
The open command will open the file in the read mode and the for loop will print each line present in the file.
There is more than one way to read a file in Python. If you need to extract a string that contains all characters in the file then we
can use file.read(). The full code would work like this:
Python3
print (file.read())
Another way to read a file is to call a certain number of characters like in the following code the interpreter will read the first five
characters of stored data and return it as a string:
Python3
print (file.read(5))
Python3
file = open('geek.txt','w')
file.close()
The close() command terminates all the resources in use and frees the system of this particular program.
Python3
file = open('geek.txt','a')
file.close()
There are also various other commands in file handling that is used to handle various tasks like:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are working with code. That explains why it’s
good practice to use them with a statement where applicable. This is helpful because using this method any files opened will be
closed automatically after one is done, so auto-cleanup.
Example:
Python3
We can also use the write function along with the with() function:
Python3
f.write("Hello World!!!")
We can also split lines using file handling in Python. This splits the variable when space is encountered. You can also split using
any characters as we wish. Here is the code:
Python3
data = file.readlines()
word = line.split()
print (word)
Error in Python can be of two types i.e. Syntax errors and Exceptions. Errors are the problems in a program
due to which the program will stop the execution. On the other hand, exceptions are raised when some
internal events occur which changes the normal flow of the program.
Example:
Python3
amount = 10000
Output:
Exceptions: Exceptions are raised when the program is syntactically correct, but the code resulted in an
error. This error does not stop the execution of the program, however, it changes the normal flow of the
program.
Example:
Python3
marks = 10000
a = marks / 0
print(a)
Output:
In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.
Try and except statements are used to catch and handle exceptions in Python. Statements that can raise
exceptions are kept inside the try clause and the statements that handle the exception are written inside except
clause.
Example: Let us try to access the array element whose index is out of bound and handle the corresponding
exception.
Python3
#Python 3
a = [1, 2, 3]
try:
except:
Output
Second element = 2
An error occurred
In the above example, the statements that can cause the error are placed inside the try statement (second print
statement in our case). The second print statement tries to access the fourth element of the list which is not
there and this throws an exception. This exception is then caught by the except statement.
Catching Specific Exception
A try statement can have more than one except clause, to specify handlers for different exceptions. Please
note that at most one handler will be executed. For example, we can add IndexError in the above code. The
general syntax for adding specific exceptions are –
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
Python3
# except statement
# Python 3
def fun(a):
if a < 4:
b = a/(a-3)
print("Value of b = ",
try:
fun(3)
fun(5)
# multiple exceptions
except ZeroDivisionError:
except NameError:
Output
The output above is so because as soon as python tries to access the value of b, NameError occurs.
In python, you can also use the else clause on the try-except block which must be present after all the except
clauses. The code enters the else block only if the try clause does not raise an exception.
Python3
# Python 3
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
else:
print (c)
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)
Output:
-5.0
a/b result in 0
Python provides a keyword finally, which is always executed after the try and except blocks. The final block
always executes after normal termination of try block or after try block terminates due to some exception.
Syntax:
try:
# Some Code....
except:
# optional block
else:
# execute if no exception
finally:
Example:
Python3
try:
print(k)
finally:
Output:
Can't divide by zero
Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The sole argument in raise
indicates the exception to be raised. This must be either an exception instance or an exception class (a class
that derives from Exception).
Python3
try:
except NameError:
The output of the above code will simply line printed as “An exception” but a Runtime error will also occur
in the last due to the raise statement in the last line. So, the output on your command line will look like
NameError: Hi there
(ii). Design a python code to count the number of words in a python file
# creating variable to store the
# number of words
number_of_words = 0
data = file.read()
lines = data.split()
# variable
number_of_words += len(lines)
print(number_of_words)
Output:
Explanation:
Creating a new variable to store the total number of words in the text file. And then open the text file in read-only mode
using the open() function.
Read the content of the file using the read() function and storing them in a new variable. And then split the data stored in
the data variable into separate lines using the split() function and then storing them in a new variable. And add the length
of the lines in our number_of_words variable.
16 MARK
11. b)
• Iteration
• Recursion
Iteration:
called iterations.
• for loop
• while loop
ITERATION
for loop:
• The for-loop sets up a control variable that manages execution of the loop.
• Execution iterates over the items in a sequence (the value of each item is
assigned to the control variable at the beginning of each pass through the
loop).
• In the following code sample, the variable word is used as a control variable.
• At the beginning of each iteration of the loop, it is assigned the next value
...
ENDFOR
Iteration:
‘garnishes’]
print(len(word))
# Prints: 2 3 4 5 6 7 8 9
• for loop:
example 2:
print(number * 42)
• for loop:
example 3:
BEGIN
GET n
INITIALIZE i=1
FOR (i<=n) DO
PRINT i
i=i+1
ENDFOR
END
While loop:
iteration.
• As soon as the condition evaluates to false, the loop ends and execution
jumps immediately to the next line following the end of the while block.
While loop:
WHILE (condition) DO
Statement
ENDWHIL
While loop:
example 1:
• #This program invites the user to guess a number (set in the# age variable). As long as they haven’t guessed correctly, the
program keeps asking.
age = 25
guess = 0
# Whereas a == b tests whether a and b are equal, a != b tests whether a and b are not equal
# The int() function turns the user’s input (which is text) into an integer.
11.b)
STEP1:Start
STEP4:Compare the current element with all elements in the sorted list.
STEP5:If the element in the sorted list is smaller than the current element, iterate to the next element. Otherwise, shift all the
greater element in the list by one position towards the right.
STEP8:Stop
12.a.(i) sketch the structure of interpreter and compiler . detail the difference between them.
Explain how python works in interactive mode and script mode with examples
*Python interpreter and interactive mode, debugging; values and types: int, float, boolean, string , and list; variables,
expressions, statements, tuple assignment, precedence of operators, comments; Illustrative programs: exchange the values of
two variables, circulate the values of n variables, distance between two points.
COMPILER:
• A compiler is a program that translates source code into object code to be understood by a specific central processing
unit (CPU).
INTERPRETER:
An Interpreter directly executes instructions written in a programming or scripting language without previously converting them
to an object code or machine code
INTERPRETER
Compiler vs Interpreter
PYTHON INTERPRETER:
* Python is considered an interpreted language because Python programs are executed by an interpreter.
i) interactive mode
* The interpreter prints a welcome message stating its version number and a copyright notice before printing
the first prompt:
*For continuation lines it prompts with the secondary prompt, by default three dots (…)
*We can execute the script of code either using the command prompt or using Python IDE installed in our system
PYTHON SCRIPT MODE
PYTHON
SCRIPT MODE VS INTERACTIVE MODE:
13 a)Python string are immutable or not.
The standard wisdom is that Python strings are immutable. You can't change a string's value, only the reference to the string.
Like so:
x = "hello"
Which implies that each time you make a change to a string variable, you are actually producing a brand new string. Because of
this, tutorials out there warn you to avoid string concatenation inside a loop and advise using join instead for performance reasons.
Even the official documentation says so!
There is a common case for when strings in Python are actually mutable. I will show you an example by inspecting the string
object's unique ID using the builtin id() function, which is just the memory address. The number is different for each object.
(Objects can be shared though, such as with interning.)
I concatenated two strings but the memory address did not change!
For an extra sanity check, let's make our own "pointer" and see if it points to the original or modified string.
If strings were truly immutable, then the address we stored in b would point to the original string. However, we see that the strings
printed are equivalent.
We can try another test to see how often we get a new string object by doing 10,000 small concatenations.
14.a)
Here are the methods which one can refer to for traversing lists in Python:
List Comprehension
Lambda function
Output:
2
4
6
8
10
If you wish to use the traditional for loop which iterates from number x to number y.
Output:
2
4
6
8
10
It is essential to remember that it is not recommended to iterate by making use of the index if one can iterate over the elements (like
how it is done in the first method).
Output:
2
4
6
8
10
Output:
2
4
6
8
10
Using Enumerate()
If you wish to convert the list into an iterable list of tuples (or get the index on the basis of a condition check, for instance, in linear
search, one might want to save the index of minimum element), one can use the enumerate () function.
list = [1, 3, 5, 7, 9]
for i, val in enumerate(list):
print(i, ",",val)
Output:
0,1
1,3
2,5
3,7
4,9
You can also use the second method for finding the index. However, the first method cannot be used unless an extra variable is
incremented every iteration. Moreover, the fifth method gives a concise representation of this indexing.
Using Numpy
For every large n-dimensional list (for instance an image array), sometimes, it is better to make use of an external library like numpy.
Output:
0
1
2
3
4
5
6
7
8
One can make use of np.ndenumerate() for mimicking the behaviour of enumerating. Further, the extra power of numpy comes from
the fact that one can even control the way for visiting the elements (Fortran order rather than C order, say :)) however the one caveat is
that the np.nditer treats the array as read-only by default. Thus, one must pass extra flags like op_flags=[‘readwrite’] for it to be able to
modify elements.
Syntax:
The input function to the map () method gets called with every element of the iterable and it returns a new list with all the elements
returned from the function, individually.
Example:
print(res)
In the snippet of code mentioned above, you see how the lambda x:x function is given as input to the map() function. Thus, the lambda
x:x accepts every element of the iterable and returns it.
The input_list (lst) is given as the second argument to the map() function. Thus, the map() function will pass every element of lst to the
lambda x:x function and return the elements.
Output:
3. The list is better for performing Tuple data type is appropriate for
operations, such as insertion and accessing the elements
deletion.
5. Lists have several built-in methods Tuple does not have many built-in
methods.
6. The unexpected changes and errors are In tuple, it is hard to take place.
more likely to occur
str.format() is one of the string formatting methods in Python3, which allows multiple substitutions and value formatting. This
method lets us concatenate elements within a string through positional formatting. Types
Type Specification
Note: The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing
to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings
may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or
extensibility.
String objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or
interpolation operator. Given format % values (where format is a string), % conversion specifications in format are replaced with
zero or more elements of values. The effect is similar to using the sprintf() in the C language.
If format requires a single argument, values may be a single non-tuple object. 5 Otherwise, values must be a tuple with exactly the
number of items specified by the format string, or a single mapping object (for example, a dictionary).
A conversion specifier contains two or more characters and has the following components, which must occur in this order:
Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)).
Conversion flags (optional), which affect the result of some conversion types.
Minimum field width (optional). If specified as an '*' (asterisk), the actual width is read from the next element of the tuple in
values, and the object to convert comes after the minimum field width and optional precision.
Precision (optional), given as a '.' (dot) followed by the precision. If specified as '*' (an asterisk), the actual precision is read from
the next element of the tuple in values, and the value to convert comes after the precision.
When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised
mapping key into that dictionary inserted immediately after the '%' character. The mapping key selects the value to be formatted
from the mapping. For example:
In this case no * specifiers may occur in a format (since they require a sequential parameter list).
Flag Meaning
The value conversion will use the “alternate form” (where defined below).
'#'
'-' The converted value is left adjusted (overrides the '0' conversion if both are given).
'' (a space) A blank should be left before a positive number (or empty string) produced by a
signed conversion.
'+' A sign character ('+' or '-') will precede the conversion (overrides a “space” flag).
A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python
Conversion Meaning
'g' Floating point format. Uses lowercase exponential format if exponent is less than -4
'G' Floating point format. Uses uppercase exponential format if exponent is less than -4
Notes:
*The alternate form causes a leading octal specifier ('0o') to be inserted before the first digit.
*The alternate form causes a leading '0x' or '0X' (depending on whether the 'x' or 'X' format was used) to be inserted before the
first digit.
*The alternate form causes the result to always contain a decimal point, even if no digits follow it.
*The precision determines the number of digits after the decimal point and defaults to 6.
*The alternate form causes the result to always contain a decimal point, and trailing zeroes are not removed as they would
otherwise be.
*The precision determines the number of significant digits before and after the decimal point and defaults to 6.
It is possible to write programs that handle selected exceptions. Look at the following example, which asks the user for input until
a valid integer has been entered, but allows the user to interrupt the program (using Control-C or whatever the operating system
supports); note that a user-generated interruption is signalled by raising the KeyboardInterrupt exception.
>>> while True:
... try:
... break
...
First, the try clause (the statement(s) between the try and except keywords) is executed.
If no exception occurs, the except clause is skipped and execution of the try statement is finished.
If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception
named after the except keyword, the except clause is executed, and then execution continues after the try/except block.
If an exception occurs which does not match the exception named in the except clause, it is passed on to outer try statements; if no
handler is found, it is an unhandled exception and execution stops with a message as shown above.
A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be
executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try
statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:
... pass
class in an except clause is compatible with an exception if it is the same class or a base class thereof (but not the other way
around — an except clause listing a derived class is not compatible with a base class). For example, the following code will print
B, C, D in that order:
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
Note that if the except clauses were reversed (with except B first), it would have printed B, B, B — the first matching except
clause is triggered.
All exceptions inherit from BaseException, and so it can be used to serve as a wildcard. Use this with extreme caution, since it is
easy to mask a real programming error in this way! It can also be used to print an error message and then re-raise the exception
(allowing a caller to handle the exception as well):
import sys
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except ValueError:
raise
Alternatively the last except clause may omit the exception name(s), however the exception value must then be retrieved from
sys.exc_info()[1].
The try … except statement has an optional else clause, which, when present, must follow all except clauses. It is useful for code
that must be executed if the try clause does not raise an exception. For example:
try:
f = open(arg, 'r')
except OSError:
else:
f.close()
The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an
exception that wasn’t raised by the code being protected by the try … except statement.
>>> try:
...
<class 'Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
When an exception occurs, it may have an associated value, also known as the exception’s argument. The presence and type of the
argument depend on the exception type.
The except clause may specify a variable after the exception name. The variable is bound to an exception instance with the
arguments stored in instance.args. For convenience, the exception instance defines str() so the arguments can be printed directly
without having to reference .args. One may also instantiate an exception first before raising it and add any attributes to it as
desired.
If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions.
Exception handlers don’t just handle exceptions if they occur immediately in the try clause, but also if they occur inside functions
that are called (even indirectly) in the try clause. For example:
... x = 1/0
...
>>> try:
... this_fails()
...