Python - 2 Marks Question Bank
Python - 2 Marks Question Bank
UNIT I
COMPUTATIONAL THINKING AND PROBLEM SOLVING
PART- A (2 Marks)
1. What is an algorithm?
Algorithm is an ordered sequence of finite, well defined, unambiguous instructions for
completing a task. It is an English-like representation of the logic which is used to solve
the problem. It is a step- by-step procedure for solving a task or a problem. The steps must be
ordered, unambiguous and finite in number.
2. Write an algorithm to find minimum of 3 numbers in a list.
ALGORITHM : Find Minimum of 3 numbers in a list
Step 1: Start
Step 2: Read the three numbers A, B, C
Step 3: Compare A and B.
If A is minimum, go to step 4 else go to step 5.
Step 4: Compare A and C.
If A is minimum, output “A is minimum” else output “C is minimum”. Go to step 6.
Step 5: Compare B and C.
If B is minimum, output “B is minimum” else output “C is minimum”.
Step 6: Stop
3. List the building blocks of an algorithm.
The building blocks of an algorithm are
Statements
Sequence
Selection or Conditional
Repetition or Control flow
Functions
4. Define statement. List its types.
Statements are instructions in Python designed as components for algorithmic problem
solving, rather than as one-to-one translations of the underlying machine language instruction
set of the computer.
There are three types of high-level programming language statements Input/output
statements make up one type of statement. An input statement collects a specific value from
the user for a variable within the program. An output statement writes a message or the value
of a program variable to the user’s screen.
5. Write the pseudo code to calculate the sum and product of two numbers and display it.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2
sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
6. How does flow of control work?
Control flow (or flow of control) is the order in which individual statements, instructions or
function calls of an imperative program are executed or evaluated. A control flow statement is
a statement in which execution results in a choice being made as to which of two or more
paths to follow.
7. What is a function?
Functions are "self-contained" modules of code that accomplish a specific task. Functions
usually "take in" data, process it, and "return" a result. Once a function is written, it can be used
over and over and over again. Functions can be "called" from the inside of other functions.
8. Write the pseudo code to calculate the sum and product displaying the answer on the
monitor screen.
INITIALIZE variables sum, product, number1, number2 of type real
PRINT “Input two numbers”
READ number1, number2
sum = number1 + number2
PRINT “The sum is “, sum
COMPUTE product = number1 * number2
PRINT “The Product is “, product
END program
9. Give the rules for writing Pseudo codes.
Write one statement per line.
Capitalize initial keywords.
Indent to show hierarchy.
End multiline structure.
Keep statements to be language independent.
10. Give the difference between flowchart and pseudo code.
Flowchart and Pseudo code are used to document and represent the algorithm. In other words,
an algorithm can be represented using a flowchart or a pseudo code. Flowchart is a graphical
representation of the algorithm. Pseudo code is a readable, formally styled English like language
representation of the algorithm.
11. Define a flowchart.
A flowchart is a diagrammatic representation of the logic for solving a task. A flowchart is
drawn using boxes of different shapes with lines connecting them to show the flow of control.
The purpose of drawing a flowchart is to make the logic of the program clearer in a visual form.
12. Give an example of iteration.
a=0
for i from 1 to 3 // loop three times
{
a=a+i // add the current value of i to a
}
print a // the number 6 is printed (0 + 1; 1 + 2; 3 + 3)
13. Write down the rules for preparing a flowchart.
While drawing a flowchart, some rules need to be followed—
(1) A flowchart should have a start and end,
(2) The direction of flow in a flowchart must be from top to bottom and left to right, and
(3) The relevant symbols must be used while drawing a flowchart.
14. List the categories of Programming languages.
Programming languages are divided into the following categories:
Interpreted, Functional, Compiled, Procedural, Scripting, Markup, Logic-Based, Concurrent
and Object-Oriented Programming Languages
15. Mention the characteristics of an algorithm.
Algorithm should be precise and unambiguous.
Instruction in an algorithm should not be repeated infinitely.
Ensure that the algorithm will ultimately terminate.
Algorithm should be written in sequence.
Algorithm should be written in normal English.
Desired result should be obtained only after the algorithm terminates.
16. Compare machine language, assembly language and high-level language.
Machine language is a collection of binary digits or bits that the computer reads and
interprets. This language is not easily understandable by the human.
An assembly language directly controls the physical hardware. A program written in assembly
language consists of a series of instructions mnemonics that correspond to a stream of executable
instructions, when translated by an assembler can be loaded into memory and executed. The
programs written in this language are not portable and the debugging process is also not very
easy.
A high level language is much more abstract, that must be translated or compiled in to
machine language. It is easily understandable and the programs are portable. Debugging the code is easy
and the program written is not machine dependent.
17. What is the difference between algorithm and pseudo code?
An algorithm is a systematic logical approach used to solve problems in a computer while
pseudo code is the statement in plain English that may be translated later to a programming
language. Pseudo code is the intermediary between algorithm and program.
18. List out the simple steps to develop an algorithm.
Algorithm development process consists of five major steps.
Step 1: Obtain a description of the problem.
Step 2: Analyze the problem.
Step 3: Develop a high-level algorithm.
Step 4: Refine the algorithm by adding more detail.
Step 5: Review the algorithm.
19.Give the differences between recursion and iteration.
Recursion Iteration
Function calls itself until the base condition is Repetition of process until the condition fails.
reached.
Only base condition (terminating condition) is It involves four steps: initialization, condition,
specified. execution and updation.
It keeps our code short and simple. Iterative approach makes our code longer.
It is slower than iteration due to overhead of Iteration is faster.
maintaining stack.
It takes more memory than iteration due to Iteration takes less memory.
overhead of maintaining stack.
20. What are advantages and disadvantages of recursion?
Advantages Disadvantages
Recursive functions make the code look clean Sometimes the logic behind recursion is hard to
and elegant. follow through.
A complex task can be broken down into Recursive calls are expensive (inefficient) as
simpler sub-problems using recursion. they take up a lot of memory and time.
Sequence generation is easier with recursion Recursive functions are hard to debug.
than using some nested iteration.
UNIT II
DATA TYPES, EXPRESSIONS, STATEMENTS
PART- A (2 Marks)
1. What is meant by interpreter?
An interpreter is a computer program that executes instructions written in a programming
language. It can either execute the source code directly or translate the source code in a first step into
a more efficient representation and executes this code.
2. How will you invoke the python interpreter?
The Python interpreter can be invoked by typing the command "python" without any
parameter followed by the "return" key at the shell prompt.
3. What is meant by interactive mode of the interpreter?
Interactive mode is a command line shell which gives immediate feedback for each statement,
while running previously fed statements in active memory. As new lines are fed into the interpreter,
the fed program is evaluated both in part and in whole.
4. Write a snippet to display “Hello World” in python interpreter.
In script mode:
>>> print "Hello World"
Hello World
In Interactive Mode:
>>> "Hello World"
'Hello World'
5. What is a value? What are the different types of values?
A value is one of the fundamental things – like a letter or a number – that a program manipulates. Its
types are: integer, float, boolean, strings and lists.
6. Define a variable and write down the rules for naming a variable.
A name that refers to a value is a variable. Variable names can be arbitrarily long. They can
contain both letters and numbers, but they have to begin with a letter. It is legal to use uppercase
letters, but it is good to begin variable names with a lowercase letter.
7. Define keyword and enumerate some of the keywords in Python.
A keyword is a reserved word that is used by the compiler to parse a program. Keywords
cannot be used as variable names. Some of the keywords used in python are: and, del, from, not,
while, is, continue.
8. Define statement and what are its types?
A statement is an instruction that the Python interpreter can execute. There are two types of
statements: print and assignment statement.
9. What do you meant by an assignment statement?
An assignment statement creates new variables and gives them values:
Eg 1: Message = 'And now for something completely different'
Eg 2: n = 17
10. What is tuple?
A tuple is a sequence of immutable Python objects. Tuples are sequences, like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different
comma-separated values. Comma-separated values between parentheses can also be used.
Example: tup1 = ('physics', 'chemistry', 1997, 2000);
11.What is an expression?
An expression is a combination of values, variables, and operators. An expression is evaluated
using assignment operator.
Examples: Y=x + 17
12. What do you mean by an operand and an operator? Illustrate your answer with relevant
example.
An operator is a symbol that specifies an operation to be performed on the operands. The data
items that an operator acts upon are called operands. The operators +, -, *, / and ** perform addition,
subtraction, multiplication, division and exponentiation.
Example: 20+32
In this example, 20 and 32 are operands and + is an operator.
13. What is the order in which operations are evaluated? Give the order of precedence.
The set of rules that govern the order in which expressions involving multiple operators and
operands are evaluated is known as rule of precedence. Parentheses have the highest precedence
followed by exponentiation. Multiplication and division have the next highest precedence followed
by addition and subtraction.
14. Illustrate the use of * and + operators in string with example.
The * operator performs repetition on strings and the + operator performs concatenation on
strings.
Example:
>>> ‘Hello*3’
Output: HelloHelloHello
>>>’Hello+World’
Output: HelloWorld
15. What is the symbol for comment? Give an example.
# is the symbol for comments in Python.
Example:
# compute the percentage of the hour that has elapsed
16. What is function call?
A function is a named sequence of statements that performs a computation. When we define a
function, we specify the name and the sequence of statements. Later, we can “call” the function by its
name called as function call.
17. Identify the parts of a function in the given example.
>>> betty = type("32")
>>> print betty
The name of the function is type, and it displays the type of a value or variable. The value or variable,
which is called the argument of the function, is enclosed in parentheses. The argument is 32. The
function returns the result called return value. The return value is stored in betty.
18. What is a local variable?
A variable defined inside a function. A local variable can only be used inside its function.
15. What is the output of the following?
a. float(32)
b. float("3.14159")
Output:
a. 32.0 The float function converts integers to floating-point numbers.
b. 3.14159 The float function converts strings to floating-point numbers.
16. What do you mean by flow of execution?
In order to ensure that a function is defined before its first use, we have to know the order in
which statements are executed, which is called the flow of execution. Execution always begins at the
first statement of the program. Statements are executed one at a time, in order from top to bottom.
17. Write down the output for the following program.
first = 'throat'
second = 'warbler'
print first + second
Output:
throatwarbler
18. Give the syntax of function definition.
def NAME( LIST OF PARAMETERS ):
STATEMENTS
19. Explain the concept of floor division.
The operation that divides two numbers and chops off the fraction part is known as floor
division.
UNIT III
CONTROL FLOW, FUNCTIONS
PART- A (2 Marks)
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. There is no limit on
the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have
to be one.
9. Explain while loop with example.
Eg:
def countdown(n):
while n > 0:
print n
n = n-1
print 'Blastoff!'
More formally, here is the flow of execution for a while statement:
1. Evaluate the condition, yielding True or False.
2. If the condition is false, exit the while statement and continue execution at the next statement.
3. If the condition is true, execute the body and then go back to step 1
1. What is list?
A list is an ordered set of values, where each value is identified by an index. The values that make up
a list are called its elements. Lists are similar to strings, which are ordered sets of characters, except
that the elements of a list can have any type.
2. Solve a)[0] * 4 and b) [1, 2, 3] * 3.
>>> [0] * 4 [0, 0, 0, 0]
>>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
3.Let list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]. Find a) list[1:3] b) t[:4] c) t[3:] .
>>> list = [’a’, ’b’, ’c’, ’d’, ’e’, ’f’]
>>> list[1:3] [’b’, ’c’]
>>> list[:4] [’a’, ’b’, ’c’, ’d’]
>>> list[3:] [’d’, ’e’, ’f’]
4. Mention any 5 list methods.
append() ,extend () ,sort(), pop(),index(),insert and remove()
5. State the difference between lists and dictionary.
List is a mutable type meaning that it can be modified whereas dictionary is immutable and is a key
value store. Dictionary is not ordered and it requires that the keys are hashable whereas list can store
a sequence of objects in a certain order.
6. What is List mutability in Python? Give an example.
Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable,
i.e., their content can be changed without changing their identity. Other objects like integers, floats,
strings and tuples are objects that cannot be changed.
Example:
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers [17, 5]
7. What is aliasing in list? Give an example.
An object with more than one reference has more than one name, then the object is said to be
aliased. Example: If a refers to an object and we assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a True
8. Define cloning in list.
In order to modify a list and also keep a copy of the original, it is required to make a copy of
the list itself, not just the reference. This process is called cloning, to avoid the ambiguity of the word
“copy”.
9. Explain List parameters with an example.
Passing a list as an argument actually passes a reference to the list, not a copy of the list. For
example, the function head takes a list as an argument and returns the first element:
def head(list):
return list[0]
output:
>>> numbers = [1, 2, 3]
>>> head(numbers)
10. Write a program in Python to delete first element from a list.
def deleteHead(list): del list[0]
Here’s how deleteHead is used:
>>> numbers = [1, 2, 3]
>>> deleteHead(numbers)
>>> print numbers [2, 3]
11. Write a program in Python returns a list that contains all but the first element of the given
list.
def tail(list):
return list[1:]
Here’s how tail is used:
>>> numbers = [1, 2, 3]
>>> rest = tail(numbers)
>>> print rest [2, 3]
12. What is the benefit of using tuple assignment in Python?
It is often useful to swap the values of two variables. With conventional assignments a temporary
variable would be used. For example, to swap a and b:
>>> temp = a
>>> a = b
>>> b = temp
This solution is cumbersome; tuple assignment is more elegant:
>>> a, b = b, a
13. Define key-value pairs.
The elements of a dictionary appear in a comma-separated list. Each entry contains an index and a
value separated by a colon. In a dictionary, the indices are called keys, so the elements are called key-
value pairs.
8. What are the error messages that are displayed for the following exceptions?
a. Accessing a non-existent list item
b. Accessing a key that isn’t in the dictionary
c. Trying to open a non-existent file
a. IndexError: list index out of range
b. KeyError: what
c. IOError: [Errno 2] No such file or directory: 'filename'
9. What are the two parts in an error message?
The error message has two parts: the type of error before the colon, and speci_cs about the
error after the colon.
10. How do you handle the exception inside a program when you try to open a non-existent
file?
filename = raw_input('Enter a file name: ')
try:
f = open (filename, "r")
except IOError:
print 'There is no file named', filename
11. How does try and execute work?
The try statement executes the statements in the first block. If no exception occurs, then except
statement is ignored. If an exception of type IOError occurs, it executes the statements in the except
branch and then continues.
12. What is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes two
arguments: the exception type and specific information about the error.
13. What is a pickle?
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any
type of object to a string suitable for storage in a database and then translate the strings back in to
objects.
14. What are the two methods used in pickling?
The two methods used in pickling are pickle.dump() and pickle.load(). To store a data structure,
dump method is used and to load the data structures that are dumped , load method is used.
15. What is the use of the format operator?
The format operator % takes a format string and a tuple of expressions and yields a string that
includes the expressions, formatted according to the format string.
16. What are modules?
A module is simply a file that defines one or more related functions grouped together. To reuse the
functions of a given module, we need to import the module.
Syntax: import <modulename>
17. What is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Syntax: from <mypackage> import <modulename>
18. What is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py
19. How do you delete a file in Python?
The remove() method is used to delete the files by supplying the name of the file to be deleted as
argument.
Syntax: os.remove(filename)
20. How do you use command line arguments to give input to the program?
Python sys module provides access to any command-line arguments via sys.argv. sys.argv is the list
of command-line arguments. len(sys.argv) is the number of command-line arguments.