0% found this document useful (0 votes)
12 views43 pages

Python Question Bank

The document covers Python programming concepts, focusing on variables, operators, control structures, and input/output functions. It includes multiple-choice questions, explanations of tokens, operators, and control structures, as well as programming examples and syntax. The document is structured into sections with varying question formats, including short notes and detailed explanations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views43 pages

Python Question Bank

The document covers Python programming concepts, focusing on variables, operators, control structures, and input/output functions. It includes multiple-choice questions, explanations of tokens, operators, and control structures, as well as programming examples and syntax. The document is structured into sections with varying question formats, including short notes and detailed explanations.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

5.

PYTHON - VARIABLES AND OPERATORS


Section – A
Choose the best answer (1 Mark)
1. Who developed Python ?
A) Ritche B) Guido Van Rossum C) Bill Gates D) Sunder Pitchai
2. The Python prompt indicates that Interpreter is ready to accept instruction.
A) >>> B) <<< C) # D) <<
3. Which of the following shortcut is used to create new Python Program ?
A) Ctrl + C B) Ctrl + F C) Ctrl + B D) Ctrl + N
4. Which of the following character is used to give comments in Python Program ?
A) # B) & C) @ D) $
5. This symbol is used to print more than one item on a single line.
A) Semicolon(;) B) Dollor($) C) comma(,) D) Colon(:)
6. Which of the following is not a token ?
A) Interpreter B) Identifiers C) Keyword D) Operators
7. Which of the following is not a Keyword in Python ?
A) break B) while C) continue D) operators
8. Which operator is also called as Comparative operator?
A) Arithmetic B) Relational C) Logical D) Assignment
9. Which of the following is not Logical operator?
A) and B) or C) not D) Assignment
10. Which operator is also called as Conditional operator?
A) Ternary B) Relational C) Logical D) Assignment
Section-B
Answer the following questions (2 Mark)
1. What are the different modes that can be used to test Python Program ?
In Python, programs can be written in two ways namely Interactive mode and Script mode.
Interactive mode allows us to write codes in Python command prompt ( >>> ).
Script mode is used to create and edit python source file with the extension .py
2. Write short notes on Tokens.
Python breaks each logical line into a sequence of elementary lexical components known as Tokens.
The normal token types are ,
1) Identifiers,
2) Keywords,
31
3) Operators,
4) Delimiters and
5) Literals.
3. What are the different operators that can be used in Python ?
Operators are special symbols which represent computations, conditional matching in programming.
Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
4. What is a literal? Explain the types of literals ?
Literal is a raw data given in a variable or constant.
In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits and are immutable
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.
5. Write short notes on Exponent data?
An Exponent data contains decimal digit part, decimal point, exponent part followed by one or more
digits.
Example: 12.E04, 24.e04
Section-C
Answer the following questions (3 Mark)
1. Write short notes on Arithmetic operator with examples.
 An arithmetic operator is a mathematical operator used for simple arithmetic.
 It takes two operands and performs a calculation on them.
 Arithmetic Operators used in python:

2. What are the assignment operators that can be used in Python?


 ‘=’ is a simple assignment operator to assign values to variable.
 There are various compound operators in Python like +=, -=, *=, /=, %=, **= and //=.
 Example:
a=5 # assigns the value 5 to a
a,b=5,10 # assigns the value 5 to a and 10 to b
a+=2 # a=a+2, add 2 to the value of ‘a’ and stores the result in ‘a’ (Left hand operator)

32
3. Explain Ternary operator with examples.
 Ternary operator is also known as conditional operator that evaluates something based on a
condition being true or false.
 It simply allows testing a condition in a single line replacing the multiline if-else making the code
compact.
Syntax:
Variable Name = [on_true] if [Test expression] else [on_false]
Example :

min = 50 if 49<50 else 70 # Output: min = 50


4. Write short notes on Escape sequences with examples.
 In Python strings, the backslash "\" is a special character, also called the "escape" character.
 It is used in representing certain whitespace characters.
 Python supports the following escape sequence characters.

5. What are string literals? Explain.


 In Python a string literal is a sequence of characters surrounded by quotes.
 Python supports single, double and triple quotes for a string.
 A character literal is a single character surrounded by single or double quotes.
 The value with triple-quote "' '" is used to give multi-line string literal.
 Example:
strings = "This is Python"
char = "C"
multiline_str = "' This is a multiline string with more than one line code."'
print (strings)
print (char)
print (multiline_str)
 Output:
This is Python
C
This is a multiline string with more than one line code.

33
Section - D
Answer the following questions: (5 Mark)
1. Describe in detail the procedure Script mode programming.
SCRIPT MODE PROGRAMMING:
 A script is a text file containing the Python statements.
 Once the Python Scripts is created, they are reusable , it can be executed again and again without
retyping.
 The Scripts are editable.
(i) Creating Scripts in Python
1. Choose File → New File or press Ctrl + N in Python shell window.
2. An untitled blank script text editor will be displayed on screen.
3. Type the code in Script editor as given below,

(ii) Saving Python Script


(1) Choose File → Save or Press Ctrl + S
(2) Now, Save As dialog box appears on the screen.
(3) In the Save As dialog box
 Select the location to save your Python code.
 Type the file name in File Name box.
 Python files are by default saved with extension .py.
 So, while creating scripts using Python Script editor, no need to specify the file extension.
(4) Finally, click Save button to save your Python script.
(iii) Executing Python Script
(1) Choose Run → Run Module or Press F5
(2) If your code has any error, it will be shown in red color in the IDLE window, and Python describes the
type of error occurred.
 To correct the errors, go back to Script editor, make corrections, save the file and execute it again.
(3) For all error free code, the output will appear in the IDLE window of Python as shown in Figure.

34
2. Explain input() and print() functions with examples.
Input and Output Functions
 A program needs to interact with the user to accomplish the desired task; this can be achieved using
Input-Output functions.

 The input() function helps to enter data at run time by the user
 The output function print() is used to display the result of the program on the screen after execution.
1) input() function
 In Python, input( ) function is used to accept data as input at run time.
 The syntax for input() function is,

 “Prompt string” in the syntax is a message to the user, to know what input can be given.
 If a prompt string is used, it is displayed on the monitor; the user can provide expected data from
the input device.
 The input( ) takes typed data from the keyboard and stores in the given variable.
 If prompt string is not given in input( ), the user will not know what is to be typed as input.

 Example:

 In Example 1 input() using prompt string takes proper input and produce relevant output.
 In Example 2 input() without using prompt string takes irrelevant input and produce unexpected
output.
 So, to make your program more interactive, provide prompt string with input( ).
Input() using Numerical values:
 The input ( ) accepts all data as string or characters but not as numbers.
 The int( ) function is used to convert string data as integer data explicitly.
 Example:

35
2) Print() function
 In Python, the print() function is used to display result on the screen.
 Syntax for print():

 Example:

 The print ( ) evaluates the expression before printing it on the monitor.


 The print () displays an entire statement which is specified within print ( ).
 Comma ( , ) is used as a separator in print ( ) to print more than one item.

3. Discuss in detail about Tokens in Python.


Tokens
 Python breaks each logical line into a sequence of elementary lexical components known as Tokens.
 The normal token types are,
1) Identifiers,
2) Keywords,
3) Operators,
4) Delimiters and
5) Literals.
 Whitespace separation is necessary between tokens, identifiers or keywords.
1) Identifiers
 An Identifier is a name used to identify a variable, function, class, module or object.
 An identifier must start with an alphabet (A..Z or a..z) or underscore ( _ ).
 Identifiers may contain digits (0 .. 9)
 Python identifiers are case sensitive i.e. uppercase and lowercase letters are distinct.
 Identifiers must not be a python keyword.
 Python does not allow punctuation character such as %,$, @ etc., within identifiers.
 Example of valid identifiers: Sum, total_marks, regno, num1

36
 Example of invalid identifiers: 12Name, name$, total-mark, continue
2) Keywords
 Keywords are special words used by Python interpreter to recognize the structure of program.
 Keywords have specific meaning for interpreter, they cannot be used for any other purpose.
 Python Keywords: false, class, If, elif, else, pass, break etc.
3) Operators
 Operators are special symbols which represent computations, conditional matching in
programming.
 Operators are categorized as Arithmetic, Relational, Logical, Assignment and Conditional.
 Value and variables when used with operator are known as operands.
 Example:
a=100
b=10
print ("The Sum = ",a+b)
print ("The a > b = ",a>b)
print ("The a > b or a == b = ",a>b or a==b)
a+=10
print(“The a+=10 is =”, a)
 Output:
The Sum = 110
The a>b = True
The a > b or a == b = True
The a+=10 is= 110

4) Delimiters
 Python uses the symbols and symbol combinations as delimiters in expressions, lists, dictionaries and
strings.
 Following are the delimiters.

5) Literals
 Literal is a raw data given in a variable or constant.
 In Python, there are various types of literals. They are,
1) Numeric Literals consists of digits and are immutable
2) String literal is a sequence of characters surrounded by quotes.
3) Boolean literal can have any of the two values: True or False.

37
6. CONTROL STRUCTURES
Section – A
Choose the best answer (1 Mark)
1. How many important control structures are there in Python?
A) 3 B) 4 C) 5 D) 6
2. elif can be considered to be abbreviation of
A) nested if B) if..else C) else if D) if..elif
3. What plays a vital role in Python programming?
A) Statements B) Control C) Structure D) Indentation
4. Which statement is generally used as a placeholder?
A) continue B) break C) pass D) goto
5. The condition in the if statement should be in the form of
A) Arithmetic or Relational expression B) Arithmetic or Logical expression
C) Relational or Logical expression D) Arithmetic
6. Which is the most comfortable loop?
A) do..while B) while C) for D) if..elif
7. What is the output of the following snippet?
i=1
while True:
if i%3 ==0:
break
print(i,end='')
i +=1
A) 1 2 B) 123 C) 1234 D) 124
8. What is the output of the following snippet?
T=1
while T:
print(True)
break
A) False B) True C) 0 D) no output
9. Which amongst this is not a jump statement ?
A) for B) goto C) continue D) break

38
10. Which punctuation should be used in the blank?
if <condition>_
statements-block 1
else:
statements-block 2
A) ; B) : C) :: D) !
Section-B
Answer the following questions (2 Mark)
1. List the control structures in Python.
Three important control structures are,
Sequential
Alternative or Branching
Iterative or Looping

2. Write note on break statement.


break statement :
The break statement terminates the loop containing it.
Control of the program flows to the statement immediately after the body of the loop.
3. Write is the syntax of if..else statement
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
4. Define control structure.
 A program statement that causes a jump of control from one part of the program to another is called
control structure or control statement.

5. Write note on range () in loop


 range() generates a list of values starting from start till stop-1 in for loop.
 The syntax of range() is as follows:
range (start,stop,[step])
Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.

39
Section-C
Answer the following questions (3 Mark)
1. Write a program to display
A
AB
AB C
ABCD
ABCDE
CODE:
for i in range(65, 70):
for j in range(65, i+1):
print(chr(j), end= ‘ ‘)
print(end=’\n’)
i+=1
OUTPUT
A
AB
AB C
ABCD
ABCDE

2. Write note on if..else structure.


 The if .. else statement provides control to check the true block as well as the false block.
 if..else statement thus provides two possibilities and the condition determines which BLOCK is to be
executed.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2
3. Using if..else..elif statement write a suitable program to display largest of 3 numbers.
CODE:
n1= int(input("Enter the first number:"))
n2= int(input("Enter the second number:"))
n3= int(input("Enter the third number:"))
if(n1>=n2)and(n1>=n3):
biggest=n1;
elif(n2>=n1)and(n2>=n3):
40
biggest=n2
else:
biggest=n3
print("The biggest number between",n1,",",n2,"and",n3,"is",biggest)
OUTPUT
Enter the first number:1
Enter the second number:3
Enter the third number:5
The biggest number between 1 , 3 and 5 is 5
4. Write the syntax of while loop.
Syntax:
while <condition>:
statements block 1
[else:
statements block2]
5. List the differences between break and continue statements.
break continue
The break statement terminates the loop The Continue statement is used to skip the
containing it. remaining part of a loop and
Control of the program flows to the statement Control of the program flows start with next
immediately after the body of the loop. iteration.
Syntax: Syntax:
break continue

Section - D
Answer the following questions: (5 Mark)
1. Write a detail note on for loop.
 for loop is the most comfortable loop.
 It is also an entry check loop.
 The condition is checked in the beginning and the body of the loop(statements-block 1) is executed if it
is only True otherwise the loop is not executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
 The counter_variable is the control variable.
 The sequence refers to the initial, final and increment value.
 for loop uses the range() function in the sequence to specify the initial, final and increment values.
 range() generates a list of values starting from start till stop-1.

41
The syntax of range() is as follows:
range (start,stop,[step])
Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.
Example:
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")
Output:
2468
End of the loop
2. Write a detail note on if..else..elif statement with suitable example.
Nested if..elif...else statement:
 When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.
 ‘elif’ clause combines if..else-if..else statements to one if..elif…else.
 ‘elif’ can be considered to be abbreviation of ‘else if’.
 In an ‘if’ statement there is no limit of ‘elif’ clause that can be used, but an ‘else’ clause if used should
be placed at the end.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
 In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-block1
is executed.
 Otherwise the control checks condition-2, if it is true statements-block2 is executed and even if it fails
statements-block n mentioned in else part is executed.
Example:
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)

42
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)

Output :
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D

3. Write a program to display all 3 digit odd numbers.


CODE:
lower=int(input("Enter the lower limit for the range:"))
upper=int(input("Enter the upper limit for the range:"))
for i in range(lower,upper+1):
if(i%2!=0):
print(i,end=" ")
Output:

4. Write a program to display multiplication table for a given number.


CODE:
num=int(input("Display Multiplication Table of "))
for i in range(1,11):
print(i, 'x' ,num, '=' , num*i)
Output:

43
7. PYTHON FUNCTIONS
Section – A
Choose the best answer (1 Mark)
1. A named blocks of code that are designed to do one specific job is called as
(a) Loop (b) Branching (c) Function (d) Block
2. A Function which calls itself is called as
(a) Built-in (b) Recursion (c) Lambda (d) return
3. Which function is called anonymous un-named function
(a) Lambda (b) Recursion (c) Function (d) define
4. Which of the following keyword is used to begin the function block?
(a) define (b) for (c) finally (d) def
5. Which of the following keyword is used to exit a function block?
(a) define (b) return (c) finally (d) def
6. While defining a function which of the following symbol is used.
(a) ; (semicolon) (b) . (dot) (c) : (colon) (d) $ (dollar)
7. In which arguments the correct positional order is passed to a function?
(a) Required (b) Keyword (c) Default (d) Variable-length
8. Read the following statement and choose the correct statement(s).
(I) In Python, you don’t have to mention the specific data types while defining function.
(II) Python keywords can be used as function name.
(a) I is correct and II is wrong
(b) Both are correct
(c) I is wrong and II is correct
(d) Both are wrong
9. Pick the correct one to execute the given statement successfully.
if : print(x, " is a leap year")
(a) x%2=0 (b) x%4==0 (c) x/4=0 (d) x%4=0
10. Which of the following keyword is used to define the function testpython(): ?
(a) define (b) pass (c) def (d) while
Section-B
Answer the following questions (2 Mark)
1. What is function?
 Functions are named blocks of code that are designed to do one specific job.
 Types of Functions are User defined, Built-in, lambda and recursion.
44
 Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
2. Write the different types of function.
TYPES OF FUNCTION:

3. What are the main advantages of function?


 Main advantages of functions are ,
o It avoids repetition and makes high degree of code reusing.
o It provides better modularity for your application.
4. What is meant by scope of variable? Mention its types.
 Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can refer
(use) it.
 Scope holds the current set of variables and their values.
 The two types of scopes are- local scope and global scope.
5. Define global scope.
 A variable, with global scope can be used anywhere in the program.
 It can be created by defining a variable outside the scope of any function/block.
6. What is base condition in recursive function
 A recursive function calls itself.
 The condition that is applied in any recursive function is known as base condition.
 A base condition is must in every recursive function otherwise it will continue to execute like an
infinite loop.
7. How to set the limit for recursive function? Give an example.
 Python stops calling recursive function after 1000 calls by default.
 So, It also allows you to change the limit using [Link] (limit_value).
 Example:
import sys
[Link](3000)
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
print(fact (2000))

45
Section-C
Answer the following questions (3 Mark)
1. Write the rules of local variable.

• A variable with local scope can be accessed only within the function/block that it is created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal arguments are also local to function.
2. Write the basic rules for global keyword in python.
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global by default. You don’t have to use global
keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect.
3. What happens when we modify global variable inside the function?

• If we modify the global variable , We can see the change on the global variable outside the function
also.
Example:
x=0 # global variable
def add():
global x
x=x+5 # increment by 2

print ("Inside add() function x value is :", x)


add()
print ("In main x value is :", x)
Output:
Inside add() function x value is : 5
In main x value is : 5 #value of x changed outside the function
4. Differentiate ceil() and floor() function?
ceil() floor()

Returns the smallest integer greater than or Returns the largest integer less than or equal to
equal to x x

[Link](x) [Link](x)

46
5. Write a Python code to check whether a given year is leap year or not.
CODE:
n=int(input("Enter the year"))
if(n%4==0):
print ("Leap Year")
else:
print ("Not a Leap Year")
Output:
Enter the year 2012
Leap Year
6. What is composition in functions?
• The value returned by a function may be used as an argument for another function in a nested manner.
• This is called composition.
• For example, if we wish to take a numeric value as a input from the user, we take the input string from
the user using the function input() and apply eval() function to evaluate its value.
7. How recursive function works?
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
8. What are the points to be noted while defining a function?
When defining functions there are multiple things that need to be noted;

• Function blocks begin with the keyword “def” followed by function name and parenthesis ().
• Any input parameters should be placed within these parentheses.
• The code block always comes after a colon (:) and is indented.
• The statement “return [expression]” exits a function, and it is optional.
• A “return” with no arguments is the same as return None.
Section - D
Answer the following questions: (5 Mark)
1. Explain the different types of function with an example.
 Functions are named blocks of code that are designed to do one specific job.
 Types of Functions
 User defined Function
 Built-in Function
 Lambda Function
 Recursion Function

47
i) BUILT-IN FUNCTION:
• Built-in functions are Functions that are inbuilt with in Python.
• print(), echo() are some built-in function.
ii) USER DEFINED FUNCTION:
• Functions defined by the users themselves are called user defined function.
 Functions must be defined, to create and use certain functionality.
 Function blocks begin with the keyword “def ” followed by function name and parenthesis ().
 When defining functions there are multiple things that need to be noted;
 Function blocks begin with the keyword “def” followed by function name and parenthesis ().
 Any input parameters should be placed within these parentheses.
 The code block always comes after a colon (:) and is indented.
 The statement “return [expression]” exits a function, and it is optional.
 A “return” with no arguments is the same as return None.
 EXAMPLE:
def area(w,h):
return w * h
print (area (3,5))
iii) LAMBDA FUNCTION:
• In Python, anonymous function is a function that is defined without a name.
• While normal functions are defined using the def keyword, in Python anonymous functions are
defined using the lambda keyword.
• Hence, anonymous functions are also called as lambda functions.
USE OF LAMBDA OR ANONYMOUS FUNCTION:
• Lambda function is mostly used for creating small and one-time anonymous function.
• Lambda functions are mainly used in combination with the functions like filter(), map() and
reduce().
EXAMPLE:
sum = lambda arg1, arg2: arg1 + arg2
print ('The Sum is :', sum(30,40))
print ('The Sum is :', sum(-30,40))
Output:
The Sum is : 70
The Sum is : 10

iv) RECURSIVE FUNCTION:


Functions that calls itself is known as recursive.
Overview of how recursive function works
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.

48
2. Explain the scope of variables with an example.
• Scope of variable refers to the part of the program, where it is accessible, i.e., area where you can
refer (use) it.
• We can say that scope holds the current set of variables and their values.
• There are two types of scopes - local scope and global scope.
 Local Scope:
• A variable declared inside the function's body or in the local scope is known as local variable.
Rules of local variable:
• A variable with local scope can be accessed only within the function/block that it is created in.
• When a variable is created inside the function/block, the variable becomes local to it.
• A local variable only exists while the function is executing.
• The formal arguments are also local to function.
Example:
def loc():
y=0 # local scope
print(y)
loc()
Output:
0

49
 Global Scope
• A variable, with global scope can be used anywhere in the program.
• It can be created by defining a variable outside the scope of any function/block.
 Rules of global Keyword
The basic rules for global keyword in Python are:
• When we define a variable outside a function, it’s global by default. You don’t have to use global
keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect
Use of global Keyword
• Without using the global keyword we cannot modify the global variable inside the function but we
can only access the global variable.
Example:
x=0 # global variable
def add():
global x
x=x+5 # increment by 2
print ("Inside add() function x value is :", x)
add()
print ("In main x value is :", x)
Output:

Inside add() function x value is : 5


In main x value is : 5 #value of x changed outside the function
3. Explain the following built-in functions.
(a) id() (b) chr() (c) round() (d) type() (e) pow()

Function Description Syntax Example


Return the “identity” of id (object) x=15
id ( ) an object. i.e. the address y='a'
of the object in memory. print ('address of x is :',id (x))
print ('address of y is :',id (y))
Output:
address of x is : 1357486752
address of y is : 13480736
Returns the Unicode
chr ( ) character for the given chr(i) c=65
ASCII value. print(chr(c))
Output:
A

50
round ( ) Returns the nearest round x= 17.9
integer to its input. (number print ('x value is rounded to',
1. First argument [,ndigits]) round (x))
(number) is used to
specify the value to be
Output:
rounded.
X value is rounded to 18

type ( ) Returns the type of type x= 15.2


object for the given (object) print (type
single object. (x))
Output:
<class
'float'>

pow ( ) Returns the pow a= 5


computation of a,b i.e. (a,b) b= 2
(a**b ) a raised to the print (pow (a,b))
power of b. Output:
25

4. Write a Python code to find the L.C.M. of two numbers.


CODE:
x=int(input("Enter first number:"))
y=int(input("Enter second number:"))
if x>y:
min=x
else:
min=y
while(1):
if((min%x == 0) and (min % y == 0)):
print("LCM is:",min)
break
min=min+1
OUTPUT:
Enter first number:2
Enter second number:3
LCM is: 6

51
5. Explain recursive function with an example.
 Functions that calls itself is known as recursive.
 When a function calls itself is known as recursion.
 Recursion works like loop but sometimes it makes more sense to use recursion than loop.
 Imagine a process would iterate indefinitely if not stopped by some condition is known as infinite
iteration.
 The condition that is applied in any recursive function is known as base condition.
 A base condition is must in every recursive function otherwise it will continue to execute like an
infinite loop.
 Python stops calling recursive function after 1000 calls by default.
 So, It also allows you to change the limit using [Link] (limit_value).
Overview of how recursive function works:
1. Recursive function is called by some external code.
2. If the base condition is met then the program gives meaningful output and exits.
3. Otherwise, function does some required processing and then calls itself to continue recursion.
EXAMPLE:
def fact(n):
if n == 0:
return 1
else:
return n * fact (n-1)
print (fact (0))
print (fact (5))
Output:
1
120

52
8. STRINGS AND STRING MANIPULATION
Section – A
Choose the best answer (1 Mark)
1. Which of the following is the output of the following python code?
str1="TamilNadu"
print(str1[::-1])
(a) Tamilnadu (b) Tmlau (c) udanlimaT d) udaNlimaT
2. What will be the output of the following code?
str1 = "Chennai Schools"
str1[7] = "-"
(a) Chennai-Schools (b) Chenna-School (c) Type error (d) Chennai
3. Which of the following operator is used for concatenation?
(a) + (b) & (c) * (d) =
4. Defining strings within triple quotes allows creating:
(a) Single line Strings (b) Multiline Strings
(c) Double line Strings (d) Multiple Strings
5. Strings in python:
(a) Changeable (b) Mutable (c) Immutable (d) flexible
6. Which of the following is the slicing operator?
(a) { } (b) [ ] (c) < > (d) ( )
7. What is stride?
(a) index value of slide operation (b) first argument of slice operation
(c) second argument of slice operation (d) third argument of slice operation
8. Which of the following formatting character is used to print exponential notation in upper case?
(a) %e (b) %E (c) %g (d) %n
9. Which of the following is used as placeholders or replacement fields which get replaced along with
format( ) function?
(a) { } (b) < > (c) ++ (d) ^^
10. The subscript of a string may be:
(a) Positive (b) Negative (c) Both (a) and (b) (d) Either (a) or (b)

53
Section-B
Answer the following questions (2 Mark)
1. What is String?
 String is a data type in python, used to handle array of characters.
 String is a sequence of characters that may be a combination of letters, numbers, or special
symbols enclosed within single, double or even triple quotes.
2. Do you modify a string in Python?
 No we cannot modify the string in python.
 String is an immutable
 But we can modify the string use following method,
 A new string value can be assign to the existing string variable.
 When defining a new string value to the existing string variable.
 Python completely overwrite new string on the existing string.
3. How will you delete a string in Python?
 Python will not allow deleting a particular character in a string.
 Whereas you can remove entire string variable using del command.
 Example:
del str1[2]
4. What will be the output of the following python code?
str1 = “School”
print(str1*3)
OUTPUT:
School School School
5. What is slicing?
 Slice is a substring of a main string.
 A substring can be taken from the original string by using [ ] slicing operator and index or subscript
values.
 Using slice operator, you have to slice one or more substrings from a main string.
General format of slice operation:
str[start:end]
Section-C
Answer the following questions (3 Mark)
1. Write a Python program to display the given pattern
COMPUTER
COMPUTE
COMPUT
COMPU
COMP
COM
CO
C

54
CODE:
str="COMPUTER"
index=len(str)
for i in str:
print(str[:index])
index-=1

55
2. Write a short about the followings with suitable example: (a) capitalize( ) (b) swapcase( )
FUNCTION PURPOSE EXAMPLE
Used to capitalize the first character of the >>> city="chennai"
capitalize( ) string >>> print([Link]())
Output:
Chennai
It will change case of every character to its >>> str1="tAmiL NaDu"
swapcase( ) opposite case vice-versa. >>> print([Link]())
Output:
TaMIl nAdU

3. What will be the output of the given python program?


CODE:
str1 = "welcome"
str2 = "to school"
str3=str1[:2]+str2[len(str2)-2:]
print(str3)
OUTPUT:
weol

4. What is the use of format( )? Give an example.


 The format( ) function used with strings is very powerful function used for formatting strings.
 The curly braces { } are used as placeholders or replacement fields which get replaced along with
format( ) function.
EXAMPLE:
num1=int (input("Number 1: "))
num2=int (input("Number 2: "))
print ("The sum of { } and { } is { }".format(num1, num2,(num1+num2)))

OUTPUT:
Number 1: 34
Number 2: 54
The sum of 34 and 54 is 88

56
5. Write a note about count( ) function in python.
 Returns the number of substrings occurs within the given range.
 Remember that substring may be a single character.
 Range (beg and end) arguments are optional. If it is not given, python searched in whole string.
 Search is case sensitive.
SYNTAX:

count(str, beg, end)

EXAMPLE:
>>> str1="Raja Raja Chozhan"
>>> print([Link]('Raja'))
OUTPUT: 2
Section - D
Answer the following questions: (5 Mark)
1. Explain about string operators in python with suitable example.
STRING OPERATORS
Python provides the following string operators to manipulate string.
(i) Concatenation (+)
 Joining of two or more strings using plus (+) operator is called as Concatenation.
Example
>>> "welcome" + "Python"
Output: 'welcomePython'
(ii) Append (+ =)
 Adding more strings at the end of an existing string using operator += is known as append.
Example:
>>> str1="Welcome to "
>>> str1+="Learn Python"
>>> print (str1)
Output: Welcome to Learn Python
(iii) Repeating (*)
 The multiplication operator (*) is used to display a string in multiple number of times.
Example:
>>> str1="Welcome "
>>> print (str1*4)
Output: Welcome Welcome Welcome Welcome

(iv) String slicing


 Slice is a substring of a main string.
 A substring can be taken from the original string by using [ ] slicing operator and index values.
 Using slice operator, you have to slice one or more substrings from a main string.
57
General format of slice operation:
str[start:end]
 Where start is the beginning index and end is the last index value of a character in the string.
 Python takes the end value less than one from the actual index specified.
Example: slice a single character from a string
>>> str1="THIRUKKURAL"
>>> print (str1[0])
Output: T
(v) Stride when slicing string
 When the slicing operation, you can specify a third argument as the stride, which refers to the number
of characters to move forward after the first character is retrieved from the string.
 The default value of stride is 1.
 Python takes the last value as n-1
 You can also use negative value as stride, to prints data in reverse order.
Example:
>>> str1 = "Welcome to learn Python"
>>> print (str1[10:16])
>>> print(str1[::-2])
Output: Learn
nhy re teolW

58
9. LISTS, TUPLES, SETS, AND DICTIONARY
Section – A
Choose the best answer (1 Mark)
1. Pick odd one in connection with collection data type
(a) List (b) Tuple (c) Dictionary (d) Loop
2. Let list1=[2,4,6,8,10], then print(List1[-2]) will result in
(a) 10 (b) 8 (c) 4 (d) 6
3. Which of the following function is used to count the number of elements in a list?
(a) count() (b) find() (c)len() (d) index()
4. If List=[10,20,30,40,50] then List[2]=35 will result
(a) [35,10,20,30,40,50] (b) [10,20,30,40,50,35]
(c) [10,20,35,40,50] (d) [10,35,30,40,50]
5. If List=[17,23,41,10] then [Link](32) will result
(a) [32,17,23,41,10] (b) [17,23,41,10,32]
(c) [10,17,23,32,41] (d) [41,32,23,17,10]
6. Which of the following Python function can be used to add more than one element within an
Existing list?
(a) append() (b) append_more() (c)extend() (d) more()
7. What will be the result of the following Python code?
S=[x**2 for x in range(5)]
print(S)
(a) [0,1,2,4,5] (b) [0,1,4,9,16] (c) [0,1,4,9,16,25] (d) [1,4,9,16,25]
8. What is the use of type() function in python?
(a) To create a Tuple (b) To know the type of an element in tuple.
(c) To know the data type of python object. (d) To create a list.
9. Which of the following statement is not correct?
(a) A list is mutable
(b) A tuple is immutable.
(c) The append() function is used to add an element.
(d) The extend() function is used in tuple to add elements in a list.
10. Let setA={3,6,9}, setB={1,3,9}. What will be the result of the following snippet?
print(setA|setB)
(a) {3,6,9,1,3,9} (b) {3,9} (c) {1} (d) {1,3,6,9}

59
11. Which of the following set operation includes all the elements that are in two sets but not the one that
are common to two sets?
(a) Symmetric difference (b) Difference (c) Intersection (d) Union
12. The keys in Python, dictionary is specified by
(a) = (b) ; (c)+ (d) :
Section-B
Answer the following questions (2 Mark)
1. What is List in Python?
 A list is an ordered collection of values enclosed within square brackets [ ] also known as a “sequence
data type”.
 Each value of a list is called as element.
 Elements can be a numbers, characters, strings and even the nested lists.
 Syntax: Variable = [element-1, element-2, element-3 …… element-n]
2. How will you access the list elements in reverse order?
Python enables reverse or negative indexing for the list elements.
A negative index can be used to access an element in reverse order.
Thus, python lists index in opposite order.
The python sets -1 as the index value for the last element in list and -2 for the preceding element and so
on.
This is called as Reverse Indexing.
3. What will be the value of x in following python code?
List1=[2,4,6,[1,3,5]]
x=len(List1)
print(x)
OUTPUT:
====== RESTART: C:/Users/[Link]-PC/Desktop/Python/[Link] ======
4
>>>
4. Differentiate del with remove( ) function of List.
del remove( )
del statement is used to delete known elements remove( ) function is used to delete elements of
a list if its index is unknown.
The del statement can also be used to delete The remove is used to delete a particular element
entire list.
5. Write the syntax of creating a Tuple with n number of elements.
Syntax:
Tuple_Name = (E1, E2, E2 ……. En) # Tuple with n number elements
Tuple_Name = E1, E2, E3 ….. En # Elements of a tuple without parenthesis

60
6. What is set in Python?
 In python, a set is another type of collection data type.
 A Set is a mutable and an unordered collection of elements without duplicates or repeated element.
 This feature used to include membership testing and eliminating duplicate elements.
Section-C
Answer the following questions (3 Mark)
1. What are the advantages of Tuples over a list?
 The elements of a list are changeable (mutable) whereas the elements of a tuple are unchangeable
(immutable), this is the key difference between tuples and list.
 The elements of a list are enclosed within square brackets. But, the elements of a tuple are enclosed by
paranthesis.
 Iterating tuples is faster than list.

2. Write a short note about sort( ).


sort ( ):
 It sorts the element in list.
 sort( ) will affect the original list.
Syntax : [Link](reverse=True|False, key=myFunc)
Description of the Syntax:
Both arguments are optional ,
 If reverse is set as True, list sorting is in descending order.
 Ascending is default.
 Key=myFunc; “myFunc” - the name of the user defined function that specifies the sorting criteria.
3. What will be the output of the following code?
list = [2**x for x in range(5)]
print(list)
OUTPUT: [1, 2, 4, 8, 16]
4. Explain the difference between del and clear( ) in dictionary with an example.
del clear( )
The del statement is used to delete known The function clear( ) is used to delete all the
elements elements in list
The del statement can also be used to delete entire It deletes only the elements and retains the list.
list.
5. List out the set operations supported by python.
Set Operations:
(i) Union: It includes all elements from two or more sets.
(ii) Intersection: It includes the common elements in two sets.

61
(iii) Difference: It includes all elements that are in first set (say set A) but not in the second set (say set
B).
iv) Symmetric difference: It includes all the elements that are in two sets (say sets A and B) but not the
one that are common to two sets.
6. What are the difference between List and Dictionary?
List Dictionary
 A list is an ordered collection of values or  A dictionary is a mixed collection of
elements of any type . elements and it stores a key along with its
element.
 It is enclosed within square brackets [ ]  The key value pairs are enclosed with curly
braces { }.
 Syntax:  Syntax of defining a dictionary:
Variable = [element-1, element-2, element-3 Dictionary_Name = { Key_1: Value_1,
…… element-n] Key_2:Value_2,
……..
Key_n:Value_n
}
 The commas work as a separator for the  The keys in a Python dictionary is
elements. separated by a colon ( : ) while the commas
work as a separator for the elements.

Section - D
Answer the following questions: (5 Mark)
1. What the different ways to insert an element in a list. Explain with suitable example.
Inserting elements in a list using insert():
 The insert ( ) function helps you to include an element at your desired position.
 The insert( ) function is used to insert an element at any position of a list.
Syntax:
[Link] (position index, element)
Example:
>>> MyList=[34,98,47,'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan' ]
>>> [Link](3, 'Ramakrishnan')
>>> print(MyList)
Output: [34, 98, 47, 'Ramakrishnan', 'Kannan', 'Gowrisankar', 'Lenin', 'Sreenivasan']
 In the above example, insert( ) function inserts a new element ‘Ramakrishnan’ at the index value 3, ie.
th
at the 4 position.
 While inserting a new element, the existing elements shifts one position to the right.
Adding more elements in a list using append():
 The append( ) function is used to add a single element in a list.
 But, it includes elements at the end of a list.

62
Syntax:
[Link] (element to be added)
Example:
>>> Mylist=[34, 45, 48]
>>> [Link](90)
>>> print(Mylist)
Output: [34, 45, 48, 90]
Adding more elements in a list using extend():
 The extend( ) function is used to add more than one element to an existing list.
 In extend( ) function, multiple elements should be specified within square bracket as arguments of the
function.
Syntax:
[Link] ( [elements to be added])
Example:
>>> Mylist=[34, 45, 48]
>>> [Link]([71, 32, 29])
>>> print(Mylist)

63
Output: [34, 45, 48, 90, 71, 32, 29]
2. What is the purpose of range( )? Explain with an example.
range():
 The range( ) is a function used to generate a series of values in Python.
 Using range( ) function, you can create list with series of values.
 The range( ) function has three arguments.

Syntax of range ( ) function:


range (start value, end value, step value)
where,
 start value – beginning value of series. Zero is the default beginning value.
 end value – upper limit of series. Python takes the ending value as upper limit – 1.
 step value – It is an optional argument, which is used to generate different interval of values.
Example : Generating whole numbers upto 10
for x in range (1, 11):
print(x)
Output:
1
2
3
4
5
6
7
8
9
10

Creating a list with series of values

 Using the range( ) function, you can create a list with series of values.
 To convert the result of range( ) function into list, we need one more function called list( ).
 The list( ) function makes the result of range( ) as a list.
Syntax:
List_Varibale = list ( range ( ) )
Example :
>>> Even_List = list(range(2,11,2))
>>> print(Even_List)

64
Output: [2, 4, 6, 8, 10]

 In the above code, list( ) function takes the result of range( ) as Even_List elements.
 Thus, Even_List list has the elements of first five even numbers.

3. What is nested tuple? Explain with an example.


Tuple:
 Tuples consists of a number of values separated by comma and enclosed within parentheses.
 Tuple is similar to list, values in a list can be changed but not in a tuple.
Nested Tuples:
 In Python, a tuple can be defined inside another tuple; called Nested tuple.
 In a nested tuple, each tuple is considered as an element.
 The for loop will be useful to access all the elements in a nested tuple.
Example:

Toppers = (("Vinodini", "XII-F", 98.7), ("Soundarya", "XII-H", 97.5), ("Tharani", "XII-F", 95.3),
("Saisri", "XII-G", 93.8))
for i in Toppers:
print(i)

Output:
('Vinodini', 'XII-F', 98.7)
('Soundarya', 'XII-H', 97.5)
('Tharani', 'XII-F', 95.3)
('Saisri', 'XII-G', 93.8)

4. Explain the different set operations supported by python with suitable example.
 A Set is a mutable and an unordered collection of elements without duplicates.
Set Operations:
 The set operations such as Union, Intersection, difference and Symmetric difference.
(i) Union:
 It includes all elements from two or more sets.
 The operator | is used to union of two sets.
 The function union( ) is also used to join two sets in python.

65
Example:
set_A={2,4,6,8}
set_B={'A', 'B', 'C', 'D'}
U_set=set_A|set_B
print(U_set)
Output:
{2, 4, 6, 8, 'A', 'D', 'C', 'B'}
(ii) Intersection:
 It includes the common elements in two sets.
 The operator & is used to intersect two sets in python.
 The function intersection( ) is also used to intersect two sets in python.

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A & set_B)

Output:
{'A', 'D'}

(iii) Difference:
 It includes all elements that are in first set (say set A) but not in the second set (say set B).
 The minus (-) operator is used to difference set operation in python.
 The function difference( ) is also used to difference operation.

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A - set_B)
Output:
66
{2, 4}

(iv) Symmetric difference


 It includes all the elements that are in two sets (say sets A and B) but not the one that are common to
two sets.
 The caret (^) operator is used to symmetric difference set operation in python.
 The function symmetric_difference( ) is also used to do the same operation.

Example:
set_A={'A', 2, 4, 'D'}
set_B={'A', 'B', 'C', 'D'}
print(set_A ^ set_B)

Output:
{2, 4, 'B', 'C'}

67
10. PYTHON CLASSES AND OBJECTS
Section – A
Choose the best answer (1 Mark)
1. Which of the following are the key features of an Object Oriented Programming language?
(a) Constructor and Classes (b) Constructor and Object
(c) Classes and Objects (d) Constructor and Destructor
2. Functions defined inside a class:
(a) Functions (b) Module (c) Methods (d) section
3. Class members are accessed through which operator?
(a) & (b) . (c) # (d) %
4. Which of the following method is automatically executed when an object is created?
(a) object ( ) (b) del ( ) (c) func__( ) (d) init ( )
5. A private class variable is prefixed with
(a) (b) && (c) ## (d) **
6. Which of the following method is used as destructor?
(a) init ( ) (b) dest__( ) (c) rem ( ) (d) del__( )
7. Which of the following class declaration is correct?
(a) class class_name (b) class class_name<> (c) class class_name: (d) class class_name[ ]
8. Which of the following is the output of the following program?
class Student:
def init__(self, name):
[Link]=name
S=Student(“Tamil”)
(a) Error (b) Tamil (c) name (d) self
9. Which of the following is the private class variable?
(a) num (b) ##num (c) $$num (d) &&num
10. The process of creating an object is called as:
(a) Constructor (b) Destructor (c) Initialize (d) Instantiation
Section-B
Answer the following questions (2 Mark)
1. What is class?
 Class is the main building block in Python.
 Class is a template for the object.
 Object is a collection of data and function that act on those data.

68
 Objects are also called as instances of a class or class variable.
2. What is instantiation?
 The process of creating object is called as “Class Instantiation”.
Syntax:
Object_name = class_name( )
3. What is the output of the following program?
class Sample:
num=10
def disp(self):
print(self. num)
S=Sample()
[Link]()
print(S. num)
OUTPUT:
>>>
10
line 7, in <module>
print(S. num)
AttributeError: 'Sample' object has no attribute ' num'
4. How will you create constructor in Python?
 “init” is a special function begin and end with double underscore in Python act as a Constructor.
 Constructor function will automatically executed when an object of a class is created.
General format:
def init__(self, [args .......... ]):
<statements>

5. What is the purpose of Destructor?


 Destructor is also a special method gets executed automatically when an object exit from the scope.
 In Python, del__( ) method is used as destructor.
General format:
def del (self):
<statements>
Section-C
Answer the following questions (3 Mark)
1. What are class members? How do you define it?
 Variables defined inside a class are called as “Class Variable” and functions are called as “Methods”.
 Class variable and methods are together known as members of the class.
 The class members should be accessed through objects or instance of class.
 A class can be defined anywhere in a Python program.

69
 SYNTAX FOR DEFINING A CLASS:
class class_name:
statement_1
statement_2
…………..
…………..
statement_n
2. Write a class with two private class variables and print the sum using a method.
CODE:
class Sample:
def init (self,n1,n2):
self.__n1=n1
self.__n2=n2
def sum(self):
print("Class Variable 1:",self. n1)
print("Class Variable 2:",self. n2)
print("Sum:",self. n1 + self. n2)
S=Sample(5,10)
[Link]()
OUTPUT:
>>>
Class Variable 1: 5
Class Variable 2: 10
Sum: 15
>>>
3. Find the error in the following program to get the given output?
ERROR CODE:
class Fruits:
def init__(self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple', 'Mango')
del [Link]
[Link]()
OUTPUT:

70
Fruit 1 = Apple, Fruit 2 = Mango
ERROR:
line 8, in <module>
del [Link]
AttributeError: display
CORRECT CODE:
class Fruits:
def init (self, f1, f2):
self.f1=f1
self.f2=f2
def display(self):
print("Fruit 1 = %s, Fruit 2 = %s" %(self.f1, self.f2))
F = Fruits ('Apple','Mango')
[Link]()
OUTPUT:
Fruit 1 = Apple, Fruit 2 = Mango
4. What is the output of the following program?
CODE:
class Greeting:
def init__(self, name):
self. name = name
def display(self):
print("Good Morning ", self. name)

obj=Greeting('Bindu Madhavan')
[Link]()
Output:
>>>
Good Morning Bindu Madhavan
>>>
5. How do define constructor and destructor in Python?
CONSTRUCTOR:
 “init” is a special function begin and end with double underscore in Python act as a Constructor.
 Constructor function will automatically executed when an object of a class is created.
General format of constructor:
def init__(self, [args .......... ]):
<statements>
71
DESTRUCTOR:
 Destructor is also a special method gets executed automatically when an object exit from the scope.
 In Python, del__( ) method is used as destructor.
General format of destructor:
def del (self):
<statements>

Section - D
Answer the following questions: (5 Mark)
1. Write a menu driven program to add or delete stationary items. You should use dictionary to
store items and the brand.
CODE:
stationary={}
print("\n1. Add Item \[Link] item \[Link]")
ch=int(input("\nEnter your choice: "))

while(ch==1)or(ch==2):
if(ch==1):
n=int(input("\nEnter the Number of Items to be added in the Dictionary: "))
for i in range(n):
item=input("\nEnter an Item Name: ")
brand=input("\nEnter the Brand Name: ")
stationary[item]=brand
print(stationary)
elif(ch==2):
ritem=input("\nEnter the item to be removed from the Dictionary: ")
[Link](ritem)
print(stationary)
ch=int(input("\nEnter your choice: "))

72
OUTPUT:

73

You might also like