Home | | Problem Solving and Python Programming | Python Control Flow, Functions: brief important questions and answers

# Python Control Flow, Functions: brief important questions and answers

Problem Solving and Python Programming : Control Flow, Functions

1. Explain types of operators.

i)Arithmetic Operators

Assume variable a holds 10 and variable b holds 20, then-

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 –

(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

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 indented statement 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 of an expression.

The first example is area, which returns the area of a circle with the given radius:

Eg:

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:

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

>>>     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.append (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

if int(data[pos])==e:

found= True

else:

pos = pos+1

if found:

print('Element %d Found at Position %d ' %(e,pos+1))

else:

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

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:

Part B:

1.   Explain conditional statements in detail with example(if, if..else, if..elif..else)

2.   explain in detail about operators in detail

3.   Explain in detail about iterations with example.(for, while)

4.   Explain the usage of else statements in loops

5.   Explain in detail about using for loop in sequence.

6.   Explain in detail about string built in function with suitable examples?

7.   Explain about loop control statement(break, continue, pass)

8.   Breifly discuss about fruitful function.

9.   Discuss with an example about local and global variable

10.        Discuss with an example about function composition

11.        Explain in detail about recursion with example.

12.        Explain in detail about strings and its operations(slicing,immutablity)

13.        Program to find square root of a given number using newtons method

14.        program to find gcd of given nnumber

15.        program to find exponentiation of given number using recursion

16.        program to find sum of array elements.

17.        program to search an element using linear search.

18.        program to search an element using binary element.

19.        program to find factorial of a given number using recursion

Tags : Problem Solving and Python Programming , Problem Solving and Python Programming : Control Flow, Functions
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Problem Solving and Python Programming : Control Flow, Functions : Python Control Flow, Functions: brief important questions and answers | Problem Solving and Python Programming