GE8151-Problem Solving and Python Programming
TWO MARKS WITH ANSWERS
UNIT-3 CONTROL FLOW, FUNCTIONS
1. 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.
2. 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)
3. Write about 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
4. Write about 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
x <= y # x is less than or equal to y
5. What is conditional execution?
The ability to check the condition and change the behavior of the program accordingly is
called conditional execution.
Example: if statement:
The simplest form of if statement is:
Syntax:
if
statement:
Eg:
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.
6. 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.
Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd
7. 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:
Eg:
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.
8. What is 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.
9. Explain ‘for loop’ with example.
The general form of a for statement is
Syntax:
for variable in sequence:
code block
Eg:
x=4
for i in range(0, x):
print i
10. 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.
Eg:
while True:
line = raw_input('>')
if line == 'done':
break
print line
print 'Done!'
11. 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.
Eg: for num in range(2,10):
if num%2==0;
print “Found an even number”, num
continue
print “Found a number”, num
12. 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.
Eg:
def area(radius):
temp = math.pi * radius**2
return temp
Composition:
Calling one function from another is called composition.
Eg:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
13. 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.
Eg:
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
14. 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.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)
15. Compare string and string slices.
A string is a sequence of character.
Eg: fruit = ‘banana’
String Slices :
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
>>> print s[6:12]
Python
16. 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.
Program:
a = “foo”
# a now points to foo
b=a
# b now points to the same foo that a points to
a=a+a
# a points to the new string “foofoo”, but b points to the same old “foo”
print a
print b
Output:
#foofoo
#foo
It is observed that ‘b’ hasn’t changed even though ‘a’ has changed.
17. Mention a few string functions.
s.captilize() – Capitalizes first character of string
s.count(sub) – Count number of occurrences of sub in string
s.lower() – converts a string to lower case
s.split() – returns a list of words in string
18. 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
19. 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:
Program:
import string
text = "Monty Python's Flying Circus"
print "upper", "=>", string.upper(text)
print "lower", "=>", string.lower(text)
print "split", "=>", string.split(text)
print "join", "=>", string.join(string.split(text),"+")
print "replace", "=>", string.replace(text,"Python", "Java")
print "find", "=>", string.find(text, "Python"),string.find(text, "Java")
print "count", "=>", string.count(text, "n")
Output:
upper => MONTY PYTHON'S FLYING CIRCUS
lower => monty python's flying circus
split => ['Monty', "Python's", 'Flying', 'Circus']
join => Monty+Python's+Flying+Circus
replace => Monty Java's Flying Circus
find => 6 -1
count => 3
20. 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.
21. Define return statement.
The return keyword is used to return values from a function. A function may or may not
return a value. If a function does not have a return keyword, it will send None.
Syntax: return[exp_list]
22. 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.
23. 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.
24. 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.
25. What is type coercion? Give example.
Automatic method to convert between data types is called type coercion. For
Mathematical operators, if any one operand is a float, the other is automatically converted to
float.
Eg:
>>> minute = 59
>>> minute / 60.0
0.983333333333
26. What are the two types of functions?
Built_in function and user defined function
27. List any three python built_in function.
abs()-The absolute value of a number is returned
min()- finding minimum of a list
max()=Finding maximum of a list
28. Define Lifetime of the variable.
Lifetime of a variable is the time during which the variable exits in the memory. The
Lifetime of variables within a function is as extended as the function execute.
29. What is replication operator?
* is the symbol of replication operator which will repeated the string in mentioned
number of times.
30. Define Escape sequence.
Control characters are special character that is not displayed on the screen. Rather they
control the display of output. An escape sequence is a character that gets interpreted when placed
inside a single or double quote. They are usually represented as a backlash notation(\).