SlideShare a Scribd company logo
1 of 17
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
UNIT III
CONTROL FLOW, FUNCTIONS
PART- A (2 Marks)
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. 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.
4. 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
x <= y # x is less than or equal to y
5. 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.
6. 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.
7. 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'
8. 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.
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
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.
PART B (16 MARKS)
1. Explain types of operators.
i)Arithmetic Operators
Assume variable a holds 10 and variable b holds 20, then-
Operator Description Example
+ Addition Adds values on either side of
the operator
a + b = 30
-Subtraction Subtracts right hand operand
from left hand operand
a – b = -10
* Multiplication Multiplies values on either
side of the operator
a * b = 200
/ Division Divides left hand operand by
right hand operand
b / a = 2
% Modulus Divides left hand operand by
right hand operand and
returns remainder
b % a = 0
** Exponent Performs exponential power
calculation on operators
a**b =10
// Floor Division The division of operands
where the result is thequotient
in which the digits after the
decimal point are removed
9//2 = 4 and 9.0//2.0 = 4.0
ii) Python Comparison Operators
These operators compare the values on either sides of them and decide the relation among them. They
are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
Operator Description Example
== If the values of two operands
are equal, then the condition
becomes true.
a == b is not true
!= If values of two operands are
not equal, then condition
becomes true.
a!=b is true
<> If values of two operands are
not equal, then condition
becomes true
a <> b is true
> If the value of left operand is
greater than the value of right
operand, then condition
becomes true
a > b is not true
< If the value of left operand is
less than the value of right
operand, then condition
becomes true
a < b is true
>= If the value of left operand is
greater than or equal to the
value of right operand, then
condition becomes true
a >= b is not true
<= If the value of left operand is
less than or equal to the value
of right operand, then
condition becomes true
a <= b is true
(iii) 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.
(iv) Assignment operators
Operator Description Example
= Assigns values from rightside
operands to left side operand.
c = a + b assigns value of a +
b into c
+= Add AND It adds right operand to the
left operand and assign the
result to left operand
c += a is equivalent to c = c +
a
-= Subtract AND It subtracts right operand
from the left operand and
assign the result to left
operand
c -= a is equivalent to c = c -
a
*= Multiply AND It multiplies right operand
with the left operand and
assign the result to left
operand
c *= a is equivalent to c = c *
a
/= Divide AND It divides left operand withthe
right operand and assign the
result to left operand
c /= a is equivalent to c = c /
ac /= a is equivalent to c = c /
a
%= Modulus AND It takes modulus using two
operands and assign theresult
to left operand
c %= a is equivalent to c = c
% a
**= Exponent AND Performs exponential power
calculation on operators and
assign value to the left
operand
c **= a is equivalent to c = c
** a
//= Floor Division It performs floor division on
operators and assign value to
the left operand
c //= a is equivalent to c = c //
a
2. Explain conditional alternative and chained conditional.
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 indentedstatement
gets executed. If not, nothing happens. if statements have the same structure as function
definitions: a header followed by an indented body. Statements like this are called compound
statements. There is no limit on the number of statements that can appear in the body, but there
has to be at least one. Occasionally, it is useful to have a body with no statements .In that case,
you can use the pass statement, which does nothing.
if x < 0:
pass # need to handle negative values!
Alternative execution (if-else):
A second form of if statement is alternative execution, in which there are two possibilities and
the condition determines which one gets executed. The syntax looks like this:
Eg:
if x%2 == 0:
print 'x is even'
else:
print 'x is odd'
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a
message to that effect. If the condition is false, the second set of statements is executed. Since the
condition must be true or false, exactly one of the alternatives will be executed. The alternatives are
called branches, because they are branches in the flow of execution.
Chained conditionals(if-elif-else):
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.
Eg:
if choice == 'a':
draw_a()
elif choice =='b':
draw_b()
elif choice =='c':
draw_c()
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them
is true, the corresponding branch executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.
3. Explain in detail about Fruitful Functions.
Return values
Some of the built-in functions we have used, such as the math functions, produce results. Calling
the function generates a value, which we usually assign to a variable or use as part ofan
expression.
The first example is area, which returns the area of a circle with the given radius:
Eg:
def area(radius):
temp = math.pi * radius**2
return temp
We have seen the return statement before, but in a fruitful function the return statement includes
an expression. This statement means: “Return immediately from this function and use the
following expression as a return value.” The expression can be arbitrarily complicated, so we
could have written this function more concisely:
def area(radius):
return math.pi * radius**2
On the other hand, temporary variables like temp often make debugging easier. Sometimes it is
useful to have multiple return statements, one in each branch of a conditional:
def absolute_value(x):
if x < 0:
return -x
else:
return x
4. Write a Python program to find the square root of a
number.n=int(input("Enter a number to find Square
Root:"))
approx = 0.5 * n
better = 0.5 * (approx + n/approx)
while better != approx:
approx = better
better = 0.5 * (approx + n/approx)
print(approx)
5. Explain RECURSION.
The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is called as recursive function. Using recursive algorithm, certain
problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH),
Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc.
Python program:
# take input from the user
num = int(input("Enter a number: "))
def fact(n):
if n == 1:
return n
else:
return n*fact(n-1)
print(“Factorial of n numbers is :%d” %(fact(n)))
6. Explain string slices and string immutability.
String slices
A segment of a string is called a slice . Selecting a slice is similar to selecting a character:
>>> s ='Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
The operator [n:m]returns the part of the string from the “n-eth” character to the “m-eth”
character, including the first but excluding the last. If you omit the first index (before the colon), the
slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the
string:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
If the first index is greater than or equal to the second the result is an empty string, represented by
two quotation marks:
>>> fruit ='banana'
>>> fruit[3:3]
An empty string contains no characters and has length 0, but other than that, it is the same as any
other string.
String immutability.
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. You can’t mutate
the string but can change what value of the variable to a new string.
Eg:
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 the value.
7. Explain string functions and methods.
There are a number of useful operations that can be performed with string. One of the most useful
of these is the function split. This function takes a string (typically a line of input from the user) and
splits it into individual words.
Another useful function is lower, which converts text into lower case.
Eg:
>>> line = input(“What is your name?”)
What is your name? Timothy Alan Budd
>>> lowname = line.lower()
>>> print lowname.split()
[‘timothy’, ‘alan’, ‘budd’]
Other useful functions will search a string for a given text value, or strip leading or trailing white
space from a string. An alternative version of split takes as argument the separator string.The
string is broken into a list using the separator as a division. This can be useful, for example, for
breaking a file path name into parts:
Eg:
>>> pathname = ‘/usr/local/bin/ls’
>>> pathname.split(‘/’)
[‘usr’, ‘local’, ‘bin’, ‘ls’]
The inverse of split is the function join. The argument to join is a list of strings. The value to the left
of the dot is the separator that will be placed between each element. Often this is simply an empty
string. The values in the list are laminated along with the separator to produce the result string.
>>> lst = [‘abc’,’pdq’,’xyz’]
>>> pri
nt ‘::’.join(lst)
abc::pdq::xyz
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
This form of dot notation specifies the name of the method, upper, and the name of the string to
apply the method to, word. The empty parentheses indicate that this method takes no argument. A
method call is called an invocation ; in this case, we would say that we are invoking upper on the
word. As it turns out, there is a string method named find that is remarkably similar to the function
we wrote:
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
In this example, we invoke find on word and pass the letter we are looking for as a parameter.
Actually, the find method is more general than our function; it can find substrings, not just
characters:
>>> word.find('na')
2
It can take as a second argument the index where it should start:
>>> word.find('n', 3)
4
And as a third argument the index where it should stop:
>>> name ='bob'
>>> name.find('b', 1, 2)
-1
This search fails because b does not appear in the index range from 1 to 2 (not including 2).
8. Explain 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
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")
Eg: Using string methods instead of string module functions
text = "Monty Python's Flying Circus"
print "upper", "=>", text.upper()
print "lower", "=>", text.lower()
print "split", "=>", text.split()
print "join", "=>", "+".join(text.split())
print "replace", "=>", text.replace("Python", "Perl")
print "find", "=>", text.find("Python"), text.find("Perl")
print "count", "=>", text.count("n")
9. Explain list as arrays.
10. Write a Python program to find GCD of two numbers.
d1=int(input("Enter a number:"))
d2=int(input("Enter another number"))
rem=d1%d2
while rem!=0 :
print(rem)
d1=d2
d2=rem
rem=d1%d2
print("gcd of given numbers is : %d" %(d2))
11. Write a Python program to find the exponentiation of a number.
print("Calculation of X^Y")
x=int(input("Enter X Value :"))
y=int(input("Enter Y Value :"))
powered = x
if y == 0:
powered=1
else:
while y > 1:
powered *= x
y -= 1
print(powered)
12. Write a Python program to sum an array of
numbers.def sum_arr (arr,size):
if (size = = 0):
return 0
else:
return arr[size-1]+ sum_arr (arr, size-1)
n = int(input(“Enter the number of elements for the list:”))
a = [ ]
for I in range (0,n):
element = int (input(“Enter element:”))
a.apppend (element)
print (“ The list is: ”)
print a
print ( “ The Sum is : ”)
b = sum_arr(a,n)
print(b)
13. Write a Python program to perform linear search.
data = []
n = int(raw_input('Enter Number of Elements in the Array: '))
for i in range(0, n):
x = raw_input('Enter the Element %d :' %(i+1))
data.append(x)
e= int(raw_input('Enter the Element to be Search '))
pos = 0
found= False
while pos < n and not found:
if int(data[pos])==e:
found= True
else:
pos = pos+1
if found:
print('Element %d Found at Position %d ' %(e,pos+1))
else:
print('Element %d is Not Found in the Array '%(e))
14. Write a Python program to perform binary
search.data = []
n = int(input('Enter Number of Elements in the Array: '))
print('Enter the Elements in Ascending Order' )
for i in range(0, n):
x = int(input('Enter the Element %d :' %(i+1)))
data.append(x)
e= int(input('Enter the Element to be Search '))
first = 0
last = n-1
found = False
while( first<=last and not found):
mid = (first + last)/2
if int(data[mid]) == e :
found = True
else:
if e < int(data[mid]):
last = mid - 1
else:
first = mid + 1
if found:
print('Element %d Found at Position %d ' %(e,mid+1))
else:
print('Element %d is Not Found in the Array '%(e))

More Related Content

Similar to GE3151 PSPP UNIT III QUESTION BANK.docx.pdf

Similar to GE3151 PSPP UNIT III QUESTION BANK.docx.pdf (20)

Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
[C++][a] tutorial 2
[C++][a] tutorial 2[C++][a] tutorial 2
[C++][a] tutorial 2
 
Programming for Problem Solving
Programming for Problem SolvingProgramming for Problem Solving
Programming for Problem Solving
 
C operators
C operatorsC operators
C operators
 
What is c
What is cWhat is c
What is c
 
LOOPS AND DECISIONS
LOOPS AND DECISIONSLOOPS AND DECISIONS
LOOPS AND DECISIONS
 
Vb script final pari
Vb script final pariVb script final pari
Vb script final pari
 
Operator & Expression in c++
Operator & Expression in c++Operator & Expression in c++
Operator & Expression in c++
 
Types of Operators in C
Types of Operators in CTypes of Operators in C
Types of Operators in C
 
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdfBasic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
Basic_C++ Notes with problema from Preethi arora and suneetha arora.pdf
 
C statements.ppt presentation in c language
C statements.ppt presentation in c languageC statements.ppt presentation in c language
C statements.ppt presentation in c language
 
Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
 
C PRESENTATION.pptx
C PRESENTATION.pptxC PRESENTATION.pptx
C PRESENTATION.pptx
 
Java script session 4
Java script session 4Java script session 4
Java script session 4
 
C# operators
C# operatorsC# operators
C# operators
 
Operators in c programming
Operators in c programmingOperators in c programming
Operators in c programming
 
Cprogrammingoperator
CprogrammingoperatorCprogrammingoperator
Cprogrammingoperator
 
Ch05.pdf
Ch05.pdfCh05.pdf
Ch05.pdf
 

More from Asst.prof M.Gokilavani

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
IT8073_Information Security_UNIT I _.pdf
IT8073_Information Security_UNIT I _.pdfIT8073_Information Security_UNIT I _.pdf
IT8073_Information Security_UNIT I _.pdfAsst.prof M.Gokilavani
 
IT8073 _Information Security _UNIT I Full notes
IT8073 _Information Security _UNIT I Full notesIT8073 _Information Security _UNIT I Full notes
IT8073 _Information Security _UNIT I Full notesAsst.prof M.Gokilavani
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfAsst.prof M.Gokilavani
 
GE3151 PSPP All unit question bank.pdf
GE3151 PSPP All unit question bank.pdfGE3151 PSPP All unit question bank.pdf
GE3151 PSPP All unit question bank.pdfAsst.prof M.Gokilavani
 
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdfAI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdfAsst.prof M.Gokilavani
 
AI3391 Artificial intelligence Session 29 Forward and backward chaining.pdf
AI3391 Artificial intelligence Session 29 Forward and backward chaining.pdfAI3391 Artificial intelligence Session 29 Forward and backward chaining.pdf
AI3391 Artificial intelligence Session 29 Forward and backward chaining.pdfAsst.prof M.Gokilavani
 
AI3391 Artificial intelligence Session 28 Resolution.pptx
AI3391 Artificial intelligence Session 28 Resolution.pptxAI3391 Artificial intelligence Session 28 Resolution.pptx
AI3391 Artificial intelligence Session 28 Resolution.pptxAsst.prof M.Gokilavani
 
AI3391 Artificial intelligence session 27 inference and unification.pptx
AI3391 Artificial intelligence session 27 inference and unification.pptxAI3391 Artificial intelligence session 27 inference and unification.pptx
AI3391 Artificial intelligence session 27 inference and unification.pptxAsst.prof M.Gokilavani
 
AI3391 Artificial Intelligence Session 26 First order logic.pptx
AI3391 Artificial Intelligence Session 26 First order logic.pptxAI3391 Artificial Intelligence Session 26 First order logic.pptx
AI3391 Artificial Intelligence Session 26 First order logic.pptxAsst.prof M.Gokilavani
 
AI3391 Artificial Intelligence Session 25 Horn clause.pptx
AI3391 Artificial Intelligence Session 25 Horn clause.pptxAI3391 Artificial Intelligence Session 25 Horn clause.pptx
AI3391 Artificial Intelligence Session 25 Horn clause.pptxAsst.prof M.Gokilavani
 
AI3391 Artificial Intelligence session 24 knowledge representation.pptx
AI3391 Artificial Intelligence session 24 knowledge representation.pptxAI3391 Artificial Intelligence session 24 knowledge representation.pptx
AI3391 Artificial Intelligence session 24 knowledge representation.pptxAsst.prof M.Gokilavani
 

More from Asst.prof M.Gokilavani (20)

CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
IT8073_Information Security_UNIT I _.pdf
IT8073_Information Security_UNIT I _.pdfIT8073_Information Security_UNIT I _.pdf
IT8073_Information Security_UNIT I _.pdf
 
IT8073 _Information Security _UNIT I Full notes
IT8073 _Information Security _UNIT I Full notesIT8073 _Information Security _UNIT I Full notes
IT8073 _Information Security _UNIT I Full notes
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
GE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdfGE3151 UNIT II Study material .pdf
GE3151 UNIT II Study material .pdf
 
GE3151 PSPP All unit question bank.pdf
GE3151 PSPP All unit question bank.pdfGE3151 PSPP All unit question bank.pdf
GE3151 PSPP All unit question bank.pdf
 
GE3151_PSPP_All unit _Notes
GE3151_PSPP_All unit _NotesGE3151_PSPP_All unit _Notes
GE3151_PSPP_All unit _Notes
 
GE3151_PSPP_UNIT_5_Notes
GE3151_PSPP_UNIT_5_NotesGE3151_PSPP_UNIT_5_Notes
GE3151_PSPP_UNIT_5_Notes
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
GE3151_PSPP_UNIT_3_Notes
GE3151_PSPP_UNIT_3_NotesGE3151_PSPP_UNIT_3_Notes
GE3151_PSPP_UNIT_3_Notes
 
GE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_NotesGE3151_PSPP_UNIT_2_Notes
GE3151_PSPP_UNIT_2_Notes
 
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdfAI3391 Artificial intelligence Unit IV Notes _ merged.pdf
AI3391 Artificial intelligence Unit IV Notes _ merged.pdf
 
AI3391 Artificial intelligence Session 29 Forward and backward chaining.pdf
AI3391 Artificial intelligence Session 29 Forward and backward chaining.pdfAI3391 Artificial intelligence Session 29 Forward and backward chaining.pdf
AI3391 Artificial intelligence Session 29 Forward and backward chaining.pdf
 
AI3391 Artificial intelligence Session 28 Resolution.pptx
AI3391 Artificial intelligence Session 28 Resolution.pptxAI3391 Artificial intelligence Session 28 Resolution.pptx
AI3391 Artificial intelligence Session 28 Resolution.pptx
 
AI3391 Artificial intelligence session 27 inference and unification.pptx
AI3391 Artificial intelligence session 27 inference and unification.pptxAI3391 Artificial intelligence session 27 inference and unification.pptx
AI3391 Artificial intelligence session 27 inference and unification.pptx
 
AI3391 Artificial Intelligence Session 26 First order logic.pptx
AI3391 Artificial Intelligence Session 26 First order logic.pptxAI3391 Artificial Intelligence Session 26 First order logic.pptx
AI3391 Artificial Intelligence Session 26 First order logic.pptx
 
AI3391 Artificial Intelligence Session 25 Horn clause.pptx
AI3391 Artificial Intelligence Session 25 Horn clause.pptxAI3391 Artificial Intelligence Session 25 Horn clause.pptx
AI3391 Artificial Intelligence Session 25 Horn clause.pptx
 
AI3391 Artificial Intelligence session 24 knowledge representation.pptx
AI3391 Artificial Intelligence session 24 knowledge representation.pptxAI3391 Artificial Intelligence session 24 knowledge representation.pptx
AI3391 Artificial Intelligence session 24 knowledge representation.pptx
 

Recently uploaded

(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...ranjana rawat
 
Sustainable Clothing Strategies and Challenges
Sustainable Clothing Strategies and ChallengesSustainable Clothing Strategies and Challenges
Sustainable Clothing Strategies and ChallengesDr. Salem Baidas
 
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full NightCall Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Nightssuser7cb4ff
 
(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service
(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service
(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
VIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service Gorakhpur
VIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service GorakhpurVIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service Gorakhpur
VIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service GorakhpurSuhani Kapoor
 
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...Cluster TWEED
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...Delhi Escorts
 
See How do animals kill their prey for food
See How do animals kill their prey for foodSee How do animals kill their prey for food
See How do animals kill their prey for fooddrsk203
 
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service NashikRussian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashikranjana rawat
 
Soil pollution causes effects remedial measures
Soil pollution causes effects remedial measuresSoil pollution causes effects remedial measures
Soil pollution causes effects remedial measuresvasubhanot1234
 
Mumbai Call Girls, 💞 Prity 9892124323, Navi Mumbai Call girls
Mumbai Call Girls, 💞  Prity 9892124323, Navi Mumbai Call girlsMumbai Call Girls, 💞  Prity 9892124323, Navi Mumbai Call girls
Mumbai Call Girls, 💞 Prity 9892124323, Navi Mumbai Call girlsPooja Nehwal
 
(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service
(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service
(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Freegle User Survey as visual display - BH
Freegle User Survey as visual display - BHFreegle User Survey as visual display - BH
Freegle User Survey as visual display - BHbill846304
 

Recently uploaded (20)

(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
(NANDITA) Hadapsar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune ...
 
Sustainable Clothing Strategies and Challenges
Sustainable Clothing Strategies and ChallengesSustainable Clothing Strategies and Challenges
Sustainable Clothing Strategies and Challenges
 
E Waste Management
E Waste ManagementE Waste Management
E Waste Management
 
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full NightCall Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
Call Girls Ahmedabad 7397865700 Ridhima Hire Me Full Night
 
(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service
(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service
(ANAYA) Call Girls Hadapsar ( 7001035870 ) HI-Fi Pune Escorts Service
 
VIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service Gorakhpur
VIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service GorakhpurVIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service Gorakhpur
VIP Call Girl Gorakhpur Aashi 8250192130 Independent Escort Service Gorakhpur
 
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
webinaire-green-mirror-episode-2-Smart contracts and virtual purchase agreeme...
 
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Nehru Place, 🔝 9953056974 🔝 escort Service
 
Call Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi Ncr
Call Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi NcrCall Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi Ncr
Call Girls In R.K. Puram 9953056974 Escorts ServiCe In Delhi Ncr
 
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Rajiv Chowk Delhi reach out to us at 🔝9953056974🔝
 
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...9873940964 High Profile  Call Girls  Delhi |Defence Colony ( MAYA CHOPRA ) DE...
9873940964 High Profile Call Girls Delhi |Defence Colony ( MAYA CHOPRA ) DE...
 
Sustainable Packaging
Sustainable PackagingSustainable Packaging
Sustainable Packaging
 
See How do animals kill their prey for food
See How do animals kill their prey for foodSee How do animals kill their prey for food
See How do animals kill their prey for food
 
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service NashikRussian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
Russian Call Girls Nashik Anjali 7001305949 Independent Escort Service Nashik
 
Green Banking
Green Banking Green Banking
Green Banking
 
Soil pollution causes effects remedial measures
Soil pollution causes effects remedial measuresSoil pollution causes effects remedial measures
Soil pollution causes effects remedial measures
 
Mumbai Call Girls, 💞 Prity 9892124323, Navi Mumbai Call girls
Mumbai Call Girls, 💞  Prity 9892124323, Navi Mumbai Call girlsMumbai Call Girls, 💞  Prity 9892124323, Navi Mumbai Call girls
Mumbai Call Girls, 💞 Prity 9892124323, Navi Mumbai Call girls
 
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
Sexy Call Girls Patel Nagar New Delhi +918448380779 Call Girls Service in Del...
 
(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service
(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service
(ZARA) Call Girls Talegaon Dabhade ( 7001035870 ) HI-Fi Pune Escorts Service
 
Freegle User Survey as visual display - BH
Freegle User Survey as visual display - BHFreegle User Survey as visual display - BH
Freegle User Survey as visual display - BH
 

GE3151 PSPP UNIT III QUESTION BANK.docx.pdf

  • 1. GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT III CONTROL FLOW, FUNCTIONS PART- A (2 Marks) 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. 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. 4. 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 x <= y # x is less than or equal to y 5. 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. 6. What is conditional execution? The ability to check the condition and change the behavior of the program accordingly is called conditional execution. Example:
  • 2. 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. 7. 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' 8. 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. 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 9. Explain ‘for loop’ with example. The general form of a for statement is
  • 3. 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.
  • 4. 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.
  • 5. 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. PART B (16 MARKS) 1. Explain types of operators.
  • 6. i)Arithmetic Operators Assume variable a holds 10 and variable b holds 20, then- Operator Description Example + Addition Adds values on either side of the operator a + b = 30 -Subtraction Subtracts right hand operand from left hand operand a – b = -10 * Multiplication Multiplies values on either side of the operator a * b = 200 / Division Divides left hand operand by right hand operand b / a = 2 % Modulus Divides left hand operand by right hand operand and returns remainder b % a = 0 ** Exponent Performs exponential power calculation on operators a**b =10 // Floor Division The division of operands where the result is thequotient in which the digits after the decimal point are removed 9//2 = 4 and 9.0//2.0 = 4.0 ii) Python Comparison Operators These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then − Operator Description Example
  • 7. == If the values of two operands are equal, then the condition becomes true. a == b is not true != If values of two operands are not equal, then condition becomes true. a!=b is true <> If values of two operands are not equal, then condition becomes true a <> b is true > If the value of left operand is greater than the value of right operand, then condition becomes true a > b is not true < If the value of left operand is less than the value of right operand, then condition becomes true a < b is true >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true a >= b is not true <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true a <= b is true (iii) 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. (iv) Assignment operators
  • 8. Operator Description Example = Assigns values from rightside operands to left side operand. c = a + b assigns value of a + b into c += Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a -= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c - a *= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a /= Divide AND It divides left operand withthe right operand and assign the result to left operand c /= a is equivalent to c = c / ac /= a is equivalent to c = c / a %= Modulus AND It takes modulus using two operands and assign theresult to left operand c %= a is equivalent to c = c % a **= Exponent AND Performs exponential power calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a //= Floor Division It performs floor division on operators and assign value to the left operand c //= a is equivalent to c = c // a 2. Explain conditional alternative and chained conditional. The simplest form of if statement is: Syntax: if statement:
  • 9. Eg: if x > 0: print 'x is positive' The boolean expression after ‘if’ is called the condition. If it is true, then the indentedstatement gets executed. If not, nothing happens. if statements have the same structure as function definitions: a header followed by an indented body. Statements like this are called compound statements. There is no limit on the number of statements that can appear in the body, but there has to be at least one. Occasionally, it is useful to have a body with no statements .In that case, you can use the pass statement, which does nothing. if x < 0: pass # need to handle negative values! Alternative execution (if-else): A second form of if statement is alternative execution, in which there are two possibilities and the condition determines which one gets executed. The syntax looks like this: Eg: if x%2 == 0: print 'x is even' else: print 'x is odd' If the remainder when x is divided by 2 is 0, then we know that x is even, and the program displays a message to that effect. If the condition is false, the second set of statements is executed. Since the condition must be true or false, exactly one of the alternatives will be executed. The alternatives are called branches, because they are branches in the flow of execution. Chained conditionals(if-elif-else): 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. Eg: if choice == 'a': draw_a()
  • 10. elif choice =='b': draw_b() elif choice =='c': draw_c() Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true branch executes. 3. Explain in detail about Fruitful Functions. Return values Some of the built-in functions we have used, such as the math functions, produce results. Calling the function generates a value, which we usually assign to a variable or use as part ofan expression. The first example is area, which returns the area of a circle with the given radius: Eg: def area(radius): temp = math.pi * radius**2 return temp We have seen the return statement before, but in a fruitful function the return statement includes an expression. This statement means: “Return immediately from this function and use the following expression as a return value.” The expression can be arbitrarily complicated, so we could have written this function more concisely: def area(radius): return math.pi * radius**2 On the other hand, temporary variables like temp often make debugging easier. Sometimes it is useful to have multiple return statements, one in each branch of a conditional: def absolute_value(x): if x < 0: return -x else: return x 4. Write a Python program to find the square root of a number.n=int(input("Enter a number to find Square Root:"))
  • 11. approx = 0.5 * n better = 0.5 * (approx + n/approx) while better != approx: approx = better better = 0.5 * (approx + n/approx) print(approx) 5. Explain RECURSION. The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily. Examples of such problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of Graph, etc. Python program: # take input from the user num = int(input("Enter a number: ")) def fact(n): if n == 1: return n else: return n*fact(n-1) print(“Factorial of n numbers is :%d” %(fact(n))) 6. Explain string slices and string immutability. String slices A segment of a string is called a slice . Selecting a slice is similar to selecting a character: >>> s ='Monty Python' >>> print s[0:5] Monty >>> print s[6:12] The operator [n:m]returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. If you omit the first index (before the colon), the slice starts at the beginning of the string. If you omit the second index, the slice goes to the end of the string: >>> fruit = 'banana'
  • 12. >>> fruit[:3] 'ban' >>> fruit[3:] 'ana' If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks: >>> fruit ='banana' >>> fruit[3:3] An empty string contains no characters and has length 0, but other than that, it is the same as any other string. String immutability. Python strings are immutable. ‘a’ is not a string. It is a variable with string value. You can’t mutate the string but can change what value of the variable to a new string. Eg: 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 the value. 7. Explain string functions and methods. There are a number of useful operations that can be performed with string. One of the most useful of these is the function split. This function takes a string (typically a line of input from the user) and splits it into individual words. Another useful function is lower, which converts text into lower case.
  • 13. Eg: >>> line = input(“What is your name?”) What is your name? Timothy Alan Budd >>> lowname = line.lower() >>> print lowname.split() [‘timothy’, ‘alan’, ‘budd’] Other useful functions will search a string for a given text value, or strip leading or trailing white space from a string. An alternative version of split takes as argument the separator string.The string is broken into a list using the separator as a division. This can be useful, for example, for breaking a file path name into parts: Eg: >>> pathname = ‘/usr/local/bin/ls’ >>> pathname.split(‘/’) [‘usr’, ‘local’, ‘bin’, ‘ls’] The inverse of split is the function join. The argument to join is a list of strings. The value to the left of the dot is the separator that will be placed between each element. Often this is simply an empty string. The values in the list are laminated along with the separator to produce the result string. >>> lst = [‘abc’,’pdq’,’xyz’] >>> pri nt ‘::’.join(lst) abc::pdq::xyz 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
  • 14. This form of dot notation specifies the name of the method, upper, and the name of the string to apply the method to, word. The empty parentheses indicate that this method takes no argument. A method call is called an invocation ; in this case, we would say that we are invoking upper on the word. As it turns out, there is a string method named find that is remarkably similar to the function we wrote: >>> word = 'banana' >>> index = word.find('a') >>> print index 1 In this example, we invoke find on word and pass the letter we are looking for as a parameter. Actually, the find method is more general than our function; it can find substrings, not just characters: >>> word.find('na') 2 It can take as a second argument the index where it should start: >>> word.find('n', 3) 4 And as a third argument the index where it should stop: >>> name ='bob' >>> name.find('b', 1, 2) -1 This search fails because b does not appear in the index range from 1 to 2 (not including 2). 8. Explain 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 text = "Monty Python's Flying Circus" print "upper", "=>", string.upper(text) print "lower", "=>", string.lower(text)
  • 15. 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") Eg: Using string methods instead of string module functions text = "Monty Python's Flying Circus" print "upper", "=>", text.upper() print "lower", "=>", text.lower() print "split", "=>", text.split() print "join", "=>", "+".join(text.split()) print "replace", "=>", text.replace("Python", "Perl") print "find", "=>", text.find("Python"), text.find("Perl") print "count", "=>", text.count("n") 9. Explain list as arrays. 10. Write a Python program to find GCD of two numbers. d1=int(input("Enter a number:")) d2=int(input("Enter another number")) rem=d1%d2 while rem!=0 : print(rem) d1=d2 d2=rem rem=d1%d2 print("gcd of given numbers is : %d" %(d2)) 11. Write a Python program to find the exponentiation of a number. print("Calculation of X^Y") x=int(input("Enter X Value :")) y=int(input("Enter Y Value :")) powered = x if y == 0: powered=1 else: while y > 1: powered *= x y -= 1
  • 16. print(powered) 12. Write a Python program to sum an array of numbers.def sum_arr (arr,size): if (size = = 0): return 0 else: return arr[size-1]+ sum_arr (arr, size-1) n = int(input(“Enter the number of elements for the list:”)) a = [ ] for I in range (0,n): element = int (input(“Enter element:”)) a.apppend (element) print (“ The list is: ”) print a print ( “ The Sum is : ”) b = sum_arr(a,n) print(b) 13. Write a Python program to perform linear search. data = [] n = int(raw_input('Enter Number of Elements in the Array: ')) for i in range(0, n): x = raw_input('Enter the Element %d :' %(i+1)) data.append(x) e= int(raw_input('Enter the Element to be Search ')) pos = 0 found= False while pos < n and not found: if int(data[pos])==e: found= True else: pos = pos+1 if found: print('Element %d Found at Position %d ' %(e,pos+1)) else: print('Element %d is Not Found in the Array '%(e)) 14. Write a Python program to perform binary search.data = [] n = int(input('Enter Number of Elements in the Array: ')) print('Enter the Elements in Ascending Order' ) for i in range(0, n): x = int(input('Enter the Element %d :' %(i+1))) data.append(x)
  • 17. e= int(input('Enter the Element to be Search ')) first = 0 last = n-1 found = False while( first<=last and not found): mid = (first + last)/2 if int(data[mid]) == e : found = True else: if e < int(data[mid]): last = mid - 1 else: first = mid + 1 if found: print('Element %d Found at Position %d ' %(e,mid+1)) else: print('Element %d is Not Found in the Array '%(e))