New - Unit 3
New - Unit 3
3.1 CONDITIONALS
3.1.1 Boolean values and operator
The Boolean values are True and False. The relational operators such as = = , !=, > , < ,
>= , <= and the logical operators such as and, or, not are the Boolean operators. The statement
that prints either true or false is a Boolean expression. The following examples use the operator !=,
which compares two operands and produces ‘True’ if they are not equal and ‘False’ otherwise:
>>> 5 != 5
True
>>> 5 != 6
False
So, ‘True’ and ‘False’ are special values which belong to the Boolean type; they are not
strings (case sensitive):
The result is :
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
For example,
x== “Sunday”
y= “sunday”
print (“x==y:”, x==y)
x==y : False
Control Flow, Functions 3.3
For example,
1. and opertator: Returns true only when both expression is true
(x > 0) and (x < 10)
▪▪ True only if x is greater than 0 and less than 10.
▪▪ Otherwise False
2. or operator: Returns true if any one expression is true
(n%2 == 0) or (n%3 == 0)
▪▪ True if either of the conditions is true, that is, if the number is divisible by 2.
▪▪ otherwise False
3. not operator: not operator negates a Boolean expression
▪▪ not (x > y)
▪▪ True if x > y is False
▪▪ False if x>y is True
Normally the operands of the logical operators must be Boolean expressions. However,
Python is very flexible. Any nonzero number is interpreted as “True.”
Example:
>>> 11 and True
True
Flowchart
Condition
Body of ‘if
statement’
Example:
if x > 0 : print ‘x is positive’
In the above example, if x>0 becomes true, then the indented print statement gets executed
to print ‘x is positive’. Otherwise, control skips after the print statement.
var = 24
if (var % 2 ==0):
print “Even number”
print “The even number is “, var
Occasionally, a body with no statements is used. In that case, you can use the pass statement,
which does nothing. For example,
if x < 0:
pass # need to handle negative values!
The statement which comes after condition checking and : symbol requires indentation if
the statement is typed in next line.
Program code:
num = 5
if (num%2) != 0:
print(num, “is odd number.”)
print(“This is always printed.”)
num = 4
if (num%2) == 0:
print(num, “is even number.”)
print(“This is also always printed.”)
Result:
5 is odd number.
This is always printed.
4 is even number.
This is also always printed.
if (year%4) == 0:
print(year, “is leap year.”)
print(“This is also always printed.”)
Result:
This is always printed.
2016 is leap year.
This is also always printed.
Flowchart
if (year % 4) == 0:
print (year, “is leap year.”)
else:
print (year, “is not leap year.”)
Result:
2016 is leap year.
If the remainder when year is divided by 4 is 0, then the program prints that the year is leap
year. If the condition is false, then the else part body will be executed.
If the remainder when x is divided by 2 is 0, then x is even, and the program displays a
message x is even. If the condition is false, then x is odd , so 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.
Syntax of if...elif...else
if test expression:
Body of if
elif test expression:
3.8 Problem Solving and Python Programming
Body of elif
else:
Body of else
Flowchart
if choice == ‘a’:
raw_a()
elif choice == ‘b’:
Control Flow, Functions 3.9
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.
Program code:
num = 5.4
if num > 0:
print(“Positive number”)
elif num == 0:
print(“Zero”)
else:
print(“Negative number”)
Result:
Positive number
3.3 ITERATION
3.3.1 State of a variable
It is possible to have more than one assignment for the same variable. The value which is
assigned at the last is given to the variable. The new assignment makes an existing variable assigned
with new value by replacing the old value.
The variable x is first assigned with 5 then it is assigned with 4. The last assignment statement
x=4 replaces the old value of x (x=5).
print x
print y
The result is
3
5
Here the variable x is assigned with the value 5. The variable y is assigned with the value
of x. Finally, the value of x is updated to 3. So, the value 3 is assigned to x. This is called state of
the variable.
The following code can also be an example for updating the variable
x=0
x=x+2
print x
The result is
2
Initially x is assigned with the value zero. The value of x is incremented by the value two.
So it is updated as the value 2 (0+2).
Flowchart:
The following program may illustrate the working of while loop statements.
Program is to add natural numbers
# sum= 1+2+……+n
# Program to add natural numbers upto n
n = int(input(“Enter n: “)) # To take input from the user
sum = 0 # initialize sum
i=1 # initialize counter ( loop) variable
while i <= n: # while loop begins
sum = sum + i
i = i+1 # update loop variable
print (“The sum is”, sum) # print the sum
Result:
Enter n: 10
The sum is 55
In this program the variable n is used to get integer from the user. The sum and loop variables
are initialized with zero and one respectively. The while loop continues till the loop variable value
is lesser than n. In each iteration the sum value is added with loop variable value. The increment
statement is used to update the loop variable.
In the above syntax, the while block is repeatedly tests the condition for the given expression
and executes the first block of statement if it is true otherwise the else clause is executed . It might
be tested for the first time and if the loop breaks it will not execute.
For example,
>>>a=0
>>>b=0
>>>while (a<6):
b=b+a
a=a+1
else:
print(“Sum of first 5 integers:”,b)
Output:
The sum of first 5 integers: 15
The val is the loop variable which takes the value of the item inside the sequence on each
iteration. The loop continues until the last element is reached in the sequence. The body of for loop
is marked using indentation. The Fig. 3.5 illustrates the flow of ‘for loop’.
Result:
The total is 45
# i is loop variable
for i in range(len(programming_languages)):
print(“ The programming-language is”, programming_languages[i]).
The result is :
The programming-language is C
The programming-language is C++
The programming-language is Python
3.18 Problem Solving and Python Programming
Here, range function takes the values from zero to two. The len() function is used to find
length of the sequence. The following program also used to illustrate the working of for loop
statements using range function. The program is to add natural numbers.
# sum= 1+2+……+n-1
# Program to add natural numbers upto n-1
n = int(input(“Enter n: “)) # To take input from the user
sum = 0 # initialize sum
for i in range(1, n): # while loop begins
sum = sum + i
print (“The sum is”, sum) # print the sum
Result:
Enter n: 10
The sum is 45
Here, the range of sequence is from 1 to n-1. The loop variable i started with 1.In each
iteration, the value of loop variable is added with sum. The loop continues for n-1 values. The value
of the variable n is obtained from the user.
Surprisingly, in python for loop is used with else part. This is optional. The else part of for
loop is executed if the items in the sequence used in for loop exhausts. The for loop’s else part get
executed if no break statement occurs in for loop. The break statement (see later) can be used to stop
a for loop. In such case, the else part is ignored. Here is an example to illustrate this concept
iteration until the loop exhausts. When there is no element in the list to access, it will print statement
in else part that is No items left.
Python program to display all the prime numbers within the specified range
# change the values of lower and upper for a different result
lower = int(input(“Enter lower range: “))
upper = int(input(“Enter upper range: “))
print(“Prime numbers between”, lower, “and”, upper,”are:”)
for num in range(lower,upper + 1):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
The result is :
Enter lower range: 100
Enter upper range: 150
(‘Prime numbers between’, 100, ‘and’, 150, ‘are:’)
101
103
107
109
113
127
131
137
139
149
In this program, the lower and upper values are obtained from user. Here, the outer for loop
ranges from lower to upper + 1 value. Since the prime numbers are started with greater than 1, the
if loop checks for num>1. It executes the inner for loop for the range 2 to num-1 for every iteration
of the outer for loop. If the variable num is divided by any number from 2 to num-1 completely,
it breaks the inner for loop and access the next element. If the variable num is not divided by any
number from 2 to num-1, then it prints the number (executes the for-else part).
3.20 Problem Solving and Python Programming
For example,
series = [0,1,2,3,4]
for i in series
print(i)
else:
print(“No items”)
Control Flow, Functions 3.21
Output:
1
2
3
4
No items
For example,
Weeks=[“Sunday”, “Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”]
for m in months:
print (m)
Output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Nested Loops:
Nested loops are allowed in Python. The structure of the nested loop is shown in as below:
Example:
num1=[1,5]
num2=[2,3,4]
3.22 Problem Solving and Python Programming
for n1 in num1:
print(n1)
for n2 in num2:
print(n2)
Output:
1
2
3
4
5
2
3
4
Break statement
The break statement is used to change or alter the flow of execution. The looping statements
iterates till the test expression is true. In some cases, the current iteration of the loop need to be
terminated. The break statement is used in this case. The break statement terminates the loop
containing it. Therefore, control of the program transfers to the statement immediately after the
body of the loop. If break statement is used inside a nested loop (loop inside another loop), break
will terminate the innermost loop.
Syntax of break
break
Control Flow, Functions 3.23
if count >= 5:
break
The result is :
1
2
3
4
This program prints the numbers from 1 to 4. When the count value is greater than or equal
to 5 it breaks the loop and stops the execution.
Continue statement
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Syntax of Continue:
continue
The working of continue statement in while loop is shown below.
While test expression:
#codes inside the loop
if condition: # it is true; executes continue
continue
# codes inside the loop
#codes outside the loop
In this program the loop variable val prints the character one by one. When the value of
variable val becomes i, it executes continue statement. It skips the rest of the loop body ( not prints
values of i) and continue from the next element in the string.
The result is :
1
3
5
7
9
This program prints the odd numbers from 1 to 10. The if condition checks value of x
belongs to even or odd. If it is odd, the if condition fails. So it will print the x value. If it is even the
continue statement is executed to start from the next element.
Pass Statement
Pass statement executes nothing. It results in No operation. In Python programming, pass
is a null statement. The simple difference between a comment and pass statement in Python is
that, the interpreter ignores a comment entirely, but not the pass statement.
Syntax of pass
pass
The pass statement can be used in places where the program code cannot be left as blank.
But that can be written in future. The pass is used as placeholders. Pass is used in to construct
program codes that do nothing.
Example:
# This is a global variable
a=0
if a == 0:
# This is still a global variable
b=1
def my_function(c):
Control Flow, Functions 3.27
Sample input/output:
9
In this program, the function add() is nested inside test(). So it could not be called directly.
Calling the function add(4) will result in a error. First, the outer function test(4) is called, which
returns the object of inner function add(). The return function object can then be used to refer the
inner function. The use of nonlocal keyword is explained in next section.
# global scope
a = 10 # a and func assigned in module: global
def func(b): # b and c assigned in function: locals
# local scope
c=a+b # a is not assigned, so it’s a global
return c
print(func(1)) # func in module: result=11
print c #NameError: name ‘z’ is not defined
In this program, name a and func() are assigned in module (outside block/function), resulting
in global scope. Whereas name b and c are assigned in function, resulting in local scope. Local
variables of a function can only be used inside its function. Hence c is not accessible outside func().
Python 3 introduced the nonlocal keyword that allows you to assign to variables in an
outer, but non-global, scope. The following programs explicate the difference between using
and using nonlocal keyword.
Sample input/output:
inner: 2
outer: 1
global: 0
Using nonlocal
x=0
def outer():
x=1
Control Flow, Functions 3.29
def inner():
nonlocal x # nonlocal permits the access to x=1 assigned in outer() but not to
global
#variable x=0
x=2
print(“inner:”, x)
inner()
print(“outer:”, x)
outer()
print(“global:”, x)
Sample input/output:
inner: 2
outer: 2
global: 0
Using Global
x=0
def outer():
x=1
def inner():
global x # global permits access to x=0 assigned outside all function but not
to x=l
# assigned in outer()
x=2
print(“inner:”, x)
inner()
print(“outer:”, x)
outer()
print(“global:”, x)
Sample input/output:
inner: 2
outer: 1
global: 2
3.30 Problem Solving and Python Programming
Functions provide a nested namespace, which localizes the names they use, so that names
inside the function won’t clash with those names used in other module or function. When a name
is used in a function, Python creates the name in local scope, unless it is declared as global in that
function using global keyword.
Without Global
def add(value1,value2):
result = value1 + value2
no1=3
no2=2
add(no1,no2)
print result # NameError: name ‘result’ is not defined
This program results in an error as result, the local variable of function add() could not be
accessed outside the function.
Using Global
def add(value1,value2):
global result
result = value1 + value2
no1=3
no2=2
add(no1,no2)
print result #No Error – result is a global variable; it generates the output as 5
In this program global keyword specifies result as global variable which means that we can
access that variable outside the function as well.
that represents a function call. It contains local variables and parameters of the function. The stack
diagram for preceding program without global is shown in Figure. 3.1.
def add(a,b):
c=a+b
print c
sub(a,b)
def sub(x,y):
z=x-y
print z
n1=10
n2=5
add(n1,n2)
Sample output:
15
5
The stack diagram for this example is shown in Figure.3.2. The order of frames in the
stack (top to bottom) represents the order of function call. The flow of execution starts from main
module. <module> frame indicates the variables n1,n2 which are assigned outside any function.
The function add(n1,n2) was called from main module, which in turn calls sub(a,b). add frame
includes its parameters a, b and local variable c. sub frame includes its parameters x, y and local
variable z. Each parameter refers to the same value of its arguments. Hence a, b refers to the value
of its arguments n1, n2 and x, y refers to the value of its arguments a, b.
For example, if you try to access c in sub(), you will get an following NameError.
3.32 Problem Solving and Python Programming
In a script, calling a fruitful function without assigning the return value will result in loss.
import math
math.sin(90) # no output - as the return value is not assigned
Sample Output:
Welcome!!!
None
The value is None which is not similar to string “None”. None is a special value with its
own type.
print type(None)
Control Flow, Functions 3.33
Sample Output:
<type ‘NoneType’>
It imports the module X, and creates a reference to that module in the current namespace.
Here X.name refers to the things defined in module X.
import datetime
tday=datetime.date.today()
print tday
Sample Output:
2017-04-15
Sample Output:
2017-04-15
Method 3: __import__(‘’)
Syntax:
X = __import__(‘X’)
3.34 Problem Solving and Python Programming
Sample Output:
3.14159265359
Sample input/output:
Your age? 42
(42, <type ‘int’>)
Example: Find the distance between two points, given by the coordinates (x1, y1) and
(x2, y2). By the Pythagorean theorem, the distance is:
distance= ( x2 − x1 ) 2 + ( y2 − y1 ) 2
Step 1: Identify the input parameters and return value of the function. In this example, the
inputs are two points which represents four numbers (x1,y1) and (x2,y2). The return
value is the distance, a floating point number.
The outline of the function:
def distance(x1,y1,x2,y2):
return 0.0
Test the function by calling it with some arguments. This basic version does not compute
distance and will always return 0.0.
>>>distance(1,3,5,8)
0.0
Step 2: At this point we have confirmed that the function is syntactically correct, and we can
start adding code to the body. In this step, add code to compute the differences x2-x1
and y2-y1.
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print ‘dx is’, dx
print ‘dy is’, dy
return 0.0
If this code works correctly it should display ‘dx is 4’ and ‘dy is 5’. If so, we could
confirm that the function parameters and function computation are working correctly. If
not, there are only few lines to check.
3.36 Problem Solving and Python Programming
3.4.8.2 Use temporary variables to hold intermediate values so you can display and check them.
3.4.8.3 Once the program is working, you might want to remove some of the scaffolding or
consolidate multiple statements into compound expressions, but only if it does not make the
program difficult to read.
Example: Compute area of circle with the given inputs center point (xc,yc) and perimeter point
(xp,yp).
Note: First find the radius of circle by computing distance between (xc,yc) and (xp,yp). Later
find the area of circle using radius.
import math
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
def area(radius):
return (math.pi*radius*radius)
xc=input(“Enter xc”)
yc=input(“Enter yc”)
xp=input(“Enter xp”)
yp=input(“Enter yp”)
print area(distance(xc,yc,xp,yp))
Sample input/output:
Enter xc10
Enter yc10
Enter xp15
Enter yp10
78.5398163397
Sample input/output:
Enter a no.3
Odd
3.4.11 RECURSION
Recursion is a way of programming in which a function calls itself again and again until a
condition is true. A recursive function calls itself and has a termination condition.
Advantages of recursion
3.4.11.1 Recursive functions make the code look clean and elegant.
3.4.11.2 A complex task can be broken down into simpler sub-problems using recursion.
3.4.11.3 Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of recursion
(1) Sometimes the logic behind recursion is hard to follow through.
(2) Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
(3) Recursive functions are hard to debug.
def factorial( n ):
if n ==0: # base case
return 1
else:
return n * factorial( n - 1 )
n=input(‘Enter a number:”)
print factorial(no)
Sample Input/Output:
Enter a number:5
120
1
factorial n→0
F(5)
F(4) F(3)
F(1) F(0)
3.40 Problem Solving and Python Programming
Sample input/output:
Please Enter the Range Number: 5
0
1
1
2
3
def show():
show()
show()
The program with infinite recursion runs repeatedly and terminates when the
maximum recursion depth is reached. Python reports the following error message on infinite
recursion.
File “main.py”, line 2, in show
show()
File “main.py”, line 2, in show
show()
Control Flow, Functions 3.41
3.5 STRINGS
A string is a sequence of zero or more characters. An empty string contains no characters
and has a length 0.The indices of a string’s characters are numbered from 0 from the left end and
numbered from -1 from the right end. For a string ‘WELCOME’, its index values are shown in the
following table:
Character W E L C O M E
Index from left end 0 1 2 3 4 5 6
Index from right end -7 -6 -5 -4 -3 -2 -1
Syntax:
< stringname>[<index>]
Index within [ ] indicates the position of the particular character in the string and it must be
an integer expression.
Sample Code
s= “HELLO”
print s[0] # prints H
print s[3] # prints L
The subscript operator can be used within loops as shown in the following code:
s= “HELLO PYTHON!”
for index in xrange(len(s)):
print s[index], “ is at index “, index
Output
H is at index 0
E is at index 1
L is at index 2
L is at index 3
O is at index 4
is at index 5
3.42 Problem Solving and Python Programming
P is at index 6
Y is at index 7
T is at index 8
H is at index 9
O is at index 10
N is at index 11
! is at index 12
Sample Code
s= “HELLO PYTHON!”
print “Length is “, len(s)
Sample Output
Length is 13
3.5.3 in operator
in is a boolean operator that takes two strings as its operands and returns True if the first
string appears as a substring in the second string.
Sample Code
s=”Hello, Python!”
print s[0]
print s[1:4]
print s[:5]
print s[7:]
print s[3:3]
Control Flow, Functions 3.43
print s[5:2]
print s[:]
print s[-3:]
print s[:-3]
Sample Output
H
ell
Hello
Python!
Hello, Python!
on!
Hello, Pyth
3.5.5 Immutability
The string is an immutable data structure. This means that its characters can be accessed
but the string cannot be modified.
dir( ) Function
It returns a sorted list of strings that includes the names of all modules, functions and
variables that are defined in a module.
Sample Output:
[‘Formatter’, ‘Template’, ‘_TemplateMetaclass’, ‘__builtins__’, ‘__doc__’, ‘__
file__’, ‘__name__’, ‘__package__’, ‘_float’, ‘_idmap’, ‘_idmapL’, ‘_int’, ‘_long’,
‘_multimap’, ‘_re’, ‘ascii_letters’, ‘ascii_lowercase’, ‘ascii_uppercase’, ‘atof’,
‘atof_error’, ‘atoi’, ‘atoi_error’, ‘atol’, ‘atol_error’, ‘capitalize’, ‘capwords’,
‘center’, ‘count’, ‘digits’, ‘expandtabs’, ‘find’, ‘hexdigits’, ‘index’, ‘index_error’,
‘join’, ‘joinfields’, ‘letters’, ‘ljust’, ‘lower’, ‘lowercase’, ‘lstrip’, ‘maketrans’,
‘octdigits’, ‘printable’, ‘punctuation’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rsplit’,
‘rstrip’, ‘split’, ‘splitfields’, ‘strip’, ‘swapcase’, ‘translate’, ‘upper’, ‘uppercase’,
‘whitespace’, ‘zfill’]
Here, the special string variable ‘__name__’ holds module’s name, and ‘__file__’ holds the
filename from which the corresponding module is loaded.
Sample Output:
upper PYTHON STRING MODULE
lower python string module
split [‘Python’, ‘String’, ‘Module’]
join Python+String+Module
replace Java String Module
find 0
find -1
count 2
Sample Output:
5217 5217 5217 5217 4711
5217 2703 21015
5217.0 1.0 123000.0
atoi() function uses the second argument (optional) for identifying the number base. If the
base is zero, atoi() examines the first few characters to identify the base. If ‘0x’, the base is 16
(hexadecimal), and if ‘0’, the base is 8 (octal). The default base is 10 (decimal).
3.6 ARRAYS
Python lists can store values of different data types. But, arrays in python can only store
values of same data type. Array is not a fundamental data type in Python. So, the standard ‘array’
module has to be imported as:
from array import *
Control Flow, Functions 3.49
Here, ‘arrayID’ is the name of an array, ‘typecode’ is the type of array and ‘Initializers’ are
the values with which an array is initialized.
Example:
my_array = array(‘i’,[1,2,3,4])
Typecode Description
‘b’ signed integer of size 1 byte
‘B’ unsigned integer of size 1 byte
‘c’ character of size 1 byte
‘u’ unicode character of size 2 bytes
‘h’ signed integer of size 2 bytes
‘H’ unsigned integer of size 2 bytes
‘i’ signed integer of size 2 bytes
‘I’ unsigned integer of size 2 bytes
‘w’ unicode character of size 4 bytes
‘l’ signed integer of size 4 bytes
‘L’ unsigned integer of size 4 bytes
‘f’ floating point of size 4 bytes
‘d’ floating point of size 8 bytes
Sample Code
from array import *
myArray = array(‘i’, [1,2,3,4,5])
for i in myArray:
print i
Sample Output:
1
2
3
4
5
3.50 Problem Solving and Python Programming
In Python, a one-dimensional array can easily be represented as a list. The following code
initializes an array ‘myArray’ and attempts to find the largest of its items, using the concept of lists
in Python.
myArray=[45, 23, 76, 12, 33]
print ‘The given elements are’
for i in range(len(myArray)):
print myArray[i]
m=0
for i in range(len(myArray)):
if m<myArray[i]:
m=myArray[i]
print ‘The largest is’, m
Sample Output:
The given elements are
45
23
76
12
33
The largest is 76
A 2D array can be created using lists within list. The following code creates the 2×2 matrix
as [[1,2],[3,4]] with the list [1,2] representing the first row and the list [3,4] representing the second
row.
Sample Code
myArray=[[1,2],[3,4]]
for i in range(len(myArray)):
for j in range(len(myArray[i])):
print myArray[i][j]
Control Flow, Functions 3.51
Sample Output:
1
2
3
4
In a similar manner, a 3×2 matrix with elements [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’] is created and
displayed along with their indices in the following code:
Sample Code
myArray=[[‘a’,’b’],[‘c’,’d’],[‘e’,’f’]]
for i in range(len(myArray)):
for j in range(len(myArray[i])):
print ‘[‘,i,’ ‘,j,’]’,myArray[i][j]
Sample Output:
[0 0]a
[0 1]b
[1 0]c
[1 1]d
[2 0]e
[2 1]f
Sample input/output:
Enter no. of elements in array 5 Enter no. 1
Enter no. 2
Enter no. 3
Enter no. 4
Enter no. 5
15
3.7.2. Program to compute gcd, square root, and exponentiation of a given number
import math def compute():
print(math.gcd(12,18)) print(math.sqrt(100)) print(math.exp(2))
compute()
Sample input/output:
6
10.0
7.38905609893065
20 30 40 50 60
0 1 2 3 4
Case 1:
Search value = 50
Step 1: Compare 50 with value at index 0
Step 2: Compare 50 with value at index 1
Step 3: Compare 50 with value at index 2
Step 4: Compare 50 with value at index 3 (Success)
Case 2:
Search value = 70
Step 1: Compare 70 with value at index 0
Step 2: Compare 70 with value at index 1
Step 3: Compare 70 with value at index 2
Control Flow, Functions 3.53
Sample input/output:
Enter no. of elements in the list 3
Enter no. 1
Enter no. 2
Enter no. 3
[‘1’, ‘2’, ‘3’]
Enter key to be searched 2
(True, 2)
Sample input/output:
False
True
else:
return n+rec_sum(n-1)
no=input(“Enter a no.”)
print ‘Sum:’,rec_sum(no)
Sample input/output:
Enter a no.5
Sum: 15
3.7.6 Python function that that prints out the first n rows of Pascal’s triangle.
Sample Pascal’s triangle :
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Using Recursion:
def pascal(n):
if n == 1:
return [ [1] ]
else:
result = pascal(n-1)
lastRow = result[-1]
result.append( [ (a+b) for a,b in zip([0]+lastRow, lastRow+[0]) ] )
return result
def pretty(tree):
if len(tree) == 0: return ‘’
line = ‘ ‘ * len(tree)
for cell in tree[0]:
line += ‘ %2i’ % cell
return line + “\n” + pretty(tree[1:])
print pretty(pascal(int(6))
Control Flow, Functions 3.57
Sample input/output:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Using iteration:
def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
return n>=1
pascal_triangle(6)
Sample input/output:
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
3.58 Problem Solving and Python Programming
# Global scope
s = «Example»
f()
z->5
6. What is fruitful function?
Fruitful functions are functions that return value. While using fruitful function, the return value
must be handled properly by assigning it to a variable or use it as part of expression.
Example:
import math
x=math.sin(90)+1
print x # Output is 1.8939966636
8. Define Recursion.
Recursion is a way of programming in which a function calls itself again and again until a
condition is true. A recursive function calls itself and has a termination condition.
Example:
def show():
show()
return
3.60 Problem Solving and Python Programming
10. Define Module. What are the ways to import modules in Python?
Module is a Python file that contains collection of related variables, functions, classes and
other definitions.
Python provides the following three different ways to import modules:
(1) Using import
(2) Importing individual objects
(3) __import__(‘’)
•• If the first index is omitted, the slice starts at the beginning of the string.
•• If the second index is omitted, the slice goes to the end of the string.
•• If the first index is greater than or equals to the second, the slice is an empty string.
•• If both indices are omitted, the slice is a given string itself.
16. How will you check in a string that all characters are alphanumeric?
isalnum() can be used which returns true if string has at least 1 character and all other characters
are alphanumeric.