[go: up one dir, main page]

0% found this document useful (0 votes)
62 views16 pages

5units 2marks and Answers

Uploaded by

selvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views16 pages

5units 2marks and Answers

Uploaded by

selvi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

GE3151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING


UNIT I - ALGORITHMIC PROBLEM SOLVING
PART- A (2 Marks)
1. Define Algorithm.
 Sequence of instructions for solving a problem or a step by step procedure for solving a problem.
 An algorithm is a set of instructions designed to perform a specific task. This can be a simple process, such as
multiplying two numbers, or a complex operation, such as playing a compressed video file
Example: Algorithm to print "Good Morning"
Step1: Start the program.
Step2: Display the message "Good Morning" to the user.
Step3: Stop the program.

2. Distinguish between pseudo code and flowchart.


S.No Pseudo code Flowchart
1. Short, readable, formally styled English Diagrammatic representation of the logic of the
languages of an algorithm. algorithm.
2. Knowledge about the programming language No basic knowledge about programming is needed.
is needed.
3. Beginners find it difficult to understand. Beginners find it easy to understand.
4. Understanding the flow of data and control is Understanding the flow of data and control is easy.
difficult.
5. Keywords is used in pseudo code like BEGIN, No keywords are used in flowchart.
END,IF, THEN, ENDIF, etc.
6. Easier to convert into source code as pseudo Cannot be easily converted to the source code as
code relatively maps to the syntax. flowchart is a diagrammatic representation.

3. What are the building blocks of algorithm?


Building blocks of an algorithm are,
Statement: a single action in a computer.
State: Transition from one process to another within a specified condition within a timeframe is state.
Control flow: Process of executing the individual statements in the given order is called control flow. Control flow types
include Sequence, Selection and iteration.
Functions: A subprogram which consists of the block of code that performs a particular task.

4. State the properties of algorithm.


Algorithm should be ,
 written in simple English
 each and every instruction should be precise and unambiguous
 Instructions in an algorithm should not be repeated infinitely
 Algorithm should conclude after a finite number of steps
 Algorithm should have an end point
 Results should be derived only after the algorithm terminates.

5. State the Qualities of an algorithm.


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

6. What is meant by problem solving?


It is the systematic approach to solve the problem and create number of solutions. Starts with the problem
specification and ends with a correct program.
Example:

Page 1 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A
Finding greatest of two numbers includes , different logic for comparing two numbers as defining the variables
as a & b , logics include a>b or a<b or a%b == a or a%b ==b or any logic can be defined and finally the
program is implemented.

7. What is called control flow?


The process of executing the individual statements in a given order is called the control flow.
The control can be executed in three ways,
1. Sequence 2. Selection 3. Iteration.

8. What are the benefits of using functions.


 Reduction in line of code
 Code reuse and Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability

9. Define a flowchart.
 Flow chart is defined as graphical representation of the logic for problem solving.
 The purpose of flowchart is making the logic of the program clear in a visual representation.
 A flowchart is a type of diagram that represents a workflow or process.
 The flowchart shows the steps as boxes of various kinds, and their order by connecting the boxes with arrows.
This diagrammatic representation illustrates a solution model to a given problem.

10. What are the symbols used in a flowchart?

11. Rules for drawing a flowchart.


 The flowchart should be clear, neat and easy to follow.
 The flowchart must have a logical start and finish.
 Only one flow line should come out from a process symbol.
 Only one flow line should enter a decision symbol. However, two or three flow lines may leave the decision
symbol.
 Only one flow line is used with a terminal symbol.
 Within standard symbols, write briefly and precisely.
 Intersection of flow lines should be avoided.
12. What are the advantages of flowchart?
 Communication: - Flowcharts are better way of communicating the logic of a system to all concerned.
 Effective analysis: -With the help of flowchart, problem can be analyzed in more effective way.
 Proper documentation: - Program flowcharts serve as a good program documentation, which is needed for
various purposes.
 Efficient Coding: - The flowcharts act as a guide or blueprint during the systems analysis and program
development phase.
 Proper Debugging: - The flowchart helps in debugging process.
 Efficient Program Maintenance: - The maintenance of operating program becomes easy with the help of
flowchart. It helps the programmer to put efforts more efficiently on that part.

Page 2 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

13. What are the disadvantages of flowchart?


 Complex logic: - Sometimes, the program logic is quite complicated. In that case, flowchart becomes complex
and clumsy.
 Alterations and Modifications: - If alterations are required the flowchart may require re-drawing completely.
 Reproduction: - As the flowchart symbols cannot be typed, reproduction of flowchart becomes a problem.
 Cost: For large application the time and cost of flowchart drawing becomes costly.

14. What is a psuedocode and write its properties.


Pseudo code consists of short, readable and formally styled English languages used for explain an algorithm.
 It does not include details like variable declaration, subroutines.
 It is easier to understand for the programmer or non programmer to understand the general working of the
program, because it is not based on any programming language.
 It gives us the sketch of the program before actual coding.
 It is not a machine readable
 Pseudo code can’t be compiled and executed.
 There is no standard syntax for pseudo code.

15. what are the guidelines for writing the psuedocode?


 Write one statement per line
 Capitalize initial keyword
 Indent to hierarchy
 End multiline structure
 Keep statements language independent

16. What are the keywords in pseudocode?


The following gives common keywords used in pseudocodes.
1. //: This keyword used to represent a comment.
2. BEGIN,END: Begin is the first statement and end is the last statement.
3. INPUT, GET, READ: The keyword is used to inputting data.
4. COMPUTE, CALCULATE: used for calculation of the result of the given expression.
5. ADD, SUBTRACT, INITIALIZE used for addition, subtraction and initialization.
6. OUTPUT, PRINT, DISPLAY: It is used to display the output of the program.
7. IF, ELSE, ENDIF: used to make decision.
8. WHILE, ENDWHILE: used for iterative statements.
9. FOR, ENDFOR: Another iterative incremented/decremented tested automatically.

17. List the advantages and disadvantages of


pseudocode. Advantages:
 Pseudo is independent of any language; it can be used by most programmers.
 It is easy to translate pseudo code into a programming language.
 It can be easily modified as compared to flowchart.
 Converting a pseudo code to programming language is very easy as compared with converting a flowchart to
programming language.
Disadvantages:
 It does not provide visual representation of the program’s logic.
 There are no accepted standards for writing pseudo codes.
 It cannot be compiled nor executed.
 For a beginner, It is more difficult to follow the logic or write pseudo code as compared to flowchart.

18. What is a programming language?


A programming language is a set of symbols and rules for instructing a computer to perform specific task. Each
programming language has a flow of execution and a unique syntax to be followed. It categorizes as, High level
language, low level language and assembly language.

Page 3 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit I - 2 Marks Q & A

19. Differentiate high level, low level and assembly level languages

Low level/ Machine level language Assembly level language High level language
Programs are written only in 0s and Programs are wirtten in mnuemonics Programs are written using English
1s ie. binary will be understood by like ADD A,B words and symbols.
the computer.
There is no conversion required. The Assembler converts the The compiler and the interpreter
assembly level language to the does the conversion of the high level
machine language. languages to the machine language.
20. What are the simple strategies for developing an algorithm?
Simple strategies for developing an algorithm include Iteration and Recursion
Iteration: Sequence of statements executed repeatedly until a specified condition is satisfied is iteration.
Recursion: A function that calls itself again and again until a specified condition is satisfied is called recursion.

21. List down the problem solving techniques.


The problem solving techniques are Algorithm, Flowchart, Psuedocode
22. What are the steps in algorithmic problem solving?
Understanding the problem, Decide on computational means, Design an algorithm, Prove correctness, Analyze the
algorithm, Code the algorithm
23. Write an algorithm to accept two numbers and compute the SUM.
Step1: Start the program
Step2: Get the inputs from the user and assign them to variables a and b.
Step3: Calculate the value for variable SUM , using SUM = a+b
Step4: display the output stored in the variable , SUM
Step5: Stop the program.
24. Name the four types of scalar objects Python has.
The commonly used scalar types in Python are
int - Any integer like 10, -20
float - floating point number , 10.5, 21.3
complex - numbers with real part and imaginary part, 3+4j
bool - True or False with values 1 or 0.
str - a sequence of characters
bytes - sequence of unsigned 8 bit entiites.

25. Differentiate Compiler and Interpreter.


Compiler Interpreter
Compiler takes entire program as input. Interpreter takes single instruction as input.
Intermediate object code is generated. No intermediate object code is generated.
Program need not be compiled every time. Every time a high level program is converted into a low
level program.
Errors are displayed after entire program is checked. Error are displayed after every instuction.

Ex: C Compiler Ex: Python.

PART B

1. Write an algorithm and program to find minimum in a list.


2.Discuss in detail about symbols used in flowchart and also summarize the advantage and disadvantage of flowchart.
3. Discuss in detail Towers of Hanoi Problem
4. Explain in detail about Building Blocks of Algorithm
5. Explain in detail about the steps involved in Algorithmic problem solving.
6.Explain in detail about the simple strategies for developing an algorithm.
7. Write the algorithm, flowchart and pseudocode for inserting a card in a list of sorted cards.
8. Write the algorithm and flowchart and pseudocode for guessing an integer in a range.

Page 4 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit II - 2 Marks Q
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT II DATA, EXPRESSIONS, STATEMENTS
PART – A (2 MARKS)

1. Name the four types of Scalar objects.(D/J-18)


A scalar is a type that can have a single value such as 5, 3.14, or ‘Bob’.
The commonly used scalar types in Python are: Int, Float, Complex, Boolean, String, Bytes, None

2. What is a tuple? How literals of type tuple are written? Give example.(D/J-18).
A tuple is created by surrounding objects with ()'s and separating the items with commas (,). An empty tuple is
empty ()'s. An interesting question is how Python tells an expression from a 1-tuple. A 1-element tuple has a
single comma: (1,). An expression lacks the comma: (1). A pleasant consequence of this is that an extra comma
at the end of every tuple is legal; for example, (9, 10, 56, ).
Examples:
xy= (2, 3)
personal= ('John',14,5*12+6)
singleton= ("hello",)
The elements of a tuple do not have to be the same type. A tuple can be a mixture of any Python data types,
including other tuples

3. Outline the logic to swap the contents of two identifiers without using third variable.(A/M-19)
Logic:
a=int(input(“Enter the value of a”))
b=int (input(“Enter the value of b”))
a=a+b
b=a-b
a=a-b
print(a,b)

4. State about Logical operators available in python language with example. (A/M -19)
In Python, the primary logical operators are AND, OR, and NOT. A boolean expression or valid expression
evaluates to one of two states True or False. Python provides the boolean type that can be either set to False or
True. Many functions and operations return boolean objects.

5. What are keywords? Give examples.(D/J-2019)


Keywords are the reserved words in Python. We cannot use a keyword as variable name, function name or any
other identifier. Example: False, None, True, and, as, assert, break. Etc.

6. State the reason to divide the program into functions.(D/J-2019)


Function are used for divide a large code into module, due to this we can easily debug and maintain the code.
For example if we write a calculator programs at that time we can write every logic in a separate function (For
addition sum(), for subtraction sub()). Any function can be called many times.

7. Define assignment statement.


A statement that assigns a value to a name (variable). To the left of the assignment operator, =, is a name. To the
right of the assignment operator is an expression which is evaluated by the Python interpreter and
then assigned to the name.

8. Define Identifiers in Python.


A Python identifier is a name used to identify a variable, function, class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters,
underscores and digits (0 to 9)

9. What is the comment statement in python?


A comment is text that doesn't affect the outcome of a code, it is just a piece of text to let someone know what
you have done in a program or what is being done in a block of code. In python we use # special character to
start the comment. Lets take few examples to understand the usage.
# This is just a comment. Anything written here is ignored by Python

Page 1 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit II - 2 Marks Q
10. Define variables in python.
In Python, variables are a storage placeholder for texts and numbers. It must have a name so that you are able to
find it again. The variable is always assigned with the equal sign, followed by the value of the variable.

11. Explain Input and output statements in python.


In Python, we have the input() function to allow this. The syntax for input () is input([prompt]) where prompt is
the string we wish to display on the screen.
Ex . : a = int(input(“Enter the value of a”))
We use the print() function to output data to the standard output device (screen).
print(a)
12. List the data types in python.

13. What are the operators in Python?


Arithmetic Operators, Relational Operators, Assignment Operators, Bitwise Operators, Logical Operators
Membership Operators, Identity Operators
14. Define functions in python?
A function is a block of code which only runs when it is called.
Creating a Function
In Python a function is defined using the def keyword:
def my_function():
print("Hello from a function")
Calling a Function
To call a function, use the function name followed by parenthesis:
my_function()

15. Give the syntax for variable length arguments.


The special syntax, *args and **kwargs in function definitions is used to pass a variable number of arguments to
a function. The single asterisk form ( *args ) is used to pass a non-keyworded, variable-length argument list, and
the double asterisk form is used to pass a keyworded, variable-length argument list Syntax for a function with
non-keyword variable arguments is this –
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite return [expression].

16. Point out the difference between recursive and iterative technique.
• Recursive approach: In recursive approach the function calls itself until the condition is met. And it is slower
than iteration, which means it uses more memory than iteration. Recursion is like a selection structure, and
which makes code smaller and clean. And a function partially defined by itself. Here tracing the code will be
more difficult in the case large programs.
• Iterative approach: Iterative approach is a repetition process until the condition fails, here loops are used
such as for, while etc. Here code may be longer but it is faster than recursive. And it consumes less memory
compared to recursive approach. If the loop condition is always true in such cases it will be an infinite loop

17. What are the various operators in python.


Python language supports the following types of operators.
Arithmetic Operators, Comparison (Relational) Operators, Assignment Operators, Logical Operators, Bitwise
Operators, Membership Operators, Identity Operators

18. Compose the importance of indentation in python.


Python programs get structured through indentation, i.e. code blocks are defined by their indentation. In Python
language, indentation is used to determine the structure instead of using braces or keywords.

Page 2 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit II - 2 Marks Q
19. 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.

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

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

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

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

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

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

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

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

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

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

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

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

32. Illustrate the use of * and + operators in string with example.


The * operator performs repetition on strings and the + operator performs concatenation on strings.
Page 3 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit II - 2 Marks Q
Example:
>>> ‘Hello*3’ Output: HelloHelloHello
>>>’Hello+World’ Output: HelloWorld

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

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

35. 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
.
36. Define a local variable and global variable?
A variable defined inside a function. A local variable can only be used inside its function.
A variable defined outside a function. A global variable can be used anywhere inside a program.

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

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

39. Give the syntax of function definition.


def NAME( LIST OF PARAMETERS ): STATEMENTS

40. Explain the concept of floor division.


The operation that divides two numbers and chops off the fraction part is known as floor division.

PART – B (16 MARKS)

1. Sketch the structures of interpreter and compiler. Detail the difference between them. Explain how python
works in interactive mode and script mode with examples.( D/J -19)
2. Summarize the precedence of mathematical operators in python.( D/J -19)
3. Explain the syntax and structure of user defined functions in Python with examples. Also discuss about
parameter passing in functions.( D/J -19)
4. Write a python function to swap the values of two variables.( D/J -19)
5. Describe about the concept of precedence and associativity of operators with example.(A/M-19)
6. Mention the list of keywords available in Python. Compare it with variable name.(A/M-19)
7. What are statements? How are they constructed from variable and expressions in Python? (A/M-19)
8. What is a numeric literal? Give examples.(D/J-18)
9. Appraise the arithmetic operators in Python with an example. (D/J-18)
10. Outline the operator precedence of arithmetic operators in Python. (D/J-18)
11. Write a Python program to exchange the value of two variables. (D/J-18)
12. Write a Python using function to find the sum of first “n” even numbers and print the result. (D/J-18).
13. Explain various types of operators used in Python.
14. Explain Values & types supported in Python.
15. What are the different function prototypes? Explain it with suitable example.
16. What are the different types of arguments available in python.
17. Explain in detail the different ways of importing a module in python.
18. Write a python program to circulate values of n variables.

Page 4 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit III - 2 Marks Q
GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT III - CONTROL FLOW, FUNCTIONS
PART- A (2 Marks)
1. What a python program to accept two inputs, find the greatest and print the result ?
Num1= int(input(“enter the value of num1”))
Num2= int(input(“enter the value of num2”))
if(Num1>Num2):
print(“Num1 is greatest”)
else:
print(“Num2 is greatest”)

2. State the reasons to divide programs into functions.


Easy to understand, Easy to debug, Easy to execute.

3. Present the flow of execution for a WHILE statement.


While(condition):
Body of while

4. Comment with an example on the use of local and global variables with the same identifier name.
Local: The value which is declared inside the function
Global: The value which is declared outside the function
a=5
def test():
a=10
print(a)
print(a)

5. State about Logical Operators available in Python programming language.


>, <, ==, >=, <=, !=

6. Define Boolean expression with example.


A boolean expression is an expression that is either true or false. The values true and false are called Boolean
values. Eg : >>> 5 == 6
False
True and False are special values that belongs to the type bool; they are not strings:

7. What are the different types of operators?


 Arithmetic Operator (+, -, *, /, %, **, // )
 Relational operator ( == , !=, <>, < , > , <=, >=)
 Assignment Operator ( =, += , *= , - =, /=, %= ,**= )
 Logical Operator (AND, OR, NOT)
 Membership Operator (in, not in)
 Bitwise Operator (& (and), | (or) , ^ (binary Xor), ~(binary 1’s complement , << (binary left shift), >> (binary
right shift))
 Identity(is, is not)

8. Explain modulus operator with example.


The modulus operator works on integers and yields the remainder when the first operand is divided by the
second. In Python, the modulus operator is a percent sign (%). The syntax is the same as for other operators:
Eg:
>>> remainder = 7 % 3
>>> print(remainder)
1
So 7 divided by 3 is 2 with 1 left over.

9. Explain relational operators.


The == operator is one of the relational operators; the others are:
x! = y # x is not equal to y
x>y # x is greater than y
x<y # x is less than y
x >= y # x is greater than or equal to y

Page 1 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit III - 2 Marks Q
x <= y # x is less than or equal to y

10. Explain Logical operators


There are three logical operators: and, or, and not.
For example,
x > 0 and x < 10 is true only if x is greater than 0 and less than 10.
n%2 == 0 or n%3 == 0 is true if either of the conditions is true, that is, if the number is divisible by 2 or 3.
Finally, the not operator negates a Boolean expression, so not(x > y) is true if x > y is false, that is, if x is less
than or equal to y. Non-zero number is said to be true in Boolean expressions.

11. What is conditional execution?


The ability to check the condition and change the behavior of the program accordingly is called conditional
execution.
Syntax:
if:
statement:
Example:
if x > 0:
print 'x is positive'
The boolean expression after ‘if’ is called the condition. If it is true, then the indented statement gets executed.
If not, nothing happens.

12. What is alternative execution?


A second form of if statement is alternative execution, that is, if …else, where there are two possibilities and the
condition determines which one to execute.
Example:
if x%2 == 0:
print("x is even")
else:
print("x is odd")

13. What are chained conditionals?


Sometimes there are more than two possibilities and we need more than two branches. One way to express a
computation like that is a chained conditional:
Example:
if (x < y):
print("x is less than y")
elif (x > y):
print("x is greater than y")
else:
print("x and y are equal")

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.

14. Explain while loop with example.


Example:
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 and continue execution at the next statement.
3. If the condition is true, execute the body and then go back to step 1

15. Explain ‘for loop’ with example.


The general form of a for statement is
Syntax:
for variable in sequence:
code block

Page 2 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit III - 2 Marks Q
Example:
x=4
for i in range(0, x):
print(i)

16. What is a break statement?


When a break statement is encountered inside a loop, the loop is immediately terminated and the program
control resumes at the next statement following the loop.
Example:
while True:
line = raw_input('>')
if (line == "done"):
break
print(line)
print("Done ! ")

17. What is a continue statement?


The continue statement works somewhat like a break statement. Instead of forcing termination, it forces the next
iteration of the loop to take place, skipping any code in between.
Example:
for num in range(2,10):
if (num%2==0):
print(“Found an even number”, num)
continue
print(“Found a number”, num)

18. Compare return value and composition.


Return Value:
Return gives back or replies to the caller of the function. The return statement causes our function to exit and
hand over back a value to its caller.
Example:
def area(radius):
temp = math.pi * radius**2
return temp

Composition:
Calling one function from another is called composition.
Example:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result

19. What is recursion?


The process in which a function calls itself directly or indirectly is called recursion and the corresponding
function is called as recursive function.
Example:
def factorial(n):
if (n == 1):
return(1)
else:
return(n * factorial(n-1))

20. Explain global and local scope.


The scope of a variable refers to the places that we can see or access a variable. If we define a variable on the
top of the script or module, the variable is called global variable. The variables that are defined inside a class or
function is called local variable.
Example:
b=5
def my_local():
a=10
print(“Value of Local Variable”,a)
print(“Value of Global Variable”,b)
Page 3 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit III - 2 Marks Q
21. Compare string and string slices.
A string is a sequence of character.
A segment of a string is called string slice, selecting a slice is similar to selecting a character.
Eg:
>>> s ='Monty Python'
>>> print(s[0:5])
Monty

22. Define string immutability.


Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t mutate the string but
can change what value of the variable to a new string.

23. Mention a few string functions.


captilize() – to capitalize first character of string
count(sub) – to count number of occurrences of sub in string
lower() – to convert a string to lower case
split() – to get a list of words in string
isalpha() – to check whether the string contains only English alphabets or not.

24. What are string methods?


 A method is similar to a function—it takes arguments and returns a value—but the syntax is different. For
example, the method upper takes a string and returns a new string with all uppercase letters:
 Instead of the function syntax upper(word), it uses the method syntax word.upper() .
>>> word = 'banana'
>>> new_word = word.upper()
>>> print(new_word)
BANANA

25. Explain about string module.


The string module contains number of useful constants and classes, as well as some deprecated legacy functions that
are also available as methods on strings. Eg: import string

26. What is the purpose of pass statement?


Using a pass statement is an explicit way of telling the interpreter to do nothing.
Eg:
def bar():
pass
If the function bar() is called, it does absolutely nothing.

PART- B (16 Marks)


1. Discuss in details about various Looping Statements in Python with suitable example.
2. Explain briefly about various Iterative Statements in Python with suitable example.
3. Discuss in details about various Conditional Statements in Python with suitable example.
4. Explain briefly about various Decision Making Statements in Python with examples.
5. Explain with an example while loop, continue statement and break statement in Python.
6. Python Strings are immutable. Justify your answer with an example.
7. Write a python program to perform Binary Search. Trace it with a set of input values.
8. Write a python program to perform Linear Search. Trace it with a set of input values.
9. Discuss in detail about Recursion. Write a program to find the factorial of a given number using recursion.
10. Write a python program to find the factorial of a given number with recursion and without using recursion.
11. Discuss about various string operations and methods with necessary examples.
12. Discuss in details about various functions' argument types with suitable examples.
13. Explain about each function prototype with necessary illustrative programs.
14. Write a python program to print first "N" numbers in Fibonacci Series.
15. Discuss in detail about List Comprehension with example.
16. Discuss in detail about various operators in python with example.

Page 4 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q
GE3151 - PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT IV - COMPOUND DATA: LISTS, TUPLES, DICTIONARIES
PART- A (2 Marks)
1. What is a list?
 A list is an ordered set of values, where each value is identified by an index.
 Values in the list are called elements / items. It can be written as a list of comma-separated items (values)
between square brackets [ ].
 Items in the lists can be of different data types and List is a mutable 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)list[:4] c) list[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.


Creating a copy of a list is called aliasing. When you create a copy both list will be having the same memory location.
Changes in one list will affect another list. Aliasing refers to having different names for same list values.
Example:
>>> a = [1, 2, 3]
>>> b=a
>>> b is a
>>> True
>>> a[0]=5
>>> print(a)
[5,2,3]
>>> print(b)
[5,2,3]

8. Define cloning in list.


To avoid the disadvantages of copying we are using cloning. creating a copy of a same list of elements with two different
memory locations is called cloning. Changes in one list will not affect locations of another list. Cloning is a process of
making a copy of the list without modifying the original list. The following are the three ways to clone a list
1. Slicing

Page 1 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q
2. list()method
3. copy()method
Example:
>>>a=[1,2,3,4,5]
>>>b=a[:]
>>>print(b)
[1,2,3,4,5]
>>>a is b
False

9. Explain List parameters with an example.


 In python, arguments are passed by reference.
 If any changes are done in the parameter which refers within the function, then the changes also reflects back in
the calling function.
 When a list to a function is passed, the function gets a reference to the list.
 Passing a list as an argument actually passes a reference to the list, not a copy of the list.
 Since lists are mutable, changes made to the elements referenced by the parameter change the same list that the
argument is referencing.
Example
def remove(a):
a.remove(1)
a=[1,2,3,4,5]
remove(a)
print(a)
output
[2,3,4,5]

10. What is the benefit of using tuple assignment in Python?


 Tuples are faster than lists.
 If the user wants to protect the data from accidental changes, tuple can be used.
 Tuples can be used as keys in dictionaries, while lists can't.
 It is often useful to swap the values of two variables.

11. Define key-value pairs.


 An element in dictionary has a key: value pair. All elements in dictionary are placed inside the curly braces i.e. {
}.
 Elements in Dictionaries are accessed via keys and not by their position. The values of a dictionary can be any
data type. Keys must be immutable data type (numbers, strings, tuple).
 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.

12. Define dictionary with an example.


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

13. How to return tuples as values?


A Tuple is a comma separated sequence of items. It is created with or without ( ). A function can return one
value. if you want to return more than one value from a function. we can use tuple as return value.
Example:
def div(a,b):
r=a%b
q=a//b
return(r,q)

Page 2 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q
a=eval(input("enter a value:"))
b=eval(input("enterb value:"))
r,q = div(a,b)
print("reminder:",r)
print("quotient:",q)

14. List two dictionary operations.


i. del - removes key-value pairs from a dictionary
ii. len() - returns the number of key-value pairs

15. Define dictionary methods with an example.


 A method is similar to a function—it takes arguments and returns a value— but the syntax is different.
>>> a = {1: 'ONE', 2: 'two', 3: 'three'}
>>> a.keys()
dict_keys([1, 2, 3])
>>> a.values()
dict_values(['ONE', 'two', 'three'])

16. Define List Comprehension.


 List comprehensions provide a concise way to apply operations on a list. It creates a new list in which each
element is the result of applying a given operation in a list.
 It consists of brackets containing an expression followed by a “for” clause, then a list. The list comprehension
always returns a result list.
Syntax:
list = [ expression for item in list if conditional ]
Example:
>>> L = [x**2 for x in range(0,5)]
>>> print(L)
[0, 1, 4, 9, 16]
17. What are list operations?
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Updating
vi. Membership
vii. Comparison

18. How to create a list in python? Illustrate the use of negative indexing of list with example.
 List is an ordered sequence of items. Values in the list are called elements / items. It can be written as a list of
comma-separated items (values) between square brackets [ ]. Items in the lists can be of different data types.
Example:
>>> a = [1,2,3]
>>> print(a)
[1,2,3]
 Negative Indexing
Python supports negative indexing for a sequence types like list. The last item on the list takes the -1 index and
second to the last item has the -2 index and so on.
>>> a = [1,2,3]
>>> print(a[-1])
3
>>> print(a[-2])
2

19. What are the different ways to create a list?


my_list = []
my_list = [1, 2, 3]
my_list = [1, "Hello", 3.4]
my_list = [0 for i in range(50)]

20. What is mutability?

Page 3 of
Saranathan College of Engineering, Tiruchirappalli -
GE3151 - Problem Solving and Python Programming - Unit IV - 2 Marks Q
 Lists are mutable (can be changed). Mutability is the ability for certain types of data to be changed without
entirely recreating it.
 An item can be changed in a list by accessing it directly as part of the assignment statement.
 Using the indexing operator (square brackets [ ]) on the left side of an assignment, one of the list items can be
updated.

21. Define Tuple.


 A tuple is same as list, except that the set of elements is enclosed in parentheses instead of square brackets.
 A tuple is an immutable list. i.e. once a tuple has been created, you can't add elements to a tuple or remove
elements from the tuple.
 But tuple can be converted into list and list can be converted in to tuple.

22. Define list slicing.


 List slicing is an operation that extracts a subset of elements from an list and packages them as another list.
Syntax: Listname [ start : stop : steps ]
>>> a=[9,8,7,6,5,4]
>>> a[0:6:2]
[9, 7, 5]

23. What are the benefits of tuple?


i. Tuples are faster than lists.
ii. If the user wants to protect the data from accidental changes, tuple can be used.
iii. Tuples can be used as keys in dictionaries, while lists can't.

PART B (16 Marks)


1. Explain in detail about list, list operations and list slices.
2. Explain in detail about list methods and list loops with examples.
3. Explain in detail about mutability and tuples with a Python Program.
4. What is tuple assignment? Explain it with an example.
5. Is it possible to return tuple as values? Justify your answer with an example.
6. Explain in detail about dictionaries operations and methods.
7. Write a python program to implement insertion sort, selection sort, merge sort and histogram.
8. Demonstrate with code the various operations that can be performed on tuples.
i. What is dictionary in Python? Give examples.
ii. Appraise the operations for dynamically manipulating dictionaries.
9. i. write a short note on cloning and aliasing.
ii. Write a short note on Advanced list processing.
10. Explain the following:
i. List Slicing & List Mutability
ii. List Accessing Methods & List Comprehension
11. Outline the algorithm and write a python program to sort the numbers in ascending order using merge sort.
12. Describe Built in functions with
i. Tuples
ii. List
iii. Dictionaries
13. Explain in detail about List as argument and tuple as return value with an example.

Page 4 of
Saranathan College of Engineering, Tiruchirappalli -

You might also like