0% found this document useful (0 votes)
99 views

Model Paper 2017-2019 Answer Key

This document provides a question bank with answers related to problem solving and Python programming. It includes 29 questions on topics like the difference between algorithms and programs, writing algorithms to find the minimum number in a list or calculate the sum of numbers, using functions, loops, recursion, strings, lists, dictionaries, modules, syntax errors, analyzing algorithm efficiency, and more. For each question, it provides explanations, code snippets, and example outputs to illustrate the concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
99 views

Model Paper 2017-2019 Answer Key

This document provides a question bank with answers related to problem solving and Python programming. It includes 29 questions on topics like the difference between algorithms and programs, writing algorithms to find the minimum number in a list or calculate the sum of numbers, using functions, loops, recursion, strings, lists, dictionaries, modules, syntax errors, analyzing algorithm efficiency, and more. For each question, it provides explanations, code snippets, and example outputs to illustrate the concepts.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

PROBLEM SOLVING AND PYTHON PROGRAMING –QUESTION BANK WITH ANSWER

2 MARKS:

1.Distinguish between algorithm or program?

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)

2 .Write an algorithm to find a minimum number in a given list of numbers ?

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

3.What are keywords?give examples?

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

4.State the reasons to divide the program into function?

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

5.Present the flow of execution for a while statement ?

N=10
Sum=0
I=1
While I<=n:
Sum=sum+i
I=i+1
Print(“the sum is:”,sum)

6.Define recursion with example?

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))

7.Relate strings and lists?

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

9.What is module?give example?

A file containing a set of function you want to include in your application


Example: import my module
My module.greeting(“python”)

10.Find the syntax error in the code given ;

While true print(“Hello world”)


Syntax error: ivalid syntax error

11.How will you analyze the effieceny of an algorithm ?

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

12.What is the use of algorithm ,flowchart,pseudocode in the perspective of problem solving ?

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

Ex:C,C++,c# etc… Ex: python,ruby perl,snobol,matlab etc…

14.Write a python program to print sum of cubes of the value of n variable?

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

15.Do loop statement have else clause ? when will it be executed ?

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

16.Write a program to display a set of strings using range ()function ?

For i in range(10):

Print(i,end,””)

Print()

For i in range (20):

Print(i,end,””)

17.How will you update list items?give one example?

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]

18.Can functions return tuples?if yes give example?

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’)

19.How to use command line arguments in python?

Import sys

Print(“number of arguments:”,len(sys.argv),’arguments.’)

Print(‘argument list:’,str(sys.argv))

20.Write methods to rename and delete files?

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

22.Name the four types of scalar objects in python ?

Scalar data types:integers,floats,none and bool.

23.What is a tuple?how literals of type tuple are written .give example?

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?

A=int(input(“enter first number :”))

B=int(input(“enter second number:”))

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

26.What is list?how lists differ from tuples?

List is a container to contain different types of objects and is used to iterate objects
LIST TUPLE

i)List is mutable Tuple is immutable


ii)list is useful for insertion and deletion operations
iii)list operations are more error prone Tuple is useful for read only
iv)ex:list=[‘a’,’b’,’c’,’d’]
operations like accessing elements

Tuple operations are safe

Ex:tuples=(‘a’,’b’,’c’,d)

27.how to slice a list in python?

 The format for list slicing is [start:stop:end]


 my_list=[1,2,3,4,5]
 Print(my_list[:])
 Output: [1,2,3,4,5]

28.Write a python script to display the current date and time ?

 Import the datetime module and display the current date


 Example:
Import datetime
X = datetime.datetime.now()
print(x)

29. Write a note on modular design?

 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[]

Print(“smallest element is:”,”list1[:1])

Output:

Smallest element is:4

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

32.state about logical operators available in python language with example.

Logical operators are used on conditional statements.

1) and - logical AND: true if both the operands are true


2) or - logical OR: true if either of the operand is true
3) not - logical NOT: true if operands is false

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]

Print(“the original list is:”+str(test_list))

K=3

Res=len(test_list) – test_list.index(K)

Print(“the required negative index: -“=+str(res))

Output:

The original list is:[5,7,8,2,3,5,1]

The required negative index: -3

35.demonstrate with simple code to draw thehistogram in python.

From matplotlib import pyplot as pit

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()

Print(“Current working direction:”,Cwd)

OUTPUT:

Current working directory:/

TYPES:

1)Import error , 2)Index error , 3)Key error


4)Name error , 5)Syntax error.

37.What is command line argument?

Python command line argument are input parameters passed to the script when executing them.Almost all programming
language provide support for command line arguments.

38.WHAT IS PICKLING IN PYTHON.

“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.

39.DEFINE FUNCTION COMPOSITION?

It is a way of combining function such that the result of each function is passed as the argument of the next function.

Function composition is achieved through lambda fuctions.

For example,

the composition of two functions f and g is denoted f(g(x)).

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.

40.DEFINE ALGORITHM.STATE SOME PROPERTIES OF THE GOOD ALGORITHM?

Algorithm is a step-by-step procedure for solving a problem.

Example:

sum of two numbers:

step1:start

step2:get the input from the user

step3:sum the two numbers

step4:store the value


step5:display the value

step6:stop

Properities:

Input specified

output specified

definiteness

finiteness

effectiveness

41.STATE THE DIFFERENCE BETWEEN ITERATION AND RECURSION.

ITERATION RECURSION

A sequence is executed repeatedly conditions true for/while loop

so long as certain

Example: Example: Example:

#numberlist Factorial(n):

Numbers=[6,5,3,8,4,2,5,4,11] If n==1:

Sum=0
Return 1

for val in numbers: Else:

sum = sum+val Return n*factorial(n-1)

print("The sum is" , sum)

42.Define file.

A file is a container in a computer system for storing information.

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.

43.Write a python program to find factorial of a given number

def factorial(x):

if x==1:

return 1

else:

return(x*factorial(x-1))
print(factorial of(6))

44.What is anonymous function in python?

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.

45.CLASSIFY GLOBAL VARIABLE WITH LOCAL VARIABLE.

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 .

46.WHAT IS LIST?HOW TO SLICE IN PYTHON?

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)

Print(‘List value : ’ , nums[ portion1])

Print(‘List value : ’ , nums[portion2])

List value:[1,2,3,4,5,6,7,8,9]

List value:[3,5,7]

47.WHAT IS TUPLE PACKING AND UNPACKING?

ANS: Tuple packing refers to assigning multiple values into a tuple. Tuple unpacking refers to assigning a tuple into multiple
variable.

48.DIFFERENTIATE ARGUMENTS AND PARAMETERS?

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

49.List out the various data types available in python.

1.Integers

Example:5433

2.Floats

Example:2.445

3.Booleans

Example: True, False

4.Lists

Example:[1,6,8,4,3]

50.Mention few strings methods.

split()-Splits the string at the specified separator and return a list

lower()-convert a string into lower case

format()-format specified value in a string

upper()-convert a string into upper case

isdigit()-returns true if all character in the string is digit

51.What is list comprehension? Give an example.

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

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = [x for x in fruits if "a" in x]

print(newlist)

52.define dictionary with example.

A dictionary is a collection which is ordered , changeable and does not allow duplicates.

They are used to store data values in key:value pairs.

Dictionaries are written in curly brackets.

EXAMPLE:
#dictionary with integer keys

my_dict ={1: 'apple',2: 'ball'}

Internal assessment - 02
PART-B

1.Implementation of Linear search?

Algorithm
 Start from the leftmost element of given arr[] and one by one compare element x with each element of arr[]

 If x matches with any of the element, return the index value.

 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?

2)Implementation of Binary search:


Binary Search Algorithm:
The basic steps to perform Binary Search are:
 Begin with an interval covering the whole array.
 If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
 Otherwise, narrow it to the upper half.
 Repeatedly check until the value is found or the interval is empty.

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

while low <= high:

mid = (high + low) // 2

# If x is greater, ignore left half


if arr[mid] < x:
low = mid + 1

# If x is smaller, ignore right half


elif arr[mid] > x:
high = mid - 1

# means x is present at mid


else:
return mid

# If we reach here, then the element was not present


return -1

# 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.

Type of condition statement in Python:

 If statement..
 Elif statement.
 Nested if statement.
 Nested if else statement.

IF statement;

An "if statement" is written by using the if keyword.

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.")

Nested if else statement;

i = 20;

if (i < 15):

print ("i is smaller than 15")

print ("i'm in if Block")

else:

print ("i is greater than 15")

print ("i'm in else Block")

print ("i'm not in if and not in else Block")

Output:
i is greater than 15

4) Different arguments in function with example.

1. default arguments

2. keyword arguments

3. positional arguments

4. arbitrary positional arguments


5. For arbitrary positional argument, a double asterisk (**) is placed before a parameter in a function which can hold keyword

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.

 The assignment operator = is used to assign a default value to the argument.

 Default arguments become optional during the function calls.

 If we provide a value to the default arguments during function calls, it overrides the default value.

 The function can have any number of default arguments

 Default arguments should follow non-default arguments.

Example:

In the below example, the default value is given to argument band c


def add(a,b=5,c=10):
return (a+b+c)

This function can be called in 3 ways

1. Giving only the mandatory argument


print(add(3))
#Output:18

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)

Calling the function add by giving keyword arguments

positional arguments;

During a function call, values passed through arguments should be in the order of parameters in the function definition. This is

called positional arguments.

Keyword arguments should follow positional arguments only.

Example:
def add(a,b,c):
return (a+b+c)

The above function can be called in two ways:

1. During the function call, all arguments are given as positional arguments. Values passed through arguments are passed to

parameters by their position. 10 is assigned to a, 20 is assigned to b and 30 is assigned to c.


print (add(10,20,30))
#Output:60

Arbitrary Keyword arguments;

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')
'''

Arbitrary Positional arguments;

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

normal arguments may occur.


def add(*b):
result=0
for i in b:
result=result+i
return result

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:

# Python program to demonstrate

# strings

# Assign Welcome string to the variable var1

var1 = "Welcome"

# Assign statistics string to the variable var2

var2 = "statistics"

# print the result

print(var1)

print(var2)

Output
Welcome
Statistics

String Concatenation in Python


String Concatenation is the technique of combining two strings. String Concatenation can be done using many ways.
We can perform string concatenation using following ways:
1. Using + operator

2. Using join() method

3. Using % operator

4. Using format() function

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

# Python program to demonstrate

# string concatenation

# Defining strings

var1 = "Hello "

var2 = "World"

# + Operator is used to combine strings

var3 = var1 + var2

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.

Using join() Method


The join() method is a string method and returns a string in which the elements of sequence have been joined by str separator.
Example:

 Python3

# Python program to demonstrate


# string concatenation

var1 = "Hello"

var2 = "World"

# join() method is used to combine the strings

print("".join([var1, var2]))

# join() method is used here to combine

# the string with a separator Space(" ")

var3 = " ".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

# Python program to demonstrate

# string concatenation

var1 = "Hello"

var2 = "World"
# % Operator is used here to combine the string

print("% s % s" % (var1, var2))

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”.

Using format() function


str.format() is one of the string formatting methods in Python, which allows multiple substitutions and value formatting. This
method lets us concatenate elements within a string through positional formatting.
Example:

 Python3

# Python program to demonstrate

# string concatenation

var1 = "Hello"

var2 = "World"

# format function is used here to

# combine the string

print("{} {}".format(var1, var2))

# store the result in another variable

var3 = "{} {}".format(var1, var2)

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:

# Python program to demonstrate

# string concatenation

var1 = "Hello"

var2 = "World"

# , to combine data types with a single whitespace.

print(var1, var2)

Output

Hello World

Python string length | len()


Python len() function returns the length of the string.
Python len() Syntax:
len(string)
len() Parameters:
It takes a string as the parameter.
len() Return Value:
It returns an integer which is the length of the string.
Python len() Example

Example 1: Len() function with tuples, list, and string

 Python

# Python program to demonstrate the use of

# 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

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.

Let’s look through some examples for string comparison.

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.

Reverse string in Python (5 different ways)


Python string library does’nt support the in-built “reverse()” as done by other python containers like list, hence knowing
other methods to reverse string can prove to be useful. This article discusses several ways to achieve it.
Using loop

# Python code to reverse a string

# using loop

def reverse(s):

str = ""

for i in s:

str = i + str

return str

s = "Geeksforgeeks"

print ("The original string is : ",end="")

print (s)

print ("The reversed string(using loops) is : ",end="")

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

Python Aliasing and Cloning Lists


Giving a new name to an existing list is called 'aliasing'. The new name is called 'alias name'. For example, take a list 'x' with 5
elements as

x = [10, 20, 30, 40, 50]

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

print(x) will display [10,20,30,40,50]

print(y) will display [10,20,30,40,50]

x[1] = 99 #modify 1st element in x

print(x) will display [10,99,30,40,50]

print(y) will display [10,99,30,40,50]

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

print(x) will display [10,20,30,40,50]

print(y) will display [10,20,30,40,50]

x[1] = 99 #modify 1st element in x

print(x) will display [10,99,30,40,50]

print(y) will display [10,20,30,40,50]

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.

7).Tuple assignment and tuple as return value


Tuple Assignment

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.

Tuple Packing (Creating Tuples)

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.

Example 1: Tuple with integers as elements

>>>tup = (22, 33, 5, 23)

>>>tup

(22, 33, 5, 23)


Example 2: Tuple with mixed data type

>>>tup2 = ('hi', 11, 45.7)

>>>tup2

('hi', 11, 45.7)


Example 3: Tuple with a tuple as an element

>>>tup3 = (55, (6, 'hi'), 67)

>>>tup3

(55, (6, 'hi'), 67)


Example 4: Tuple with a list as an element

>>>tup3 = (55, [6, 9], 67)

>>>tup3

(55, [6, 9], 67)

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

>>>seq

(22, 4, 56)

>>>type(seq)

<class 'tuple'>

Tuples as Return Values

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):

""" Return (circumference, area) of a circle of radius r """

c = 2 * 3.14159 * r

a = 3.14159 * r * r

return (c, a)

print(circleInfo(10))

8.Python List Slicing

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

Lst = [50, 70, 30, 20, 90, 10, 50]

# 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

Lst = [50, 70, 30, 20, 90, 10, 50]

# Display list
print(Lst[1:5])
Output:
[70, 30, 20, 90]

Python – List Comprehension


Python is renowned for encouraging developers and programmers to write efficient, easy-to-understand, and almost as simple-
to-read code. One of the most distinctive aspects of the language is the python list and the list compression feature, which one
can use within a single line of code to construct powerful functionality.
List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list
comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to
iterate over each element.
Syntax:
newList = [ expression(element) for element in oldList if condition ]
Example

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

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=[]

num=int(input("Enter the number of elements in the list:"))

for i in range(1,num):

temp=int(input("enter the element :"))

alist.append(temp)

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:

Enter the number of elements in the list:6

enter the element :45

enter the element :23

enter the element :76

enter the element :83

enter the element :34

Unsorted: [45, 23, 76, 83, 34]

Inter: [23, 45, 76, 83, 34]

Inter: [23, 34, 45, 76, 83]

Inter: [23, 34, 45, 76, 83]

Inter: [23, 34, 45, 76, 83]

Inter: [23, 34, 45, 76, 83]

sorted: [23, 34, 45, 76, 83]

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

Question no : 10 :Insertion Sort

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 Spilt a list in two parts - sorted and unsorted.

o Iterate from arr[1] to arr[n] over the given array.

o Compare the current element to the next element.

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.

Let's understand the following example.

We will consider the first element in the sorted array in the following array.

[10, 4, 25, 1, 5]

The first step to add 10 to the sorted subarray

[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.

[10, 10, 25, 1, 5] (temp = 4)

Here the 4 is lesser than all elements in sorted subarray, so we insert it at the first index position.

[4, 10, 25, 1, 5]

We have two elements in the sorted subarray.

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.

[4, 10, 25, 1, 5]

Again we check the number 1. We save it in temp. 1 is less than the 25. It overwrites the 25.

[4, 10, 25, 25, 5] 10>1 then it overwrites again

[4, 25, 10, 25, 5]

[25, 4, 10, 25, 5] 4>1 now put the value of temp = 1

[1, 4, 10, 25, 5]

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.

[1, 4, 5, 10, 25]

The given array is sorted.

Python Program

1. # creating a function for insertion


2. def insertion_sort(list1):
3.
4. # Outer loop to traverse through 1 to len(list1)
5. for i in range(1, len(list1)):
6.
7. value = list1[i]
8.
9. # Move elements of list1[0..i-1], that are
10. # greater than value, to one position ahead
11. # of their current position
12. j=i-1
13. while j >= 0 and value < list1[j]:
14. list1[j + 1] = list1[j]
15. j -= 1
16. list1[j + 1] = value
17. return list1
18. # Driver code to test above
19.
20. list1 = [10, 5, 13, 8, 2]
21. print("The unsorted list is:", list1)
22.
23. print("The sorted list1 is:", insertion_sort(list1))

Output:

The unsorted list is: [10, 5, 13, 8, 2]


The sorted list1 is: [2, 5, 8, 10, 13]

11.Reading and Writing to text files in Python.

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.

# Open function to open the file "MyFile1.txt"

# (same directory) in append mode and

file1 = open("MyFile.txt","a")

# store its reference in the variable file1

# and "MyFile2.txt" in D:\Text in file2

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()

# Opening and Closing a file "MyFile.txt"

# for object name file1.

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:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

Example

Open the file "demofile2.txt" and append content to the file:

f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()

#open and read the file after the appending:


f = open("demofile2.txt", "r")
print(f.read())

Reading from a file

There are three ways to read data from a text file.


1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.
File_object.read([n])
2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does
not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
3. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes

Program :

#Program to show various ways to read and

# write data in a file.

file1 = open("myfile.txt","w")

L = ["This is Delhi \n","This is Paris \n","This is London \n"]

# \n is placed to indicate EOL (End of Line)

file1.write("Hello \n")

file1.writelines(L)

file1.close() #to change file access modes

file1 = open("myfile.txt","r+")

print("Output of Read function is ")

print(file1.read())

print()

# seek(n) takes the file handle to the nth

# bite from the beginning.

file1.seek(0)

print( "Output of Readline function is ")

print(file1.readline())

print()

file1.seek(0)

# To show difference between read and readline

print("Output of Read(9) function is ")

print(file1.read(9))

print()

file1.seek(0)

print("Output of Readline(9) function is ")

print(file1.readline(9))

file1.seek(0)

# readlines function

print("Output of Readlines function is ")


print(file1.readlines())

print()

file1.close()

Output:

Output of Read function is

Hello

This is Delhi

This is Paris

This is London

Output of Readline function is

Hello

Output of Read(9) function is

Hello

Th

Output of Readline(9) function is

Hello

Output of Readlines function is

['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

In Python, exceptions can be handled using a try 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]

for entry in randomList:


try:
print("The entry is", entry)
r = 1/int(entry)
break
except:
print("Oops!", sys.exc_info()[0], "occurred.")
print("Next entry.")
print()
print("The reciprocal of", entry, "is", r)

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.

Try with Else Clause

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.

Example: Try with else clause

# Program to depict else clause with try-except

# Function which returns a/b


def AbyB(a , b):

try:

c = ((a+b) / (a-b))

except ZeroDivisionError:

print ("a/b result in 0")

else:

print (c)

# Driver program to test above function

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

# Python code to illustrate

# working of try()

def divide(x, y):

try:

# Floor Division : Gives only Fractional

# Part as Answer

result = x // y

except ZeroDivisionError:

print("Sorry ! You are dividing by zero ")

else:

print("Yeah ! Your answer is :", result)

finally:

# this block is always executed

# regardless of exception generation.


print('This is always executed')

divide(3, 2)

divide(3, 0)

Output:

Yeah ! Your answer is : 1

This is always executed

Sorry ! You are dividing by zero

This is always executed

Question no : 13

Python – Count Number of Words in Text File

You can count number of words in a text file in Python by following a sequence of steps

Steps to Count Number of Words in Text File

To count the number of words in a text file, follow these steps.

1. Open the file in read mode and handle it in text mode.


2. Read the text using read() function.
3. Split the text using space separator. We assume that words in a sentence are separated by a space character.
4. The length of the split list should equal the number of words in the text file.
5. You can refine the count by cleaning the string prior to splitting or validating the words after splitting.

Example 1: Count Number of Words

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

file = open("C:\data.txt", "rt")


data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

Output
Number of words in text file : 14

Count Number of Characters


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.

Count Number of Characters

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.

steps to Count Number of Characters

To count the number of characters in a text file, follow these steps.

1. Open the file in read mode


2. Read the text using read() function.
3. Get the length of the string, that should be the number of characters in the text file.
4. You can refine the count by cleaning the string like removing white space characters and punctuation marks.

Example 1: Count Characters in a Text File

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")

#read the content of file


data = file.read()

#get the length of the data


number_of_characters = len(data)

print('Number of characters in text file :', number_of_characters)


Output
Number of characters in text file : 97

Steps to Get Line Count in a File

1. Open file in Read Mode

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.

3. Close file after completing the read operation

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

 The enumerate() function adds a counter to each line.


 Using enumerate, we are not using unnecessary memory. It is helpful if the file size is large.

GE8151 – PROBLEM SOLVING AND PYTHON PROGRAMMING – 2017

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

WRITE “Please enter two numbers to add”

READ num1

READ num2

Sum = num1+num2

WRITE Sum

END

3.Outline the modes Python interpreter works?

 Python has two basic modes: Script and interactive mode.

 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.

4.State the difference between (I) and (II) operators in python.


Arithmetic operators:

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:

print(“Enter two numbers:”)

Num1=int(input(“Enter Number1:”)

Num2 =int(input(“Enter Number2:”)

if Num1>Num2:

print(“\n Largest Number: “, Num1)

else:

print(“\n Largest Number:”, Num2)

Output:

Enter two numbers:

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.

7.What is a list in Python? Give example.

List:

Lists are used to store multiple items in a single variable enclosed within square brackets.

Example:

Alist = [“apple”,”mango”,”orange”]

print(Alist)

8.Write the syntax for concatenating two lists in Python.

Using extend():

Llist1 = [1,”a”]

List2 = [1,2,3]

List2.extend(List1)

print(List2)

Output:

[1,2,3,1,’a’]

9.What is an exception? Give example.

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)

Output: ZeroDivisionError: division by zero

10.Write the syntax for opening a file in python for reading only.

f = open(“text1.txt”, mode=”r”, encoding=”utf-8”)

Syntax = r - opens a file for reading

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

the one that solves it the fastest.

 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 "-".

2. Append first letter

3. Append "ay"

4. Remove first letter

 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"

instead of the unpronounceable "ggs-eay":

1. Append "-"

2. Store first letter

3. If first letter is vowel:

a. Append "yay"

4. Otherwise:

a. Append first letter

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

"eanut-pay utter-bay and-yay elly-jay":

1. Store list of words

2. For each word in words:

a. Append hyphen

b. If first letter is vowel:

c. Append "yay"

d.Otherwise:

3. Append first letter

a. Append "ay"

b. Remove first letter

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

Attributes and Imports:

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.

Standard library 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

# Add two numbers

sum = num1 + num2

# Display the sum

print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))

12. a).

ii. Outline with an example the assignment operator support in python?

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

12 b). Explain the various data types of python?

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.

Built-in Data Types in Python

 Binary Types: memoryview, bytearray, bytes


 Boolean Type: bool
 Set Types: frozenset, set
 Mapping Type: dict
 Sequence Types: range, tuple, list
 Numeric Types: complex, float, int
 Text Type: str
 1. Numeric Data type:
We can find complex numbers, floating point numbers and integers in the category of Python Numbers. Complex
numbers are defined as a complex class, floating point numbers are defined as float and integers are defined as an int in
Python. There is one more type of datatype in this category, and that is long. It is used to hold longer integers. One will
find this datatype only in Python 2.x which was later removed in Python 3.x.
“Type()” function is used to know the class of a value or variable. To check the value for a particular class, “isinstance()”
function is used.
 Integers:
o There is no maximum limit on the value of an integer. The integer can be of any length without any limitation which can
go up to the maximum available memory of the system.
 Integers can look like this:
o >>> print(123123123123123123123123123123123123123123123123123 + 1)
123123123123123123123123123123123123123123123123124
 Floating Point Number:
o The difference between floating points and integers is decimal points. Floating point number can be represented as “1.0”,
and integer can be represented as “1”. It is accurate up to 15 decimal places.
 Complex Number:
o “x + yj” is the written form of the complex number. Here y is the imaginary part and x is the real part.
Python List
An ordered sequence of items is called List. It is a very flexible data type in Python. There is no need for the value in the list to be
of the same data type. The List is the data type that is highly used data type in Python. List datatype is the most exclusive datatype
in Python for containing versatile data. It can easily hold different types of data in Python.
It is effortless to declare a list. The list is enclosed with brackets and commas are used to separate the items.
A list can look like this:
>>> a = [5,9.9,’list’]
One can also alter the value of an element in the list.

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

start = int(input("Enter start number:"))

end = int(input("Enter last number:"))


while(start<=end):
if(start%5==0):
print(start)
start += 1
Output :
Enter start number: 1
Enter last number: 50
5
10
15
20
25
30
35
40
45
50

13.(a)ii)Python Program to compute the factorial of a given number

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

(b) Binary search:


Binary Search Algorithm:
The basic steps to perform Binary Search are:
 Begin with an interval covering the whole array.
 If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half.
 Otherwise, narrow it to the upper half.
 Repeatedly check until the value is found or the interval is empty.

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

while low <= high:

mid = (high + low) // 2

# If x is greater, ignore left half


if arr[mid] < x:
low = mid + 1

# If x is smaller, ignore right half


elif arr[mid] > x:
high = mid - 1

# means x is present at mid


else:
return mid

# If we reach here, then the element was not present


return -1

# 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

Write code snippets in python to perform the following.

(i)accessing tuple elements:

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'

(ii)Modifying tuple elements:

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.

ADDDING TWO TUPLES:


tup1=(912,13.46)

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])

(iii)DELETING TUPLE ELEMENTS:

my_tuple = (12,34,'test',45,22,33,19)

n=2

my_tuple = my_tuple[ :n]+my_tuple[n+1 : ]

print(my_tuple)

Output:

(12,34,45,22,33,19)
(b) Write a python program to sort an integer list using selection sort.

alist=[]

num=int(input("Enter the number of elements in the list:"))

for i in range(1,num):

temp=int(input("enter the element :"))

alist.append(temp)

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:

Enter the number of elements in the list:6

enter the element :45

enter the element :23

enter the element :76

enter the element :83

enter the element :34

Unsorted: [45, 23, 76, 83, 34]

Inter: [23, 45, 76, 83, 34]

Inter: [23, 34, 45, 76, 83]

Inter: [23, 34, 45, 76, 83]

Inter: [23, 34, 45, 76, 83]

Inter: [23, 34, 45, 76, 83]

sorted: [23, 34, 45, 76, 83]

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

Exception handling in python

The try-expect statement

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'>

The except statement with

7. print("Hi I am else block")

Output:

Enter a:10
Enter b:0
can't divide by zero
<class 'Exception'>

The except statement with

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)

print (" 'file1.txt' content Copied to 'file2.txt' using R/W")

of1.close()

of2.close()

import shutil

shutil.copyfile('file2.txt','file3.txt')

print (" 'file2.txt' content Copied to 'file3.txt' using shutil package")

GE8151 Problem Solving And Python Programming 2018

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.

REFER 2017 MODEL PAPER……..

12)a) i)What is a numeric literals? Give examples.

Numeric Literals:

*Numeric literals are used to represent numbers in a python program.

*In python we have different types of numeric literals such


integers,
floating point numbers and complex
numbers.

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'>

12)a)ii)Appraise with an arithmetic operator in python with an example.

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

# using the addition operator

res = val1 + val2

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

# using the subtraction operator


res = val1 - val2

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

# using the multiplication operator

res = val1 * val2

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

#using the division operator

res = val1 / val2

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

# using the modulus operator

res = val1 % val2

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

# using the exponentiation operator

res = val1 ** val2

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

# using the floor division

res = val1 // val2

print(res)

Output : 1

12)b)i)outline the operator precedence of arithmertic operator in python.

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.

Operator Description ASSOCIATIVITY

** Exponent Right-to-left
* Multiplication Left-to-right
/ Division
% modulus
+ Addition Left-to-right
- Subtraction

Eg: precedency of operators:

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.

Using temp variable:

# Python program to swap two variables

x=5
y = 10

# To take inputs from the user


#x = input('Enter value of x: ')
#y = input('Enter value of y: ')

# create a temporary variable and swap the values


temp = x
x=y
y = temp

print('The value of x after swapping: {}'.format(x))


print('The value of y after swapping: {}'.format(y))

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

for number in range(1,Even+1):

if (number%2==0):

print(number)

total=total+number

print("The sum of even numbers",total)

Even=int(input("Enter the range of numbers:"))

even_num()

OUTPUT:

Enter the range of numbers:10

10

The sum of even numbers 30

13.a)i) appraise with an example nested if and elif header in python

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

The syntax of the nested if...elif...else construct may be −


if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
statement(s)
else:
statement(s)

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"

print "Good bye!"

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

elif test expression:

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

In while loop, test expression is checked first.

• 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.

• In Python, the body of the while loop is determined through indentation.

• 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:

The break statement terminates the loop containing it.

• Control of the program is transferred to the statement which is present immediately after

the body of the loop.

• If break statement is inside a nested loop (loop inside another loop), break will

terminate the innermost loop

syntax:
break

Example:

For val in “string::

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:

For val in “string”:

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:

# Factorial of a number using recursion

def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

num = 7

# check if the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

if num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of", num, "is", recur_factorial(num))

Without recursion:

#Factorial without recursion

n=int(input("Enter the number: "))

fact=1

if n<0:

print("factorial doesn't exist for negative numbers")

else:

for i in range(1,n+1):

fact=fact*i

print("factorial of", n, "is", fact)

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.

# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms

n1, n2 = 0, 1

count = 0

# check if the number of terms is valid

if nterms <= 0:
print("Please enter a positive integer")

# if there is only one term, return n1

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

# generate fibonacci sequence

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1

14.a.(i) What is dictionary in python? Give example.

 Dictionaries are used to store data values in key:value pairs.


 A dictionary is a collection which is ordered*, changeable

and does not allow duplicates.

 Dictionaries are written with curly brackets, and have keys

and values

 Values in a dictionary can be of any data type and can be

duplicated, whereas keys can’t be repeated and must

be immutable.

 Dictionary keys are case sensitive, the same name but

different cases of Key will be treated distinctly.

Example:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}

(ii)Appraise the operations for dynamically manipulating dictionaries.

Dictionary operations in python:

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():

The copy() method returns a copy of the specified dictionary.

Syntax:

dictionary.copy()

Example:

car = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

x = car.copy()

print(x)

Output:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}

Fromkeys():

The fromkeys() method returns a dictionary with the specified keys and the specified value

Syntax:

dict.fromkeys(keys, value)

Example:

x = ('key1', 'key2', 'key3')

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:

Dict_items([('brand', 'Ford'), ('model', 'Mustang'), ('year', 1964)])

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:

dict_keys(['brand', 'model', 'year'])

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:

{'brand': 'Ford', 'model': 'Mustang'}

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 update() method inserts the specified items to the dictionary.

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:

{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}


values():

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:

dict_values(['Ford', 'Mustang', 1964])

Looping through dictionaries:

Looping in dictionaries can be done with for loop.

Example

Print all key names in the dictionary, one by one:

thisdict = {

"brand": "Ford",

"model": "Mustang",

"year": 1964

for x in thisdict:

print(x)

Output:

brand
model
year

14.b.(ii) Write a python program to perform linear search on a list.


A linear search or sequential search is a method for finding an element within a list. It sequentially checks each element of the list
until a match is found or the whole list has been searched. A linear search runs in at worst linear time and makes at most n
comparisions,where n is the length of the list. If each element is equally likely to be searched, then linear search has an average
case of n+1/2 comparisons, but the average case can be affected if the search probabilities for each element vary.

Python Code:

# Linear Search function

def linearsearch(num_list, search):

found = False

for i in num_list:

if search == i:

found = True

print("Element found")

break

if not found:

print("Element not found")

# Main Program

num_list = []

n = int(input("Enter number of items of num_list: "))

print("Enter ", n, "values:")

for i in range(0, n):

item = int(input(" "))

num_list.append(item)

search = int(input("Element to be searched: "))

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.

Python file processing modes

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

 r - open a file for reading. (default)

 w - Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be
created

 x - open for exclusive creation, failing if the file already exists

 a - open for writing, appending to the end of the file if it exists

 b - binary mode

 t - text mode (default)

 +r - Open a file for updating (reading and writing)

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

15.B)2) Explain with an example Exceptions with aruguments in Python .


 It can be used to gain additional information about the error encountered.

 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.

Arguments in Built-in Exceptions:


The below codes demonstrates use of Argument with Built-in Exceptions:

Example 1:
try:

b = float(100 + 50 / 0)

except Exception as Argument:

print( 'This is the Argument\n', Argument)

Output:
This is the Argument
division by zero

Arguments in User-defined Exceptions:


The below codes demonstrates use of Argument with User-defined Exceptions:

Example 1:

class MyError(Exception):

# Constructor or Initializer

def __init__(self, value):

self.value = value

# __str__ is to print() the value

def __str__(self):

return(repr(self.value))

try:

raise(MyError("Some Error Data”)

except MyError as Argument:

print('This is the Argument\n', Argument)

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 generally consist of instructions for a computer.

• Programming languages can be used to create programs that implement specific algorithms.

• Eg : C, C++, COBAL, JAVA, Python ... Etc

PROGRAMMING LANGUAGE

• Types of programming language

1. Machine language

2. Assembly language

3. High level 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.

Machine language instructions are of four types:

Arithmetic, Logical, Data transfer, and Branches (also called flow control), as follows:

• Arithmetic: add (addition), sub (subtraction), mult (multiplication), div (division)

• 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),

• Unconditional: j (jump), jr (jump register), jal (jump-and-link)

Advantages:

 Machine language makes fast and efficient use of the computer.


 It requires no translator to translate the code. It is directly understood by the computer.

Disadvantages:

 All operation codes have to be remembered.


 All memory addresses have to be remembered.

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.

• Assembly code can be converted to machine code using an assembler.

Advantages:-

 It allows complex jobs to run in a simpler way.


 It is memory efficient, as it requires less memory.
 It is faster in speed, as its execution time is less.
 It is mainly hardware-oriented.
 It requires less instruction to get the result.
 It is used for critical jobs.

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

High level language:

• High level language contains English words and symbols.

• 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:-

 High level languages are programmer friendly.


 They are easy to write, debug and maintain.
 It provide higher level of abstraction from machine languages.
 It is machine independent language.
 The main advantage of high-level languages over low-level languages is that they are easier to read, write, and
maintain.

Disadvantages of High level language

 It takes additional translation times to translate the source to machine code.


 High level programs are comparatively slower than low level programs.
 Compared to low level programs, they are generally less memory efficient.
Cannot communicate directly with the hardware.

ii)Fibonacci sequence:
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
b)i)Recursive function:
 Recursive Functions in Python
A recursive function is a function defined in terms of itself via self-referential expressions. This means that the function will
continue to call itself and repeat its behavior until some condition is met to return a result.
Advantages:-
1. The code may be easier to write.

2. To solve such problems which are naturally recursive such as tower of Hanoi.

3. Reduce unnecessary calling of function.

4. Extremely useful when applying the same solution.

5. Recursion reduce the length of code.

6. It is very useful in solving the data structure problem.

7. Stacks evolutions and infix, prefix, postfix evaluations etc.

Disadvantages of recursion

1. Recursive functions are generally slower than non-recursive function.

2. It may require a lot of memory space to hold intermediate results on the system stacks.

3. Hard to analyze or understand the code.

4. It is not more efficient in terms of space and time complexity.

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

for i in range(2, n + 1):

res *= i;

return res;

# Driver method

num = 5;

print("Factorial of",num,"using Recursion is:",

factorialUsingRecursion(5));

print("Factorial of",num,"using Iteration is:",

factorialUsingIteration(5));

# This code is contributed by mits

Output:

Factorial of 5 using Recursion is: 120

Factorial of 5 using Iteration is: 120

12a)i)python program to rotate a list by right n times with and without slicing techniques.

def right_rotation(my_list, num):

output_list = []
for item in range(len(my_list) - num, len(my_list)):

output_list.append(my_list[item])

for item in range(0, len(my_list) - num):

output_list.append(my_list[item])

return output_list

# Driver Code

A=list()

n=int(input("Enter the size of the List"))

print("Enter the number")

for i in range(int(n)):

p=int(input("n="))

A.append(int(p))

print (A)

rot_num=int(input("Enter rotate number"))

print("After rotation",right_rotation(A, rot_num))

python54.py

Output

Enter the size of the List 6

Enter the number

n= 11

[11]

n= 22

[11, 22]

n= 33

[11, 22, 33]

n= 44

[11, 22, 33, 44]

n= 55

[11, 22, 33, 44, 55]

n= 66

[11, 22, 33, 44, 55, 66]

Enter rotate number 3

After rotation [44, 55, 66, 11, 22, 33]


Method2

Here we apply slicing technique using len().

A=list()

ni=int(input("Enter the size of the List"))

print("Enter the number")

for i in range(int(ni)):

p=int(input("ni="))

A.append(int(p))

print (A)

n=3

A = (A[len(A) - n:len(A)] + A[0:len(A) - n])

print("After Rotation",A)

Output

Enter the size of the List 6

Enter the number

ni= 11

[11]

ni= 22

[11, 22]

ni= 33

[11, 22, 33]

ni= 44

[11, 22, 33, 44]

ni= 55

[11, 22, 33, 44, 55]

ni= 66

[11, 22, 33, 44, 55, 66]

After Rotation [44, 55, 66, 11, 22, 33]

ii)Keyword arguments and default arguments with example:

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

def team(name, project):

print(name, "is working on an", project)

team(project = "Edpresso", name = 'FemCode')

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):

result = integer1 * integer1

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)evaluate the following expression:


i)24//6%3=1

ii)float(4+int(2.39)%2)=

iii)2**2**3=64

13b)compare lists and array.

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

 Insertion and Deletion operations are


costlier since the memory locations are
consecutive and fixed.  Memory is allocated during the run-
 Memory is allocated during the time (Dynamic memory allocation).
compile time (Static memory
allocation).  Size of a Linked list grows/shrinks as
and when new elements are
 Size of the array must be specified at inserted/deleted.
the time of array
declaration/initialization.
ii)anagram

# function to check if two strings are

# anagram or not

def check(s1, s2):

# the sorted strings are checked

if(sorted(s1)== sorted(s2)):

print("The strings are anagrams.")

else:

print("The strings aren't anagrams.")

# driver code

s1 ="listen"

s2 ="silent"

check(s1, s2)

Output

The strings are anagrams

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

i)initialize two dictionaries with keys and value pairs:

# Python3 code to demonstrate working of

# Initialize dictionary with multiple keys

# Using fromkeys()

# Initialize keys

test_keys = ['gfg', 'is', 'best']

# Using fromkeys()

# Initialize dictionary with multiple keys

res ={ **dict.fromkeys(test_keys, 4)}

# printing result

print("Dictionary after Initializing multiple key-value : " + str(res))

ii)compare two dictrionarties nwith master keys list and print missing keys

Compare keys

if key match

compare values

if all values match

break

else:

print the key and the corresponding missing value/s.

"Missing value/s on key "Florida" in the Second_Dict"

"Naples"

if keys NOT match or missing

print the unmatching/missing key and corresponding value/s.

"Missing key and value/s on First_Dict"

Illinois

Chicago

Naperville
"Missing key and value/s on Second_Dict"

Arizona

Phoenix

Tucson

for key, value in First_Dict.items() and Second_Dict.items():

if key in First_Dict.keys() == Second_Dict.keys():

for value in First_Dict.value() and Second_Dict.value :

if value in First_Dict.value() == Second_Dict.value():

break

else:

print(value)

iii)find keys that are in first and not in secondary

# Python3 code to demonstrate working of

# Getting first key in dictionary

# Using keys() + list()

# initializing dictionary

test_dict = {'Gfg' : 1, 'is' : 2, 'best' : 3}

# printing original dictionary

print("The original dictionary is : " + str(test_dict))

# Using keys() + list()

# Getting first key in dictionary

res = list(test_dict.keys())[0]

# printing initial key

print("The first key of dictionary is : " + str(res))\

iv)find same keys in two dictionaries

some_dict = { 'zope':'zzz', 'python':'rocks' }

another_dict = { 'python':'rocks', 'perl':'$' }

intersect = []

for item in some_dict.keys( ):

if item in another_dict.keys( ):

intersect.append(item)

print "Intersects:", intersect

v)merge two dictionaries and create a new dictionary in single expression


def Merge(dict1, dict2):

return(dict2.update(dict1))

# Driver code

dict1 = {'a': 10, 'b': 8}

dict2 = {'d': 6, 'c': 4}

# This return None

print(Merge(dict1, dict2))

# changes made in dict2

print(dict2)

ii)LIST COMPREHENSION WITH EXAMPLE:

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

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]

newlist = []

for x in fruits:

if "a" in x:

newlist.append(x)

print(newlist)

14Bi)tuple: differ from list

Tuples are used to store multiple items in a single variable.

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.

A tuple is a collection which is ordered and unchangeable.

Tuples are written with round brackets.

Example

Create a Tuple:
thistuple = ("apple", "banana", "cherry")

print(thistuple)

Key difference tuple from list:

hey are both used to store collection of data

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]

ii)program to sort n numbers using merge sort:

def merge_sort(alist, start, end):

'''Sorts the list from indexes start to end - 1 inclusive.'''

if end - start > 1:

mid = (start + end)//2

merge_sort(alist, start, mid)

merge_sort(alist, mid, end)

merge_list(alist, start, mid, end)

def merge_list(alist, start, mid, end):

left = alist[start:mid]

right = alist[mid:end]

k = start

i=0

j=0

while (start + i < mid and mid + j < end):

if (left[i] <= right[j]):

alist[k] = left[i]

i=i+1

else:

alist[k] = right[j]

j=j+1

k=k+1

if start + i < mid:

while k < end:


alist[k] = left[i]

i=i+1

k=k+1

else:

while k < end:

alist[k] = right[j]

j=j+1

k=k+1

alist = input('Enter the list of numbers: ').split()

alist = [int(x) for x in alist]

merge_sort(alist, 0, len(alist))

print('Sorted list: ', end='')

print(alist)

PROBLEM SOLVING AND PYTHON PROGRAM(AM2019)


11.a)Mention the different types of iterative structure allowed in python .explain the use of continue and break statement with an example .

The three types of loops in Python programming are:


 while loop
 for loop
 nested loops

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

Syntax of for loop:

for item in iterator:

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:

for val in "string":

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:

for val in "string":

if val == "i":

continue

print(val)

print("The end")

11.b) (i) what is an algorithm ?summarise the characteristics of a good algorithm.

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.

An algorithm should have the following characteristics −

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.

Input − An algorithm should have 0 or more well-defined inputs.

Output − An algorithm should have 1 or more well-defined outputs, and should match the desired output.

Finiteness − Algorithms must terminate after a finite number of steps.

Feasibility − Should be feasible with the available resources.


Independent − An algorithm should have step-by-step directions, which should be independent of any programming
code.

(ii)outline the algorithm for displaying the first n odd numbers

Step1: Start

Step2: Get value for n

Step3: Iterate in a for loop from 1 to n+1 with step of 2

Step4: Print the numbers after looping

Step5: Stop

12.a) Describe about the concept of Precedence and Associativity of Operators with example.

Precedence of Python Operators

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

Here 5 - 7 is an expression. There can be more than one operator in an expression.

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.

For example, multiplication has higher precedence than subtraction.

# Multiplication has higher precedence


# than subtraction
>>> 10 - 4 * 2
2

But we can change this order using parentheses () as it has higher precedence than multiplication.

# Parentheses () has higher precedence


>>> (10 - 4) * 2
12

The operator precedence in Python is listed in the following table. It is in descending order (upper group has higher precedence

than the lower ones).

Operators Meaning
() Parentheses

** Exponent

+x, -x, ~x Unary plus, Unary minus, Bitwise NOT

*, /, //, % Multiplication, Division, Floor division, Modulus

+, - Addition, Subtraction

<<, >> Bitwise shift operators

& Bitwise AND

^ Bitwise XOR

| Bitwise OR

==, !=, >, >=, <, <=, is, is not, in, not in Comparisons, Identity, Membership operators

Not Logical NOT

And Logical AND

Or Logical OR

Let's look at some examples:

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.

# Precedence of or & and


meal = "fruit"

money = 0

if meal == "fruit" or meal == "sandwich" and money >= 2:


print("Lunch being delivered")
else:
print("Can't deliver lunch")

Output

Lunch being delivered

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:

# Precedence of or & and


meal = "fruit"

money = 0

if (meal == "fruit" or meal == "sandwich") and money >= 2:


print("Lunch being delivered")
else:
print("Can't deliver lunch")

Output

Can't deliver lunch

Associativity of Python Operators

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

operators have left-to-right associativity.

For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the

left one is evaluated first.

# Left-right associativity
# Output: 3
print(5 * 2 // 3)

# Shows left-right associativity


# Output: 0
print(5 * (2 // 3))

Output

3
0

Note: Exponent operator ** has right-to-left associativity in Python.


# Shows the right-left associativity of **
# Output: 512, Since 2**(3**2) = 2**9
print(2 ** 3 ** 2)

# If 2 needs to be exponated fisrt, need to use ()


# Output: 64
print((2 ** 3) ** 2)

We can see that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).

b.i) Python Keywords and Identifiers


:Python Keywords

Keywords are the reserved words in Python.

We cannot use a keyword as a variable name, function name or any other identifier. They are used to define the syntax and

structure of the Python language.

In Python, keywords are case sensitive.

The list of all the keywords is given below.

False await else import pass

None break except in raise

True class finally is return

And continue for lambda try

As def from nonlocal while

Assert del global not with

Async elif if or yield

Python Identifiers

An identifier is a name given to entities like class, functions, variables, etc. It helps to differentiate one entity from another.

Rules for writing identifiers


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore _. Names

like myClass, var_1 and print_this_to_screen , all are valid example.

2. An identifier cannot start with a digit. 1variable is invalid, but variable1 is a valid name.

3. Keywords cannot be used as identifiers.

global = 1

Output

File "<interactive input>", line 1


global = 1
^
SyntaxError: invalid syntax

4. We cannot use special symbols like !, @, #, $, % etc. in our identifier.

a@ = 0

Output

File "<interactive input>", line 1


a@ = 0
^
SyntaxError: invalid syntax

5. An identifier can be of any length.

ii) what are statements .how are they constructed from variable and expressions in python

Variables, expressions and statements

2.1 Values and types

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.

>>> type('Hello, World!')


<type 'str'>
>>> type(17)
<type 'int'>

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:

>>> print 1,000,000


100

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:

>>> message = "What's up, Doc?"


>>> n = 17
>>> pi = 3.14159

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:

The print statement also works with variables.

>>> print message


What's up, Doc?
>>> print n
17
>>> print pi
3.14159

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'>

The type of a variable is the type of the value it refers to.

2.3 Variable names and keywords

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.

If you give a variable an illegal name, you get a syntax error:

>>> 76trombones = 'big parade'


SyntaxError: invalid syntax
>>> more$ = 1000000
SyntaxError: invalid syntax
>>> class = 'Computer Science 101'
SyntaxError: invalid syntax

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.

Python has twenty-nine keywords:

and def exec if not return


assert del finally import or try
break elif for in pass while
class else from is print yield
continue except global lambda raise

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

produces the output

1
2

Again, the assignment statement produces no output.

2.5 Evaluating expressions

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.

>>> message = 'Hello, World!'


>>> message
'Hello, World!'
>>> print message
Hello, World!

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?

2.6 Operators and operands

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:

20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)

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.

A possible solution to this problem is to calculate a percentage rather than a fraction:

>>> 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.

2.7 Order of operations

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.

2.8 Operations on strings

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):

message-1 'Hello'/123 message*'Hello' '15'+2

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:

print 'Number of minutes since midnight: ', hour*60+minute

You can also put arbitrary expressions on the right-hand side of an assignment statement:

percentage = (minute * 100) / 60

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:

# compute the percentage of the hour that has elapsed


percentage = (minute * 100) / 60

In this case, the comment appears on a line by itself. You can also put comments at the end of a line:

percentage = (minute * 100) / 60 # caution: integer division

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.

percentage = (minute * 100) // 60

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

ii)Write a python code to search a string in the given list.

CHECK STRING IN LIST

l = list(map(input(“Enter strings in list : “).split()))


s = input(“Enter string to be checked: “)
if s in l:
print(f'{s} is present in the list')
else:
print(f'{s} is not present in the list')

13.b.i)outline about function definition and call with example

ABOUT FUNCTION DEFINTION AND CALL

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")

ii)why are functions needed?

The advantages of using functions are:


 Reducing duplication of code
 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding

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:

If you try to print it in IDLE,

>>> print (myTuple);

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.

You can obviously add data of different types in a single tuple,

>>> secondTuple = 1, 2, "python", 4

>>> print (secondTuple);

Output:

(1, 2, "python", 4)
An empty tuple can be created using the tuple() function or by just using an empty bracket ().

>>> emptyTuple = ();

>>> anotherEmptyTuple = tuple();

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,

>>> example = "apple", "orange", "banana", "berry", "mango"

>>> print (example[0]);

Output:

'apple'

In the table below we have marked the tuple elements for both forward and backward indexing:

Value Forward Indexing 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.

>>> print (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:

>>> print ((1, 2, 5, 8) + (2, 9, 4));

Output:

(1, 2, 5, 8, 2, 9, 4)

You can use a tuple(s) to create another tuple.

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:

>>> del (myTuple);

Output:

And myTuple will be deleted from the memory.

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.

Basic Operations and Functions

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)

>>> print (t*3);

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,

>>> t = (2, 5, 0) + (1, 3) + (4,)

>>> print (t);

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

>>> print (len(t))

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:

 if T1 > T2, then cmp(T1, T2) returns 1

 if T1 = T2, then cmp(T1, T2) returns 0

 if T1 > T2, then cmp(T1, T2) returns -1

max() and min() function

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)

>>> print (max(t))

>>> print (min(t))

Output:

14.ii)write a algorithm and program for sorting the numbers in ascending order using merge sort

Algorithm:

Consider we are sorting three numbers in ascending order.


Steps:
 Start.
 Accept three numbers from user (a, b, c).
 If a < b then goto step 4 else goto step 8.
 If a < c then goto step 5 else goto step 7.
 If b < c then goto step 9 else goto step 6.
 Interchange b and c and goto step 9.
 Interchange a and c and goto step 3.
 Interchange a and b and goto step 3.
 Display “Ascending order”.
 Display a, b, c.
 Stop.
Program:

# Python program for implementation of MergeSort

# Merges two subarrays of arr[].

# First subarray is arr[l..m]

# Second subarray is arr[m+1..r]

def merge(arr, l, m, r):

n1 = m - l + 1

n2 = r - m

# create temp arrays

L = [0] * (n1)

R = [0] * (n2)
# Copy data to temp arrays L[] and R[]

for i in range(0, n1):

L[i] = arr[l + i]

for j in range(0, n2):

R[j] = arr[m + 1 + j]

# Merge the temp arrays back into arr[l..r]

i=0 # Initial index of first subarray

j=0 # Initial index of second subarray

k=l # Initial index of merged subarray

while i < n1 and j < n2:

if L[i] <= R[j]:

arr[k] = L[i]

i += 1

else:

arr[k] = R[j]

j += 1

k += 1

# Copy the remaining elements of L[], if there

# are any

while i < n1:

arr[k] = L[i]

i += 1

k += 1

# Copy the remaining elements of R[], if there

# are any

while j < n2:

arr[k] = R[j]

j += 1

k += 1

# l is for left index and r is right index of the


# sub-array of arr to be sorted

def mergeSort(arr, l, r):

if l < r:

# Same as (l+r)//2, but avoids overflow for

# large l and h

m = l+(r-l)//2

# Sort first and second halves

mergeSort(arr, l, m)

mergeSort(arr, m+1, r)

merge(arr, l, m, r)

# Driver code to test above

arr = [12, 11, 13, 5, 6, 7]

n = len(arr)

print("Given array is")

for i in range(n):

print("%d" % arr[i],end=" ")

mergeSort(arr, 0, n-1)

print("\n\nSorted array is")

for i in range(n):

print("%d" % arr[i],end=" ")

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.

Working of open() function

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

# a file named "geek", will be opened with the reading mode.

file = open('geek.txt', 'r')

# This will print every line one by one in the file

for each in file:

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.

Working of read() mode

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

# Python code to illustrate read() mode

file = open("file.txt", "r")

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

# Python code to illustrate read() mode character wise

file = open("file.txt", "r")

print (file.read(5))

Creating a file using write() mode


Let’s see how to create a file and how write mode works:
To manipulate the file, write the following in your Python environment:

 Python3

# Python code to create a file

file = open('geek.txt','w')

file.write("This is the write command")

file.write("It allows us to write in a particular file")

file.close()

The close() command terminates all the resources in use and frees the system of this particular program.

Working of append() mode

Let’s see how the append mode works:

 Python3

# Python code to illustrate append() mode

file = open('geek.txt','a')

file.write("This will add this line")

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

# Python code to illustrate with()

with open("file.txt") as file:


data = file.read()

# do something with data

Using write along with the with() function

We can also use the write function along with the with() function:

 Python3

# Python code to illustrate with() alongwith write()

with open("file.txt", "w") as f:

f.write("Hello World!!!")

split() using file handling

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

# Python code to illustrate split() function

with open("file.text", "r") as file:

data = file.readlines()

for line in data:

word = line.split()

print (word)

b.(i) Explain about how exceptions are handled with example

Python Exception Handling


.

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.

Difference between Syntax Error and Exceptions


Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.

Example:

 Python3

# initialize the amount variable

amount = 10000

# check that You are eligible to

# purchase Dsa Self Paced or not

if(amount > 2999)

print("You are eligible to purchase Dsa Self Paced")

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

# initialize the amount variable

marks = 10000

# perform division with 0

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 Statement – Catching Exceptions

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 program to handle simple runtime error

#Python 3

a = [1, 2, 3]

try:

print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array

print ("Fourth element = %d" %(a[3]))

except:

print ("An error occurred")

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)

Example: Catching specific exception in Python

 Python3

# Program to handle multiple errors with one

# except statement

# Python 3

def fun(a):

if a < 4:

# throws ZeroDivisionError for a = 3

b = a/(a-3)

# throws NameError if a >= 4

print("Value of b = ",

try:

fun(3)

fun(5)

# note that braces () are necessary here for

# multiple exceptions
except ZeroDivisionError:

print("ZeroDivisionError Occurred and Handled")

except NameError:

print("NameError Occurred and Handled")

Output

ZeroDivisionError Occurred and Handled

If you comment on the line fun(3), the output will be

NameError Occurred and Handled

The output above is so because as soon as python tries to access the value of b, NameError occurs.

Try with Else Clause

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.

Example: Try with else clause

 Python3

# Program to depict else clause with try-except

# Python 3

# Function which returns a/b

def AbyB(a , b):

try:

c = ((a+b) / (a-b))

except ZeroDivisionError:

print ("a/b result in 0")

else:

print (c)

# Driver program to test above function

AbyB(2.0, 3.0)
 AbyB(3.0, 3.0)

Output:
-5.0

a/b result in 0

Finally Keyword in Python

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

# Handling of exception (if required)

else:

# execute if no exception

finally:

# Some code .....(always executed)

Example:

 Python3

# Python program to demonstrate finally

# No exception Exception raised in try block

try:

k = 5//0 # raises divide by zero exception.

print(k)

# handles zerodivision exception


except ZeroDivisionError:

print("Can't divide by zero")

finally:

# this block is always executed

# regardless of exception generation.

print('This is always executed')

Output:
Can't divide by zero

This is always executed

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

# Program to depict Raising Exception

try:

raise NameError("Hi there") # Raise Error

except NameError:

print ("An exception")

raise # To determine whether the exception was raised or not

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

Traceback (most recent call last):

File "/home/d6ec14ca595b97bff8d8034bbf212a9f.py", line 5, in <module>

raise NameError("Hi there") # Raise Error

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

# Opening our text file in read only

# mode using the open() function

with open(r'SampleFile.txt','r') as file:

# Reading the content of the file

# using the read() function and storing

# them in a new variable

data = file.read()

# Splitting the data into separate lines

# using the split() function

lines = data.split()

# Adding the length of the

# lines in our number_of_words

# variable

number_of_words += len(lines)

# Printing total number of words

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.

GE8151 DJ 2019 QUESTION PAPER

16 MARK
11. b)

i) Identify the simple startegies for developing an algorithm

Simple strategies for developing algorithms:

• An algorithm is a defined set of step-by-step procedures that provides the

correct answer to a particular problem.

• There are some simple strategies for developing algorithms:

• Iteration

• Recursion

Simple strategies for developing algorithms:

Iteration:

• A sequence that is executed repeatedly so long as a certain condition holds.

• A sequence of statements is executed until a specified condition is true is

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).

• That sequence could, for example, be a list.

• 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

from the list words from beginning to end.

• Syntax of for loop:

FOR( start-value to end-value) DO


Statement

...

ENDFOR

1.7 Simple strategies for developing algorithms:

Iteration:

• for loop: example 1:

• # This prints out the length of each word in a list of words

words = [‘my’, ‘big’, ‘meal’, ‘comes’, ‘mostly’, ‘bearing’, ‘doubtful’,

‘garnishes’]

for word in words:

# The following line prints the length of the word

print(len(word))

# Prints: 2 3 4 5 6 7 8 9

• for loop:

example 2:

• if you know exactly how many iterations to execute, a range:

for number in range(1, 13):

print(number * 42)

# Prints out the 42 times table

• for loop:

example 3:

Print n natural numbers

BEGIN

GET n

INITIALIZE i=1

FOR (i<=n) DO
PRINT i

i=i+1

ENDFOR

END

While loop:

• The while loop executes a block of instructions repeatedly for as long as

some condition evaluates to true.

• The value of the condition is only checked at the beginning of each

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:

• Syntax of 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

while age != guess:

# 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.

guess = int(input(‘Guess how old I am> ‘))

11.b)

ii) write an algorithm to insert a card into a list of sorted cards

STEP1:Start

STEP2:If the element is the first one, it is already sorted.

STEP3:Move to the next element of the list.

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.

STEP6:Insert the value at the correct position.

STEP7:Repeat until the complete list is sorted.

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

Compiler & Interpreter – Block Diagram

INTERPRETER
Compiler vs Interpreter

PYTHON INTERPRETER:
* Python is considered an interpreted language because Python programs are executed by an interpreter.

* There are two ways to use the interpreter:

i) interactive mode

ii) script mode.

PYTHON INTERACTIVE MODE:


* In interactive mode, you type Python programs, and the interpreter displays the result.

* The interpreter prints a welcome message stating its version number and a copyright notice before printing
the first prompt:

PYTHON INTERACTIVE MODE


 In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (>>>)
(also known as Chevron)
PYTHON INTERACTIVR MODE :

*For continuation lines it prompts with the secondary prompt, by default three dots (…)

PYTHON SCRIPT MODE:


*First write a Python program inside a file (like a script) in the script mode, and then we execute the file after saving it
in our system.

*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.

Python strings are immutable, but only sometimes

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"

x = "goodbye" # New string!

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!

This is wrong. Sort of.

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)

i. Methods of Traversing Lists

Here are the methods which one can refer to for traversing lists in Python:

 Python range () method

 List Comprehension

 Python enumerate () method

 Lambda function

 Python NumPy module

 By using a for Loop

 By using a while Loop

Using For Loop

list = [2, 4, 6, 8, 10]


for i in list:
print(i)

Output:

2
4
6
8
10

Using For Loop and Range ()

If you wish to use the traditional for loop which iterates from number x to number y.

list = [2, 4, 6, 8, 10]


length = len(list)
for i in range(length):
print(list[i])

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).

Using While Loop

list = [2, 4, 6, 8, 10]


length = len(list)
i=0
while i < length:
print(list[i])
i += 1

Output:

2
4
6
8
10

Using List Comprehension

This one is possibly the most concrete way.

list = [2, 4, 6, 8, 10]


[print(i) for i in list]

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.

import numpy as toppr


a = toppr.arange(9)
a = a.reshape(3, 3)
for x in toppr.nditer(a):
print(x)

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.

Using Lambda Function

Lambda functions in Python are essentially anonymous functions.

Syntax:

Lambda parameters: expression

 expression: The iterable which is to be evaluated.


The lambda function along with a Python map() function can come in use for traversing lists easily.

Python map () method accepts a function as a parameter and returns a list.

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:

lst = [20, 40, 85, 93, 99, 85, 31]

res = list(map(lambda x:x, lst))

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:

[20, 40, 85, 93, 99, 85, 31]

14.b). Difference Between List and Tuple in Python:


SR.NO.
LIST TUPLE

Lists are mutable Lists are mutable


1.
2. Implication of iterations is Time- The implication of iterations is
consuming comparatively Faster

3. The list is better for performing Tuple data type is appropriate for
operations, such as insertion and accessing the elements
deletion.

4. Lists consume more memory Tuple consume less memory as


compared to the list

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

15.A.(ii).DISCUSS ABOUT THE USE OF FROMAT OPERATOR IN FILE PROCESSING

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

Single Place Holder

Multiple Place Holder

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:

The '%' character, which marks the start of the specifier.

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.

Length modifier (optional).


Conversion type.

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:

>>> print('%(language)s has %(number)03d quote types.' %

{'language': "Python", "number": 2})

In this case no * specifiers may occur in a format (since they require a sequential parameter list).

The conversion flag characters are:

Flag Meaning

The value conversion will use the “alternate form” (where defined below).

'#'

'0' The conversion will be zero padded for numeric values.

'-' 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

– so e.g. %ld is identical to %d.

The conversion types are:

Conversion Meaning

'd' Signed integer decimal.

'i' Signed integer decimal.

'o' Signed octal value.

'u' Obsolete type – it is identical to 'd'.

'x' Signed hexadecimal (lowercase).

'X' Signed hexadecimal (uppercase).

'e' Floating point exponential format (lowercase).


'E' Floating point exponential format (uppercase).

'f' Floating point decimal format.

'F' Floating point decimal format.

'g' Floating point format. Uses lowercase exponential format if exponent is less than -4

or not less than precision,decimal format otherwise.

'G' Floating point format. Uses uppercase exponential format if exponent is less than -4

or not less than precision, decimal format otherwise.

'c' Single character (accepts integer or single character string).

'r' String (converts any Python object using repr()).

's' String (converts any Python object using str()).

'a' String (converts any Python object using ascii()).

'%' No argument is converted, results in a '%' character in the result.

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.

*If precision is N, the output is truncated to N characters.

15.b. DESCRIBE HOW EXCEPTIONS ARE HANDLED IN PYTHON WITH EXAMPLES

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:

... x = int(input("Please enter a number: "))

... break

... except ValueError:

... print("Oops! That was no valid number. Try again...")

...

The try statement works as follows.

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:

... except (RuntimeError, TypeError, NameError):

... 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

for cls in [B, C, D]:

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 OSError as err:

print("OS error: {0}".format(err))

except ValueError:

print("Could not convert data to an integer.")

except BaseException as err:

print(f"Unexpected {err=}, {type(err)=}")

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:

for arg in sys.argv[1:]:

try:

f = open(arg, 'r')

except OSError:

print('cannot open', arg)

else:

print(arg, 'has', len(f.readlines()), 'lines')

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:

... raise Exception('spam', 'eggs')

... except Exception as inst:

... print(type(inst)) # the exception instance

... print(inst.args) # arguments stored in .args

... print(inst) # _str_ allows args to be printed directly,

... # but may be overridden in exception


subclasses

... x, y = inst.args # unpack args

... print('x =', x)

... print('y =', y)

...

<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:

>>> def this_fails():

... x = 1/0

...

>>> try:

... this_fails()

... except ZeroDivisionError as err:

... print('Handling run-time error:', err)

...

Handling run-time error: division by

You might also like