Вы находитесь на странице: 1из 52

GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING

QUESTION BANK
(NOTE: THIS IS PURELY BASED ON ANNA UNIVERSITY QUESTION PAPERS FOR
THE YEAR DEC/JAN ’19, JAN ’18, APR/MAY ’19 ONLY, NOT COMPLETE SYLLABUS)

UNIT - 1

PART A

1. Distinguish between algorithm and program.(Dec/Jan’19)

Algorithm Program
Algorithm is aSystematic logical Program is exact code written for
approach which is a well-defined, problem following all the rules of the
step-by-step procedure that allows programming language.
a computer to solve a problem.
Example Example
Step 1: Start print(“Welcome”)
Step 2: Print “Welcome”
Step 3: End

2. Write an algorithm to find the minimum number in a given list of numbers.(Dec/Jan’19)

Algorithm:
Step 1: Start
Step 2 : Read list of n elements
Step 3: Assign min= list [0]
Step 3 :for i in range 1 to n, repeat step 4
Step 4: list [i] < min then min=list [i]
Step 5: return min
Step 6: Stop

3. What is an algorithm?(Jan ’18)


Definition:
 Algorithm is defined as “a sequence of instructions designed in such a way that if the
instructions are executed in the specified sequence, the desired result will be obtained”.
 Algorithm is a Systematic logical approach which is a well-defined, step-by-step procedure
that allows a computer to solve a problem
 It is also defined as “any problem whose solution can be expressed in a list of executable
instruction”.
Example: Algorithm to print Welcome message
Step 1: Start
Step 2: Print “Welcome”
Step 3: End

1
4. Write an algorithm to accept two numbers, compute the sum and print the result.(Jan ’18)

STEP 1: Start
STEP 2: Read a
STEP 3: Read b
STEP 4: c=a+b
STEP 5: Write c
STEP 6: Stop

5. List the symbols used in drawing the flowchart. (April/May-19)

6. What are keywords? Give examples.(Dec/Jan’19)


 Keywords are the reserved words in Python.
 We cannot use a keyword as variable name, function name or any other identifier.
 In Python, keywords are case sensitive.
 They are used to define the syntax and structure of the Python language.

Example keywords in Python Programming


true, false, class, is, finally, return, if, else, elif, while, import,break,and,or,not

7. Define recursive function.(April/May-19) / Define recursion with an example. (Dec/Jan’19)


 A recursive function is a function that calls itself during its execution.
 This enables the function to repeat itself several times, outputting the result and the end of
each iteration.
 Recursive functions are common in computer science because they allow programmers to
write efficient programs using a minimal amount of code.

Example of a recursive function.


 Towers of Hanoi (TOH) and finding the Factorial of a given number

2
8. Give the python code to find the minimum among the list of 10 numbers.(April/May-19)

list=[2,4,56,27,89,100,23,44,55,67]
min=list[0]
for i in range(0,len(list)):
if (list[i]<min):
min=list[i]
print(“The minimum among the list of numbers is: “,min)

PART B

1. Mention the different types of iterative structure allowed in Python. Explain the use of continue and
break statements with an example.(16) (April/May-19).
Iterations:

A sequence of statements is executed until a specified condition is true is called iterations.

 For loop
 While loop

Syntax for For: Example: Print n natural numbers


BEGIN GET n
FOR( start-value to end-value) DO INITIALIZE i=1 FOR (i<=n) DO PRINT
statement i
... ENDFOR i=i+1 ENDFOR END

Syntax for While: Example: Print n natural numbers


BEGIN GET n
WHILE (condition) DO statement INITIALIZE i=1 WHILE(i<=n) DO
... PRINT i
ENDWHILE i=i+1
ENDWHILE END

3
Difference between break and continue:
Break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement transfer the control to the next iteration
outside the loop. in the loop.
syntax: syntax:
break continue
for i in "welcome": for i in “welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w w
e e
l l
o
m
e
2. What is an algorithm? Summarize the characteristics of a good algorithm.(8)(April/May-19)

Algorithm Definition:
It is defined as a sequence of instructions that describe a method for solving a problem. In
other words it is a step by step procedure for solving a problem.

Qualities Of A Good Algorithm

The following are the primary factors that are often used to judge the quality of the algorithms.
Time – To execute a program, the computer system takes some amount of time. The lesser is the time
required, the better is the algorithm.
Memory – To execute a program, computer system takes some amount of memory space. The lesser is the
memory required, the better is the algorithm.
4
Accuracy – Multiple algorithms may provide suitable or correct solutions to a given problem, some of these
may provide more accurate results than others, and such algorithms may be suitable.

Example: Write an algorithm to print „Good Morning”


Step 1: Start
Step 2: Print “Good Morning”
Step 3: Stop

3. Outline the algorithm for displaying the first n odd numbers(8)(April/May-19)

Odd number means the number which is not divided by 2, so the n natural
numbers are considered and they checked whether it is divided by 2 or not then
the non divisible number is printed.

Step 1: Start
Step 2: Read n
Step 3: Repeat Step 4 until i<n
Step 4: Check if (i%2!=0) then print i and i=i+1
Step 5: Stop

4. Discuss about the building blocks of algorithms.(8)(Dec/Jan’19)

Building Blocks Of Algorithms:


Algorithms can be constructed from basic building blocks namely,
1. Statements
2. State
3. Control flow
4. Functions
1. STATEMENTS:
Statement is a single action in a computer. In a computer statements might include some of the
following actions
input data-information given to the program
process data-perform operation on a given input
output data-processed result
State:
Transition from one process to another process under specified condition with in a time is called
state.

2.CONTROL FLOW:
The process of executing the individual statements in a given order is called control flow.
The control can be executed in three ways
a. sequence
b. selection
c. iteration

a. Sequence:
All the instructions are executed one after another is called sequence execution.

5
Example:
Add two numbers:
Step 1: Start
Step 2: get a,b
Step 3: calculate c=a+b
Step 4: Display c
Step 5: Stop

b. Selection:
A selection statement causes the program control to be transferred to a specific part of the program
based upon the condition.
If the conditional test is true, one part of the program will be executed, otherwise it will execute the
other part of the program.

Example
Write an algorithm to check whether he is eligible to vote?
Step 1: Start
Step 2: Get age
Step 3: if age >= 18 print “Eligible to vote”
Step 4: else print “Not eligible to vote”
Step 6: Stop

c. Iteration:
In some programs, certain set of statements are executed again and again based upon conditional test.
i.e. executed more than one time. This type of execution is called looping or iteration.

Example
Write an algorithm to print all natural numbers up to n
Step 1: Start
Step 2: get n value.
Step 3: initialize i=1
Step 4: if (i<=n) go to step 5 else go to step 7
Step 5: Print i value and increment i value by 1
Step 6: go to step 4
Step 7: Stop

6
3.FUNCTIONS:
Function is a sub program which consists of block of code(set of instructions) that performs a
particular task. For complex problems, the problem is been divided into smaller and simpler tasks during
algorithm design
Benefits of Using Functions
 Reduction in line of code
 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability

5. Identify the simple strategies for developing an algorithm.(8)(Dec/Jan’19) / Write a Python program
to find the factorial of a given number without recursion and with recursion.(8)(Jan’18)

SIMPLE STRATEGIES FOR DEVELOPINGALGORITHMS:

1. iterations
2. Recursions

1. Iterations:

A sequence of statements is executed until a specified condition is true is called iterations.

 For loop
 While loop

Syntax for For: Example: Print n natural numbers


BEGIN GET n
FOR( start-value to end-value) DO INITIALIZE i=1 FOR (i<=n) DO PRINT
statement i
... ENDFOR i=i+1 ENDFOR END

Syntax for While: Example: Print n natural numbers


BEGIN GET n
WHILE (condition) DO statement INITIALIZE i=1 WHILE(i<=n) DO
... PRINT i
ENDWHILE i=i+1
ENDWHILE END

7
2. Recursions:
A function that calls itself is known as recursion. Recursion is a process by which a function calls
itself repeatedly until some specified condition has been satisfied.

Algorithm for factorial of n numbers using recursion:


Main function:
Step1: Start
Step2: Get n
Step3: call factorial(n)
Step4: print fact
Step5:Stop

Sub function factorial(n):

Step1: if(n==1) then fact=1 return fact


Step2: else fact=n*factorial(n-1) and return fact

8
Pseudo code for factorial using recursion:
Main function:
BEGIN GET n
CALL factorial(n)
PRINT fact

Sub function factorial(n):

IF(n==1) THEN
fact=1 RETURN fact
ELSE
RETURN fact=n*factorial(n-1)

6. Write an algorithm to insert a card into a list of sorted cards.(8)(Dec/Jan’19)

Step 1: Start
Step 2: get a list a
Step 3: for each element (i) in a goto step4 else goto step 8
Step 4: get the index of i assign it to j and goto step 5
Step 5: while (j>0) got to step6 else goto step3
Step 6: if(a[j-1]>a[j]) then swap a[j],a[j-1] and goto step7 else goto step7
Step 7: decrement j value and goto step 5
Step 8: Print the list a
Step 9: Stop

7. Draw a flowchart to accept three distinct numbers, find the greatest and print the result.(8)(Jan’18)

9
8. Draw a flowchart to find the sum of the series 1+2+3+4+5+…..+100. (8)(Jan’18)

9. Outline the Towers of Hanoi problem. Suggest a solution to the Towers of Hanoi problem with
relevant diagrams.(16)(Jan’18) / Write a recursive algorithm, to solve towers of Hanoi
problem.(8)(Dec/Jan’19)

Towers of Hanoi definition:


A tower of Hanoi is a mathematical puzzle with three rods and n number of discs. The
mission is to move all the disks to some another tower without violating the sequence of
arrangement.

A few rules to be followed for Tower of Hanoi:


1. Only one disk can be moved among the towers at any given time.
2. Only the "top" disk can be removed.
3. No large disk can sit over a small disk

No of efficient moves = 2n – 1

10
Algorithm for tower of hanoii:
Step 1 − Move n-1 disks from source to aux
Step 2 − Move nth disk from source to dest
Step 3 − Move n-1 disks from aux to dest

Pseduocode for tower of Hanoi:


BEGIN Function Hanoi (n, source, dest, aux)
IF n == 1, THEN move n from source to dest
ELSE Hanoi (n - 1, source, aux, dest)
END IF
END Function

11
UNIT - 2

PART A

1. State the reasons to divide programs into function (Dec/Jan’19).


The reasons to divide programs into function
 A function is a group of statements that together perform a task
 Writing functions avoids rewriting the same code over and over.
 Using functions it becomes easier to write programs and keep track of what they are doing.
 If the operation of a program can be divided into separate activities, and each activity placed
in a different function, then each could be written and checked more or less independently.
 Separating the code into modular functions also makes the program easier to design and
understand.

2. Name the four types of scalar objects Python has.(Jan ’18)

A scalar is a type that can have a single value such as 5, 3.14, or ‘Bob’.

Type Example Description


int x=1 integers (i.e., whole numbers)
float x = 1.0 floating-point numbers (i.e., real numbers)
Complex numbers (i.e., numbers with real and
complex x = 1 + 2j
imaginary part)
bool x = True Boolean: True/False values
str x = 'abc' String: characters or text

3. What is tuple? How literals of type tuples are written? Give example.(Jan ’18)
Tuple
 A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists.
 The differences between tuples and lists are, the tuples cannot be changed unlike lists
 Tuples use parentheses,.()
 Creating a tuple is as simple as putting different comma-separated values

Example
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();

Tuple literals
Literals can be defined as a data that is given in a variable or constant.

 (), (1,), (1,2) (tuple literals)

12
4. Outline the logic to swap the contents of two identifiers without using the third variable. (April/May-
19)

Logic to swap the contents of two identifiers without using the third variable.
In Python, there is a simple construct to swap variables. The following code does the same as above
but without the use of any temporary variable.
x=5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)
Output:
x=10
y=5

PART B

1. Sketch the structures of interpreter and compiler. Detail the differences between them. Explain how
Python works in interactive mode and script mode with examples. (2+2+4) (Dec/Jan’19)

The difference between an interpreter and a compiler is given below:

Interpreter Compiler

Translates program one statement at a Scans the entire program and translates
time. it as a whole into machine code.

It takes less amount of time to analyze It takes large amount of time to analyze
the source code but the overall the source code but the overall
execution time is slower. execution time is comparatively faster.

Generates intermediate object code


No intermediate object code is which further requires linking, hence
generated, hence are memory efficient. requires more memory.

Continues translating the program until It generates the error message only after
the first error is met, in which case it scanning the whole program. Hence
stops. Hence debugging is easy. debugging is comparatively hard.

Programming language like Python, Programming language like C, C++ use


Ruby use interpreters. compilers.

Python Interpreter is a program that reads and executes Python code.


It uses 2 modes of Execution.
1. Interactive mode
2. Script mode Interactive mode:

13
Interactive mode Script mode
A way of using the Python interpreter A way of using the Python interpreter
by typing commands and expressions at to read and execute statements in a
the prompt. script.
Can’t save and edit the code Can save and edit the code

We can see the results immediately. We can’t see the code immediately.

Example: >>> 1 + 1 Example-stud.py


2 name=”XXX”
age=18
marks=[80,90,100,90,100]
print(“Name:“,name,”Age: “,age,”Marks:
“,marks)
To execute press F5 key or select run
module.
Output
Name: XXX Age: 18 Marks:
80,90,100,90,100

Advantages: Advantages:
1. Python, in interactive mode, is good 1. It is easy to run large pieces of code.
enough to learn, experiment or 2. Editing your script is easier in script
explore. mode.
2. Working in interactive mode is 3. Good for both beginners and
convenient for beginners and for experts
testing small pieces of code
3. Describe about the concept of precedence and associativity of operators with example.(16)(April/May-19)
/ Outline the operator precedence of arithmetic operators in Python.(6)(Jan’18) / Summarize the
precedence of mathematical operators in Python.(8)(Dec/Jan’19)

OPERATOR PRECEDENCE:

When an expression contains more than one operator, the order of evaluation
depends on the order of operations.

Operator Description

** Exponentiation (raise to the power)

Complement, unary plus and minus


~+-
(method names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

+- Addition and subtraction

14
>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators


= %= /= //= -=
Assignment operators
+= *= **=
is is not Identity operators

in not in Membership operators

not or and Logical operators

-For mathematical operators, Python follows mathematical convention.


-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction).

Example python program:


a = 20
b = 10
c = 15
d=5
e=0

e = (a + b) * c / d #( 30 * 15 ) / 5
print(e)

e = ((a + b) * c) / d # (30 * 15) / 5


print(e)

e = (a + b) * (c / d); # (30) * (15/5)


print(e)

e = a + (b * c) / d; # 20 + (150/5)
print(e)

When you execute the above program, it produces the following result
90
90
90
50

15
4. Mention the list of keywords available in Python. Compare it with variable name.(8)(April/May-19)

KEYWORDS:
 Keywords are the reserved words in Python.
 We cannot use a keyword as variable name, function name or any
other identifier.
 They are used to define the syntax and structure of the Python language.
 Keywords are case sensitive.

 A variable allows us to store a value by assigning it to a name, which can be used later.
 Named memory locations to store values.
 Programmers generally choose names for their variables that are meaningful.
 It can be of any length. No space is allowed.
 We don't need to declare a variable before using it. In Python, we simply assign a value to
a variable and it will exist.

Assigning value to variable:

Value should be given on the right side of assignment operator(=) and variable on left side.
>>>counter =45
print(counter)

Assigning a single value to several variables simultaneously:

>>> a=b=c=100
Assigning multiple values to multiple variables

5. Appraise the arithmetic operators in Python with an example.(12)(Jan’18)

Arithmetic operators:
They are used to perform mathematical operations like addition, subtraction, multiplication etc.

Assume, a=10 and b=5

16
Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30


Subtracts operand. Right hand operand from left
- Subtraction a – b = -10
hand
* Multiplication Multiplies values on either side of the operator a * b = 200
Divides left hand operand by right hand
/ Division b/a=2
operand
Divides left hand operand by right hand
% Modulus b%a=0
operand and returns remainder
Performs operators exponential (power) a**b =10 to
** Exponent
calculation on the power 20

Floor Division - The division of operands


// where the result is the quotient in which the 5//2=2
digits after the decimal point are removed
Examples
a=10
b=5 print("a+b=",a+b) print("a-b=",a-b) print("a*b=",a*b) print("a/b=",a/b) print("a%b=",a%b)
print("a//b=",a//b) print("a**b=",a**b)
Output:
a +b=15
a-b= 5
a*b= 50
a/b= 2.0
a%b=0
a//b=2
a**b= 100000

6. Write a Python function to swap the values of two variables.(4)(Dec/Jan’19)

a = int(input("Enter a value "))


b = int(input("Enter b value"))
c=a
a=b
b=c
print("a=",a, "b=",b,)

Output:
Enter a value 5
Enter b value 8
a=8
b=5

17
UNIT - 3

PART A

1. Write a python program to accept two numbers, multiply them and print the result. (Jan ’18)

number1 = int(input("Enter first number: "))


number2 = int(input("Enter second number: "))
mul = number1 * number2
print("Multiplication of given two numbers is: ", mul)
Input
Enter first number: 22
Enter second number: 5
Output:
Multiplication of given two numbers is: 110

2. Write a Python program to accept two numbers,find the greatest and print the result. (Jan ’18)

num1=int(input("Enter the first number:"))


num2=int(input("Enter the second number:"))
if num1>=num2:
large=num1
else:
large=num2
print("The largest number is:",large)

Output:
Enter the first number:5
Enter the second number:10
The largest number is: 10

3. Present the flow of execution for a while statement. (Dec/Jan’19)

The while loop in Python is used to iterate over a block of code as


long as the test expression (condition) is true.

Syntax of while Loop in Python:


while test_expression:
Body of while

18
 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 testexpression evaluates to False.
 In Python, the body of the while loop is determined through indentation.
 Body starts with indentation and the first unindented line marks the end.
 Python interprets any non-zero value as True. None and 0 are interpreted as False.

4. State the logical operators available in python language with example. (April/May-19)

Logical operators are the and, or, not operators.

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Example:
a = True
b = False
print(('a and b is', a and b))
print(('a or b is', a or b))
print(('not a is', not a))

Output:
false
true
false

5. Comment with an example on the use of local and global variable with the same identifier name.
(April/May-19)
Global and Local variables
 There are two types of variables: global variables and local variables.
A global variable can be reached anywhere in the code, a local only in the scope.

Use of local and global variable with the same identifier name
def f():
s = "I love London!" # Local Variable
print(s)
s = "I love Paris!" #Global Variable Output looks like this:
f() I love London!
print(s) I love Paris!

19
PART B

1. Appraise with an example nested if and elif header in Python.(6) / List the three types of conditional
statements and explain them.(16)(Dec/Jan’19)

CONDITIONALS
1. Conditional if
2. Alternative if…else
3. Chainedif…elif…else
4. Nestedif….else

Conditional if:
conditional (if) is used to test a condition, if the condition is true the statements inside if will
be executed.

syntax:

Flowchart:

Example:
Program to provide discount rs 500, if the purchase amount is greater than 2000.

Program to provide flat rs 500, if the purchase amount is output


greater than 2000.
purchase=eval(input(“enter your purchase amount”)) enter your purchase
if(purchase>=2000): amount
purchase=purchase-500 2500
print(“amount to pay”,purchase) amount to pay
2000

20
alternative(if-else):
In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes when
the condition is false. If the condition is true statements inside the if get executed otherwise
else
part gets executed. The alternatives are called branches, because they are branches in the flow
of execution.

syntax:

Flowchart:

Examples:
Odd or even number Output
n=eval(input("enter a number")) enter a number 4 even number
if(n%2==0):
print("even number")
else:
print("odd number")

Chained conditionals (if-elif-else):


 The elif is short for elseif.
 This is used to check more than one condition.
 If the condition1 is False, it checks the condition2 of the elif block. If all the conditions
are False, then the else part isexecuted.
 Among the several if...elif...else part, only one part is executed according to the
condition.
The if block can have only one else block. But it can have multiple elif blocks.

21
Example:
Student mark system

student mark system Output


mark=eval(input("enter ur mark:")) enter ur mark:78 grade:B
if(mark>=90):
print("grade:S") elif(mark>=80):
print("grade:A") elif(mark>=70):
print("grade:B") elif(mark>=50):
print("grade:C") else:
print("fail")

22
Nested conditionals:

One conditional can also be nested within another. Any number of condition can be nested
inside one another. In this, if the condition is true it checks another if condition1. If both the
conditions are true statement1 get executed otherwise statement2 get execute. if the condition is false
statement3 gets executed

Example:
greatest of three numbers output
a=eval(input(“enter the value of a”)) enter the value of a 9 enter the value of a
b=eval(input(“enter the value ofb”)) 1
c=eval(input(“enter the value of c”)) enter the value of a 8 the greatest no is 9
if(a>b):
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
2. Explain with an example while loop, break statement and continue statement in Python.(10)(Jan’18)

23
While loop:

While loop statement in Python is used to repeatedly executes set of statement as long as a given
condition is true.

In while loop, test expression is checked first. The body of the loop is entered only if the
test_expression is 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.

The statements inside the while starts with indentation and the first unindented line marks the
end.
Syntax

While loop Flowchart

While loop –Example:


Sum of n numbers: output
n=eval(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)

Difference between break and continue:

24
Break continue
It terminates the current loop and It terminates the current iteration and
executes the remaining statement transfer the control to the next iteration
outside the loop. in the loop.

syntax: syntax:
break continue
for i in "welcome": for i in “welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)

w w

e e

l l

3. Analyze string slicing. Illustrate how it is done in Python with example.(8)(April/May-19)


List slicing is an operation that extracts a subset of elements from an list and
packages them as another list.

Syntax:
Default start value is 0
Default stop value is n-1
Listname[start:stop]
Listname[start:stop:steps]
slices example description
>>> a=[9,8,7,6,5,4]
>>> a[0:3] Printing a part of a list from 0 to 2.
a[0:3] [9, 8, 7]
>>> a[:4] Default start value is 0. so
a[:4] [9, 8, 7, 6] prints from 0 to 3
>>> a[1:] default stop value will be
a[1:] [8, 7, 6, 5, 4] n-1. so prints from 1 to 5
>>> a[:] Prints the entire list.
a[:] [9, 8, 7, 6, 5, 4]
>>> a[2:2] print an empty slice
a[2:2] []
25
>>> a[0:6:2] Slicing list values with step
a[0:6:2] [9, 7, 5] size 2.
>>> a[::-1] Returns reverse of given list
a[::-1] [4, 5, 6, 7, 8, 9] values

4. Write a Python code to search a string in the given list.(8)(April/May-19)

def search(list,n):
for i in range(len(list)):
if list[i] == n:
return True
return False

# list which contains both string and numbers.


list = [1, 2, 'sachin', 4,'Geeks', 6]

# Driver Code
n = 'Geeks'

if search(list, n):
print("Found")
else:
print("Not Found")

5. Outline about function definition and call with example.(10)(April/May-19)

Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.

 def keyword is used to define a function.


 Give the function name after def keyword followed by parentheses in which
arguments are given.
 End with colon(:)
 Inside the function add the program statements to be executed
 End with or without return statement

Syntax:

26
def fun_name(Parameter1,Parameter2…Parameter n): statement1
statement2…
statement n return[expression]

def my_add ( a,b) :


c=a+b
return c

Function Calling: (Main Function)

 Once we have defined a function, we can call it from another function, program or even
the Pythonprompt.
 To call a function we simply type the function name with appropriate arguments.

Example:
x=5 y=4
my_add(x,y)

 The order in which statements are executed is called the flow ofexecution
 Execution always begins at the first statement of theprogram.
 Statements are executed one at a time, in order, from top tobottom.
 Function definitions do not alter the flow of execution of the program, but remember that
statements inside the function are not executed until the function is called.
 Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it leftoff.

Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of execution.
This means that you will read the def statements as you are scanning from top to bottom, but you should
skip the statements of the function definition until you reach a point where that function is called.

Function Definition and Function Call

def add(): #Function Definition


a=int(input("enter a")) b=int(input("enter b"))
c=a+b
print(c) add()#Function Call
OUTPUT:
enter a 5
enter b 10
15

27
6. Why are functions needed?(6)(April/May-19)

 Function is a sub program which consists of set of instructions used to perform a specific task.
A large program is divided into basic building blocks called function.

Need For Function:


 When the program is too complex and large they are divided into parts. Each part is separately
coded and combined into single program. Each subprogram is called as function.
 Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.
 Functions are used to avoid rewriting same code again and again in a program.
 Function provides code re-usability
 The length of the program is reduced.

7. Explain the syntax and structure of user defined functions in Python with examples. Also discuss
about parameter passing in functions.(12)(Dec/Jan’19)

Types of function:
Functions can be classified into two categories:
 User defined function
 Built in function
i) Built in functions
Built in functions are the functions that are already created and stored in python.
These built in functions are always available for usage and accessed by a programmer. It cannot
be modified.
>>>max(3,4) 4 # returns largest element

>>>min(3,4) 3 # returns smallest element

>>>len("hello") 5 #returns length of an object

(ii)User Defined Functions:


 User defined functions are the functions that programmers create for their requirement and
use.
 These functions can then be combined to form module which can be used in other programs
by importing them.
Advantages of user defined functions:
 Programmers working on large project can divide the workload by making different
functions.
 If repeated code occurs in a program, function can be used to include those codes and
execute when needed by calling that function.
Example
def add(): #Function Definition
a=int(input("enter a")) b=int(input("enter b")) c=a+b

28
print(c) add()#Function Call

Parameters And Arguments:


Parameters:
 Parameters are the value(s) provided in the parenthesis when we write function header.
 These are the values required by function towork.
 If there is more than one value required, all of them will be listed in parameter list separated
bycomma.
 Example: defmy_add(a,b):
Arguments :
 Arguments are the value(s) provided in function call/invokestatement.
 List of arguments should be supplied in same way as parameters arelisted.
 Bounding of parameters to arguments is done 1:1, and so there should be same number and
type of arguments as mentioned in parameterlist.
 Example:my_add(x,y)

8. Python strings are immutable. Justify with an example.(8)(Dec/Jan’19)

Strings:
 String is defined as sequence of characters represented in quotation marks (either single
quotes ( ‘ ) or double quotes ( “).
 An individual character in a string is accessed using aindex.
 The index should always be an integer (positive ornegative).
 A index starts from 0 ton-1.
 Python will get the input at run time by default as astring.
 Python does not support character data type. A string of size 1 can be treated as characters.
1. singlequotes(' ')
2. double quotes ("")
3. triple quotes(“””“”””)

Strings are immutablei.e. the contents of the string cannot be changed after it is created.

Immutability:
 Python strings are “immutable” as they cannot be changed after they are created.
 Therefore [ ] operator cannot be used on the left side of an assignment.

operations Example output


element assignment a="PYTHON" TypeError: 'str' object does not support
a[0]='x' element assignment

element deletion a=”PYTHON” TypeError: 'str' object


del a[0] doesn't support element
deletion

29
delete a string a=”PYTHON” NameError: name 'my_string'
del a is not defined

9. Write a Python code to perform binary search. Trace it with an example of your
choice.(8)(Dec/Jan’19)

Python code to perform binary search


a=[20, 30, 40, 50, 60, 70, 89]
print(a)
search=eval(input("enter a element to search:")) start=0
stop=len(a)-1 while(start<=stop):
mid=(start+stop)//2
if(search==a[mid]):
print("elemrnt found at",mid+1)
break
elif(search<a[mid]):
stop=mid-1
else:
start=mid+1 else:
print("not found")
Output 1
[20, 30, 40, 50, 60, 70, 89]
Enter a element to search:30
element found at 2
Output 2
[20, 30, 40, 50, 60, 70, 89]
Enter a element to search:10
not found

30
31
10) What is a numeric literal? Give examples.(4)(Jan’18)
Numeric literals:
 Numeric Literals are immutable.
 Numeric literals can belong to following four different numerical types.
Int(signed integers)
 Numbers( can be both positive and negative) with no fractional part.

Example: 100
Long(long integers)
Integers of unlimited size followed by lowercase or uppercase L

Example: 87032845L
float(floating point)
Real numbers with both integer and fractional part
Example -26.2
Complex(complex)
In the form of a+bj where a forms the real part and b forms the imaginary part of complex
number.
Example : 3.14j

11.Write a Python program using function to find the sum of first ‘n’ even numbers and print the
result.(6)(Jan’18)

Sum of first n even numbers


Given a number n. The problem is to find the sum of first n even numbers.
Examples:
Input: n = 4
Output : 20
Sum of first 4 even numbers
= (2 + 4 + 6 + 8) = 20

Input : n = 20
Output : 420
Python program using function to find the sum of first ‘n’ even numbers and print the
result.
n=int(input("Enter n value:"))
sum=0
for i in range(2,n+1,2):
sum+=i
print(sum)

Input:5
Output:
6(2+4)

32
12. Write a Python program to generate 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.(8)(Jan’18)
Fibonacci numbers
 A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8....
 The first two terms are 0 and 1.
 All other terms are obtained by adding the preceding two terms.
 This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Python program to generate first ‘N’ Fibonacci numbers
a=0
b=1
n=eval(input("Enter the number of terms: "))
print("Fibonacci Series: ")
print(a,b)
for i in range(1,n,1):
c=a+b
print(c)
a=b
b=c
Output
Enter the number of terms: 6 Fibonacci Series:
01
1
2
3
5
8

33
UNIT - 4

PART A

1. What is a list? How list differs from tuples?(Jan.’18)

List Definition:
A list is a collection which is ordered and changeable. In Python lists are written with square
brackets.

Example
#Create a List:
list = ["apple", "banana", "cherry"]
print(list)

2. How to create a list in Python? Illustrate the use of negative indexing . (April/May 2019)

Creation of list:
A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas.
It can have any number of items and they may be of different types (integer, float, string etc.).

# empty list
my_list = []

# list of integers
my_list = [1, 2, 3]

Negative indexing of list with example


Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to
the second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1])
# Output: e
print(my_list[-5])
# Output: p

3. How to slice a list in Python? (Jan.’18)

Slice lists in Python


 List slicing is a computationally fast way to methodically access parts of given data.
Syntax: Listname [start:end:step]
where : end represents the first value that is not in the selected slice.

34
The difference between end and start is the number of elements selected (if step is
1, the default).The start and end may be a negative number. For negative
numbers, the count starts from the end of the array instead of the beginning.

We can access a range of items in a list by using the slicing operator (colon).
my_list = ['p','r','o','g','r','a','m','i','z']

# elements 3rd to 5th


print(my_list[2:5])
['o', 'g', 'r']
print(my_list[:])
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

4. List is mutable. Discuss.(Dec./Jan.’19)


Lists are mutable:

 Mutable means, we can change the content without changing the identity. Mutability is the
ability for certain types of data to be changed without entirely recreating it.

 Using mutable data types can allow programs to operate quickly and efficiently.

Example for mutable data types are: List, Set and Dictionary
Example :>>>numbers=[42,123]
>>>numbers[1]=5
>>>numbers [42,5]
Here, the second element which was 123 is now turned to be 5.

5. Demonstrate with simple code to draw the histogram in Python. (April/May 2019)
 A histogram is a great tool for quickly assessing a probability distribution that is intuitively
understood by almost any audience.
 Python offers a handful of different options for building and plotting histograms.
Code to draw the histogram in Python
def histogram(a):
for i in a: Output
sum = ''
****
while(i>0):
*****
sum=sum+'#'
*******
i=i-1
********
print(sum)
************
a=[4,5,7,8,12]
histogram(a)

35
6. What is a module? Give example. (Dec./Jan.’19) / Write a note on modular design. (Jan.’18)

 Modules refer to a file containing Python statements and definitions.


 A file containing Python code, for e.g.: example.py, is called a module and its module name
would be example.
 We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
 We can define our most used functions in a module and import it, instead of copying their
definitions into different programs.
 Let us create a module. Type the following and save it as example.py.
 def add(a, b):
result = a + b
return result

>>>import example
>>>example.add(4,5.5)
9.5

7. Find the error in the given code: (Dec./Jan.’19)


While True print (‘Hello World’)
Error in the given code:
"<stdin>", line 1, in ?
while True print('Hello world')

SyntaxError: invalid syntax

The parser repeats the offending line and displays a little ‘arrow’ pointing at the Earliest
point in the line where the error was detected. The error is caused by (or at least detected at) the
token preceding the arrow: in the example, the error is detected at the function print(), since a
colon (':') is missing before it. File name and line number are printed so you know where to look in
case the input came from a script.

PART B

1. Discuss the different options to traverse a list.(8) (Dec./Jan.’19)

Traversing a list is done by iteration/looping lists.


List loops:
1. For loop
2. While loop
For loop in list:
 The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable
objects.
 Iterating over a sequence is called traversal.
36
 Loop continues until we reach the last item in the sequence.
 The body of for loop is separated from the rest of the code using indentation.

Syntax:
for i in sequence:

Accessing element output


a=[10,20,30,40,50] 1
for i in a: 2
print(i) 3
4
5
Accessing index output
a=[10,20,30,40,50] 0
for i in range(0,len(a),1): 1
print(i) 2
3
4
Accessing element using range: output
a=[10,20,30,40,50] 10
for i in range(0,len(a),1): 20
print(a[i]) 30
40
50
List using While loop:
 The while loop in Python is used to iterate over a block of code as long as the test
expression (condition) is true.
 When the condition is tested and the result is false, the loop body will be
skipped and the first statement after the while loop will be executed.

Syntax:
while (condition):
body of while

Example:
a=[1,2,3,4,5]
i=0 sum=0
while i<len(a):
37
sum=sum+a[i]
i=i+1
print(sum)

Output:
15

2. Demonstrate the working of +,* and slice operators in Python.(8) (Dec./Jan.’19)

+, * and slice operators are used for the following operations:

1. + (Concatenation)
2. * (Repeatition)
3. Slicing

Concatenation
Adding and printing the items of two lists.
>>> a=[2,3,4,5,6,7,8,9,10]
>>>b=[20,30]
>>> print(a+b)
[2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30]

Repetition
Create a multiple copies of the same list.
>>> print(b*3)
[20, 30, 20, 30, 20, 30]

List slicing:
List slicing is an operation that extracts a subset of elements from an list and
packages them as another list.

Syntax:
Listname[start:stop]
Listname[start:stop:steps]
default start value is 0
default stop value is n-1

38
3. Compare and contrast tuples and lists in Python.(4) (Dec./Jan.’19)

List Tuples

A list is mutable A tuple is immutable

Lists are dynamic Tuples are fixed size in nature

List are enclosed in brackets[ ] and their Tuples are enclosed in parenthesis ( )
elements and size can be changed and cannot be updated
Homogenous Heterogeneous

Example: Example:
List = [10, 12, 15] Words = ("spam", "egss")
Or Words = "spam",
"eggs"
Access: Access:
print(list[0]) print(words[0])
Can contain duplicate elements Can contain duplicate elements.
Faster compared to lists
Slicing can be done Slicing can be done

Usage: Usage:
 List is used if a collection of data that  Tuple can be used when data
Does’nt need random access. cannot be changed.
 List is used when data can be modified  A tuple is used in combination
frequently with a dictionary i.e. a tuple might
represent a key.

4. Write a Python program to store ‘n’ numbers in a list and sort the list using selection sort. (8) (Jan.’18)
a=[]

Slices Elements Description


>>> a=[9,8,7,6,5,4]
a[0:3] >>> a[0:3] Printing a part of a list from 0 to 2.
[9, 8, 7]

a[:4] >>> a[:4] Default start value is 0. So prints


[9, 8, 7, 6] from 0 to 3
a[1:] >>> a[1:] default stop value will be n-1. so
[8, 7, 6, 5, 4] prints from 1 to 5
a[:] >>> a[:]
[9, 8, 7, 6, 5, 4] Prints the Entire list. 39
n=eval(input("Enter how many numbers "))
print("Enter the numbers one by one \n")
for i in range(0,n):
a.append(eval(input()))
print("Before sorting ")
print(a)
for i in range(0,n-1):
for j in range(i+1,n):
if (a[i]>a[j]):
a[i],a[j]=a[j],a[i]
print("After sorting ")
print(a)

OUTPUT:
Enter how many numbers 5
Enter the numbers one by one
5
6
2
1
3

Before sorting
['5', '6', '2', '1', '3']
After sorting
['1', '2', '3', '5', '6']

5. Demonstrate with the code the various operations that can be performed on tuples. (April/May 2019)

Operations on Tuples:
1. Indexing
2. Slicing
3. Concatenation
4. Repetitions
5. Membership
6. Comparison

Operations examples description

Creating the tuple


Creating a tuple >>>a=(20,40,60,”apple”,”ball”) with elements of
different data types.

40
>>>print(a[0]) Accessing the item in
Indexing 20 the position 0
>>> a[2] Accessing the item in
60 the position 2
Slicing >>>print(a[1:3]) Displaying items
(40,60) from1st till 2nd.
Concatenation >>> b=(2,4) Adding tuple
>>>print(a+b) elements at the end
>>>(20,40,60,”apple”,”ball”,2,4) of another tuple
elements
Repetition >>>print(b*2) repeating the tuple in
>>>(2,4,2,4) n no of times
>>> a=(2,3,4,5,6,7,8,9,10)
>>> 5 in a True
Membership Returns True if
>>> 100 in a
element is present in
False
tuple. Otherwise
>>> 2 not in a
returns false.
False

>>> a=(2,3,4,5,6,7,8,9,10)
>>>b=(2,3,4) Returns True if all
Comparison
>>> a==b elements in both
False elements are same.
>>> a!=b Otherwise returns
True false

6. What is a dictionary in Python? Give example.(8) (Jan.’18)


Dictionaries:
 Dictionary is an unordered collection of elements. An element in dictionary has a key:
value pair.
 All elements in dictionary are placed inside the curly braces i.e. {}
 Elements in Dictionaries are accessed via keys and not by their position.
 The values of a dictionary can be any data type.
 Keys must be immutable data type (numbers, strings, tuple)

Operations on dictionary:
1. Accessing anelement
2. Update

41
3. Add element
4. Membership

Example:
>>> a={1:"one",2:"two"}
>>> print(a)
{1: 'one', 2: 'two'}

7. Appraise the operations for dynamically manipulating dictionaries.(12) (Jan.’18)

Operations on dictionary:
1. Accessing anelement
2. Update
3. Add element
4. Membership

Operations Example Description


Creating a >>> a={1:"one",2:"two"} Creating the dictionary with
dictionary >>> print(a) elements of different
{1: 'one', 2: 'two'} datatypes.
accessing an >>> a[1] Accessing the elements by
element 'one' using keys.
>>> a[0]
KeyError: 0
Update >>> a[1]="ONE" Assigning a new value to key. It
>>> print(a) replaces the old value by new
{1: 'ONE', 2: 'two'} value.
add element >>> a[3]="three" Add new element in to the
>>> print(a) dictionary with key.
{1: 'ONE', 2: 'two', 3: 'three'}
membership a={1: 'ONE', 2: 'two', 3: 'three'} Returns True if the key is
>>> 1 in a True present in dictionary.
>>> 3 not in a Otherwise returns false.
False

42
8. Write a Python program to perform linear search on a list.(8) (Jan.’18)
l=[]
n=eval(input("Enter how many elements "))
print("Enter the elements one by one ")
for i in range(n):
l.append(eval(input()))
s=eval(input("Enter an element to search "))
flag=0
for i in range(n):
if (l[i]==s):
flag=1
break
if (flag==1):
print(s," is found at ",i+1,”position”)
else:
print(s," not found ")

OUTPUT:
Enter how many elements 5
Enter the elements one by one
3
2
4
5
1
Enter an element to search 1
1 is found at 5 position

9. Write a Python script to sort n numbers using selection sort.(12) (Dec./Jan.’19)


a=[]
n=eval(input("Enter how many numbers "))
print("Enter the numbers one by one \n")
for i in range(0,n):
a.append(eval(input()))
print("Before sorting ")
print(a)
for i in range(0,n-1):
for j in range(i+1,n):
if (a[i]>a[j]):
a[i],a[j]=a[j],a[i]
print("After sorting ")
print(a)

OUTPUT:

43
Enter how many numbers 5
Enter the numbers one by one
5
6
2
1
3

Before sorting
['5', '6', '2', '1', '3']
After sorting
['1', '2', '3', '5', '6']

10. Outline the algorithm and write a Python program to sort the numbers in ascending order using
merge sort(16) (April/May 2019)
l1=[]
l2=[]
l3=[]
n1=eval(input("Enter the size of first list "))
n2=eval(input("Enter the size of second list "))
print("Enter the First List elements ")
for i in range(n1):
l1.append(eval(input()))
print("Enter the Second List elements ")
for i in range(n2):
l2.append(eval(input()))
l1.sort()
l2.sort()
i=0
j=0
k=0
while (i<n1 and j<n2):
if (l1[i]>l2[j]):
l3.append(l2[j])
j=j+1
else:
l3.append(l1[i])
i=i+1

if (i<n1):
for m in range(i,n1):
l3.append(l1[m])

44
else:
for m in range(j,n2):
l3.append(l2[m])
print("First List elements are ",l1)
print("Second List elements are ",l2)
print("Resultant List elements are ",l3)
OUTPUT:

Enter the size of first list 4


Enter the size of second list 6
Enter the First List elements
1
3
5
7
Enter the Second List elements
0
2
4
6
8
10
First List elements are [1, 3, 5, 7]
Second List elements are [0, 2, 4, 6, 8, 10]
Resultant List elements are [0, 1, 2, 3, 4, 5, 6, 7, 8, 10]

45
UNIT - 5

PART A
1. Write a Python script to display the current date and time. (Jan.’18)

import datetime
now = datetime.datetime.now()
print("Current date and time: ")
print(str(now))

Output:
2017-12-29 11:24:48.042720

2. Categorize the different types of errors arises during programming .interpret the following python
code. (April/May 2019)
>>>import os
>>>print cwd
/home/dinsale
 Files are organized into directories(also called “folders”). Every running program has
a “current directory”, which is the default directory for most operations.
 The OS modules provides functions for working with files and directories.(“os” stands
for operating system.
 os.getcwd() returns the name of the current working directory.
 The result in this example is /home/dinsale which is the home directory of the user
named dinsale

3. What is command line argument?(April/May 2019)


sys.argv is the list of commandline arguments passed to the Python program. argv represents
all the items that come along via the command line input, it's basically an array holding the
command line arguments of our program.
Counting starts at zero (0) not one (1).
To use it, import it (import sys) The first argument, sys.argv[0], is always the name of the program
as it was invoked, and sys.argv[1] is the first argument you pass to the program. It's common that
you slice the list to access the actual command line argument:
import sys
program_name = sys.argv[0]
arguments = sys.argv[1:]
count = len(arguments)

46
PART B
1. Explain about the file reading and writing operations using format operator with Python code.(16)
(April/May 2019) / Discuss about the use of format operator in file processing.(8) Dec./Jan.’19
Format operator
The argument of write( ) has to be a string, so if we want to put other values along with
the string in a file, we have to convert them to strings.

Convert no into string: output


>>> x = 52 “52”
>>> f.write(str(x))
Convert to strings using format operator, % Example:
print (“format string”%(tuple of >>>age=13
values)) file.write(“format >>>print(“The age is
string”%(tuple of values) %d”%age) The age is 13

Program to write even number in a file using OutPut


format operator
f=open("t.txt","w") enter n:4
n=eval(input("ent enter
er n:")) for i in number:3
range(n): enter
a=int(input("enter number:4
number:")) if(a%2==0): enter
f number:6
.write(a) enter
f.close() number:8
result in file
t.txt 4
6
8
 The first operand is the format string, which specifies how the second operand is formatted.
 The result is a string. For example, the format sequence '%d' means that the second
operand should be formatted as an integer (d stands for “decimal”):

Format character Description


%c Character
%s String formatting
%d Decimal integer
%f Floating point real number

47
2. Tabulate the different modes for opening a file and explain the same.(16) (Jan.’18)

Modes in file:
modes description
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode
 Python allows you to read, write and delete files
 Use the function open("filename","w+") to create a file. The + tells the python interpreter to open
file with read and write permissions.
 To append data to an existing file use the command open("Filename", "a")
 Use the read function to read the ENTIRE contents of a file
 Use the readlines function to read the content of the file one by one.

f = open(“workfile”,”w”)
print f

file = open(“testfile.txt”,”w”)
file.write(“Hello World”)
file.write(“This is our new text file”)
file.write(“and this is another line.”)
file.write(“Why? Because we can.”)
file.close()

$ cat testfile.txt
Hello World
This is our new text file
and this is another line.
Why? Because we can.
file = open(“testfile.txt”, “r”)
for line in file:
print line,

Output:
Hello World
This is our new text file
and this is another line. Why? Because we can.

48
3. Explain the commands used to read and write into a file with examples. (8) Dec./Jan.’19)

Operations on Files:
In Python, a file operation takes place in the following order,
1. Opening a file
2. Reading / Writing file

How to open a file:


Syntax: Example:
file_object=open(“file_name.txt”,”mode”) f=open(“sample.txt”,”w”)

How to create a file:


Syntax: Example:
file_object=open(“file_name.txt”,”mode”) f=open(“sample.txt” ,”w”)
file_object.write(strng) f.write(“hello”)
file_object.close() f.close()

Modes in file:
modes description
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode

Reading and writing in files:

S.No Syntax Example Description


1 f.write(string) f.write("hello") Writing a string into a
file.
f.writelines(“1st line \n Writes a sequence of
2 f.writelines(sequence)
second line”) strings to the file.
f.read( )#read entire file
To read the content
3 f.read(size) f.read(4)#read the first 4
of a file.
character
4 f.readline( ) f.readline( ) Reads one line at a time.
Reads the entire file and
5 f.readlines( ) f.readlines( )
returns a list of lines.

49
4. Explain about how exceptions are handled with example.(8) (April/May 2019) / Describe how
exceptions are handled in Python with necessary example.(16) Dec./Jan.’19 /Appraise the use of try
block and except block in Python with syntax.(6) (Jan.’18)

Exception Handling:
 Exception handling is done by try and catch block.
 Suspicious code that may raise an exception, this kind of code will be placed in try block.
 A block of code which handles the problem is placed in except block.

Catching Exceptions:

1. try…except
2. try…except…inbuilt exception
3. try… except…else

try…except:

 In Python, exceptions can be handled using a try statement.


 A critical operation which can raise exception is placed inside the try clause and the code
that handles exception is written in except clause.
 It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.

Syntax:
try:
code that create exception
except:
exception handling statement

50
Example: Output
try: enter age:8
age=int(input("enter age:")) ur age is: 8
print("ur age is:",age) enter age: f
except: enter a valid age
print("enter a valid age")

try…except…inbuilt exception:
Syntax

try:
code that create exception except inbuilt
exception:

exception handling statement

Example: Output
try: enter
age=int(input("enterage:")) age:d
print("ur age is:",age) enter a
except ValueError: valid age
print("enter a valid
age")

try ... except ... else clause:

 Else part will be executed only if the try block doesn’t raise an exception.
 Python will try to process all the statements inside try block. If value error occurs, the flow of
control will immediately pass to the except block and remaining statement in try block will
be skipped.

Syntax
try:
code that create exception except:
exception handlin
statement else:

statements
Example program Output

51
try: enter your age: six
age=int(input("enter your entered value is not a
age:")) number enter your age:6
except ValueError: your age is 6
print("entered value is not a
number")
else:
print("your age :”,age)

5. Explain with example exceptions with arguments in Python.(10) (Jan.’18)


An exception can have an argument, which is a value that gives additional information about
the problem. The contents of the argument vary from exception to exception. You capture an
exception's argument by supplying a variable in the except clause as follows

try:
b = float(56+78/0)
except Exception, Argument:
print 'This is the Argument\n', Argument
The output obtained is as follows

This is the Argument


integer division or modulo by zero
If you write the code to handle a single exception, you can have a variable follow the name
of the exception in the except statement. If you are trapping multiple exceptions, you can have a
variable follow the tuple of the exception.

This variable receives the value of the exception mostly containing the cause of the
exception. The variable can receive a single value or multiple values in the form of a tuple. This
tuple usually contains the error string, the error number, and an error location.

6. Design a Python code to count the number of words in Python file.(8) (April/May 2019)
Note: Initially create a file with name “wordcount.txt” and enter the required text (Eg. Hai I am a
test program) and save in the python file path.

PROGRAM:
num_words = 0
f=open("wordcount.txt", 'r')
line=f.read()
words=[]
words=line.split()
print(words)
print("Number of words:")
print(len(words))
OUTPUT:
Number of words: 6

52

Вам также может понравиться