Python Question Bank
Python Question Bank
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 :
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,
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:
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
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
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
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:
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
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
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:
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
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
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:
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
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.
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.
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.
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}
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>
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