You are on page 1of 54

Republic of the Philippines

BATANGAS STATE UNIVERSITY


Pablo Borbon Main II
Golden Country Subd., Alangilan, Batangas City

COLLEGE OF INFORMATICS AND COMPUTING SCIENCES


Information Technology Department
CS 121 Advance Computer Programming

INSTRUCTIONAL MATERIAL

Part I
This module introduce Python Programming Languages, its basic elements, branching program, control
structure, iteration, string and input. It aims to assist students to understand the syntax and the structure of
Python.
 This module aims to acquire programming skill of Python, and application of in data structure and
algorithm
An exercises/examination was given at the end of the module to assess if the student understood the
topics discussed.

By the end of this module, students will able to:


1. To acquire programming skills in core Python.
2. To acquire the application of concepts in data structures and algorithm analysis

Introduction to Python
 Python is a high-level scripting language which can be used for a wide variety of text processing,
system administration and internet-related tasks.
 Unlike many similar languages, it’s core language is very small and easy to master, while
allowing the addition of modules to perform a virtually limitless variety of tasks.
 Python is a true object-oriented language, and is available on a wide variety of platforms.
 Open source general-purpose language.
 Great interactive environment.
 Python was developed in the early 1990’s by Guido van Rossum, then at CWI in Amsterdam, and
currently at CNRI in Virginia.
The Basic Elements of Python
There are a few features of python which are different than other programming languages, and which
should be mentioned so that subsequent examples don’t seem confusing. Further information on all of
these features will be provided, when the topics are covered in depth.

LITERALS
 In the following example, the parameter values passed to the print function are all technically
called literals
 More precisely, “Hello” and “Programming is fun!” are called textual literals, while 3
and 2.3 are called numeric literals

>>> print("Hello")
Hello
>>> print("Programming is fun!")
Programming is fun!
>>> print(3)
3
>>> print(2.3)
2.3

SIMPLE ASSIGNMENT STATEMENT

 A literal is used to indicate a specific value, which can be assigned to


a variable

x is a variable and 2 is its value


>>> x = 2
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3

 Python assignment statements are actually slightly different from the “variable as a box” model
 In Python, values may end up anywhere in memory, and variables are used to refer to
them

>>> x = 2
>>> print(x)
2
>>> x = 2.3
>>> print(x)
2.3

 Interestingly, as a Python programmer you do not have to worry about computer memory getting
filled up with old values when new values are assigned to variables
 Python will automatically clear old
values out of memory in a process
known as garbage collection

ASSIGNING INPUT

 So far, we have been using values specified by programmers and printed or assigned to variables
 How can we let users (not programmers) input values?
 In Python, input is accomplished via an assignment statement combined with a built-in
function called input
 When Python encounters a call to input, it prints <prompt> (which is a string literal) then pauses
and waits for the user to type some text and press the <Enter> key

<variable> = input(<prompt>)

 Here is a sample interaction with the Python interpreter:

>>> name = input("Enter your name: ")


Enter your name: Mohammad Hammoud
>>> name
'Mohammad Hammoud'
>>> 

 Notice that whatever the user types is then stored as a string


 What happens if the user inputs a number?

 Here is a sample interaction with the Python interpreter:

>>> number = input("Enter a number: ")


Enter a number: 3
>>> number
'3'
>>> 

 How can we force an input number to be stored as a number and not as a string?
 We can use the built-in eval function, which can be “wrapped around” the
input function

Still a string!

 Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a number: "))


Enter a number: 3
>>> number
3
>>> 

Now an int
(no single quotes)!

 Here is a sample interaction with the Python interpreter:

>>> number = eval(input("Enter a number: "))


Enter a number: 3.7
>>> number
3.7
>>> 

And now a float


(no single quotes)!

 Here is another sample interaction with the Python interpreter:

>>> number = eval(input("Enter an equation: "))


Enter an equation: 3 + 2
>>> number
5
>>>

The eval function will evaluate this formula and


return a value, which is then assigned to the variable “number”
DATATYPE CONVERSION

 Besides, we can convert the string output of the input function into an integer or a float using the
built-in int and float functions

>>> number = int(input("Enter a number: "))


Enter a number: 3
>>> number
3
>>> 

An integer
(no single quotes)!

 Besides, we can convert the string output of the input function into an integer or a float using the
built-in int and float functions

>>> number = float(input("Enter a number: "))


Enter a number: 3.7
>>> number
3.7
>>> 

A float
(no single quotes)!

 As a matter of fact, we can do various kinds of conversions between strings, integers and floats
using the built-in int, float, and str functions

>>> x = 10
>>> float(x)
10.0
>>> str(x)
'10'
>>>

integer  float
integer  string

>>> y = "20"
>>> float(y)
20.0
>>> int(y)
20
>>>
string  float
string  integer

>>> z = 30.0
>>> int(z)
30
>>> str(z)
'30.0'
>>> 

float  integer
float  string

SIMULTANEOUS ASSIGNMENT

 This form of assignment might seem strange at first, but it can prove remarkably useful (e.g., for
swapping values)

>>> x, y = 2, 3
>>> x
2
>>> y
3
>>> 

 Suppose you have two variables x and y, and you want to swap their values (i.e., you want the
value stored in x to be in y and vice versa)

>>> x = 2
>>> y = 3
>>> x = y
>>> y = x
>>> x
3
>>> y
3
CANNOT be done with
two simple assignments

 Suppose you have two variables x and y, and you want to swap their values (i.e., you want the
value stored in x to be in y and vice versa)

>>> x = 2
>>> y = 3
>>> temp = x
>>> x = y
>>> y = temp
>>> x
3
>>> y
2
>>> 

Thus far, we have been using different names for variables. These names are technically
called identifiers
CAN be done with three simple assignments, but more efficiently with simultaneous
assignment

IDENTIFIERS

 Python has some rules about how identifiers can be formed


 Every identifier must begin with a letter or underscore, which may be followed by any
sequence of letters, digits, or underscores

>>> x1 = 10
>>> x2 = 20
>>> y_effect = 1.5
>>> celsius = 32
>>> 2celsius
  File "<stdin>", line 1
    2celsius
           ^
SyntaxError: invalid syntax

 Python has some rules about how identifiers can be formed


 Identifiers are case-sensitive

>>> x = 10
>>> X = 5.7
>>> print(x)
10
>>> print(X)
5.7

 Python has some rules about how identifiers can be formed


 Some identifiers are part of Python itself (they are called reserved words or keywords)
and cannot be used by programmers as ordinary identifiers

 Python has some rules about how identifiers can be formed


 Some identifiers are part of Python itself (they are called reserved words or keywords)
and cannot be used by programmers as ordinary identifiers
>>> for = 4
File "<stdin>", line 1
   for = 4
     ^
SyntaxError: invalid syntax

EXPRESSION

 You can produce new data (numeric or text) values in your program using expressions

>>> x = 2 + 3
>>> print(x)
5
>>> print(5 * 7)
35
>>> print("5" + "7")
57

 You can produce new data (numeric or text) values in your program using expressions

>>> x = 2 + 3
>>> print(x)
5
>>> print(5 * 7)
35
>>> print("5" + "7")
57

 This is an expression that uses the addition operator


 This is another expression that uses the multiplication operator

 You can produce new data (numeric or text) values in your program using expressions

>>> x = 2 + 3
>>> print(x)
5
>>> print(5 * 7)
35
>>> print("5" + "7")
57
 This is an expression that uses the addition operator
 This is another expression that uses the multiplication operator
 This is yet another expression that uses the addition operator but to concatenate (or glue)
strings together

 You can produce new data (numeric or text) values in your program using expressions
>>> x = 6
>>> y = 2
>>> print(x - y)
4
>>> print(x/y)
3.0
>>> print(x//y)
3

>>> print(x*y)
12
>>> print(x**y)
36
>>> print(x%y)
0
>>> print(abs(-x))
6

Summary of Operators

BRANCHING PROGRAMS

STRINGS

 letters, special characters, spaces, digits


 enclose in quotation marks or single quotes
hi = "hello there"

 concatenatestrings

name = "ana"
greet = hi + name
greeting = hi + ""+ name

 do some operationson a string as defined in Python docs

silly = hi + ""+ name * 3


LOGIC OPERATORS ON bools

A and bare variable names (with Boolean values)


not a Trueif ais FalseFalseif ais True
a and b Trueif both are True
a or bTrueif either or both are True

COMPARISON EXAMPLE

pset_time= 15
sleep_time= 8
print(sleep_time> pset_time)
derive = True
drink = False
both = drink and derive
print(both)

CONTROL FLOW –BRANCHING

<condition>has a value Trueor False


evaluate expressions in that block if <condition> is True

CONTROL FLOW: while LOOPS


while <condition>:
<expression>
<expression>
...
<condition> evaluates to a Boolean
if <condition> is True, do all the steps inside the while code block
check <condition> again
repeat until <condition> is False
CONTROL FLOW: while and for LOOPS

iterate through numbers in a sequence


# more complicated with while loop
n=0
while n < 5:
print(n)
n = n+1
# shortcut with for loop
for n in range(5):
print(n)

CONTROL FLOW: forLOOPS

for <variable> in range(<some_num>):


<expression>
<expression>
...
each time through the loop, <variable> takes a value
first time, <variable> starts at the smallest value
next time, <variable> gets the prevvalue + 1
etc.

range(start,stop,step)

default values are start = 0and step = 1and optional


loop until value is stop -1

mysum= 0
for iin range(7, 10):
mysum+= i
print(mysum)
mysum= 0
for iin range(5, 11, 2):
mysum+= i
print(mysum)

break STATEMENT
immediately exits whatever loop it is in
skips remaining expressions in code block
exits only innermost loop!

while <condition_1>:
while <condition_2>:
<expression_a>
break
<expression_b>
<expression_c>

BreakSTATEMENT

CONTROL STRUCTURE

A program statement that causes a jump of control from one part of the program to another is
called control structure or control statement.

1. Sequential Statement
A sequential statement is composed of a sequence of statements which are executed one after another. A
code to print your name, address and phone number is an example of sequential statement.
Example 6.1
#Program to print your name and address - example for sequential statement
print ("Hello! This is Shyam")
print ("43, Second Lane, North Car Street, TN")
Output
Hello! This is Shyam
43, Second Lane, North Car Street, TN
 
2. Alternative or Branching Statement
In our day-to-day life we need to take various decisions and choose an alternate path to achieve our goal.
May be we would have taken an alternate route to reach our destination when we find the usual road by
which we travel is blocked. This type of decision making is what we are to learn through alternative or
branching statement. Checking whether the given number is positive or negative, even or odd can all be
done using alternative or branching statement.
Python provides the following types of alternative or branching statements:
Simple if statement
if..else statement
if..elif statement

(i) Simple if statement


Simple if is the simplest of all decision making statements. Condition should be in the
Syntax:
if <condition>:
statements-block1form of relational or logical expression.
In the above syntax if the condition is true statements - block 1 will be executed.

Examplem - Program to check the age and print whether eligible for voting
x=int (input("Enter your age :"))
if x>=18:
print ("You are eligible for voting")
Output 1:
Enter your age :34
You are eligible for voting
Output 2:
Enter your age :16
>>> 
As you can see in the second execution no output will be printed, only the Python prompt will be
displayed because the program does not check the alternative process when the condition is failed.

(ii) if..else statement


The if .. else statement provides control to check the true block as well as the false block. Following is the
syntax of ‘if..else’ statement.
Syntax:
if <condition>:
statements-block 1
else:
statements-block 2

if..else statement thus provides two possibilities and the condition determines which BLOCK is to be
executed.

Example -Program to check if the accepted number odd or even


a = int(input("Enter any number :"))
if a%2==0:
print (a, " is an even number")
else:
print (a, " is an odd number")
Output 1:
Enter any number :56
56 is an even number
Output 2:
Enter any number :67
67 is an odd number
An alternate method to rewrite the above program is also available in Python. The complete if..else can
also written as:
Syntax:
variable = variable1 if condition else variable 2

Example -Program to check if the accepted number is odd or even (using alternate method of
if...else)
a = int (input("Enter any number :"))
x="even" if a%2==0 else "odd"
print (a, " is ",x)
Output 1:
Enter any number :3
3 is odd
Output 2:
Enter any number :22
22 is even

Nested if..elif...else statement:

When we need to construct a chain of if statement(s) then ‘elif’ clause can be used instead of ‘else’.
Syntax:
if <condition-1>:
statements-block 1
elif <condition-2>:
statements-block 2
else:
statements-block n
In the syntax of if..elif..else mentioned above, condition-1 is tested if it is true then statements-block1 is
executed, otherwise the control checks condition-2, if it is true statements-block2 is executed and even if
it fails statements-block n mentioned in else part is executed.

‘elif’ clause combines if..else-if..else statements to one if..elif…else. ‘elif’ can be considered to be


abbreviation of ‘else if’. In an ‘if’ statement there is no limit of ‘elif’ clause that can be used, but
an ‘else’ clause if used should be placed at the end.
if..elif..else statement is similar to nested if statement which you have learnt in C++.
Example -Program to illustrate the use of nested if statement
Average               Grade
>=80 and above             A
>=70 and <80                B
>=60 and <70                C
>=50 and <60                D
Otherwise             E
m1=int (input(“Enter mark in first subject : ”))
m2=int (input(“Enter mark in second subject : ”))
avg= (m1+m2)/2
if avg>=80:
print (“Grade : A”)
elif avg>=70 and avg<80:
print (“Grade : B”)
elif avg>=60 and avg<70:
print (“Grade : C”)
elif avg>=50 and avg<60:
print (“Grade : D”)
else:
print (“Grade : E”)

Output 1:
Enter mark in first subject : 34
Enter mark in second subject : 78
Grade : D

Output 2 :
Enter mark in first subject : 67

Note
The two blocks of code in our example of if-statement are both indented four spaces, which is a typical
amount of indentation for Python. In most other programming languages, indentation is used only to
help make the code look pretty. But in Python, it is required to indicate to which block of code the
statement belongs to.

Example -Program to illustrate the use of ‘in’ and ‘not in’ in if statement
ch=input (“Enter a character :”)
# to check if the letter is vowel
if ch in (‘a’, ‘A’, ‘e’, ‘E’, ‘i’, ‘I’, ‘o’, ‘O’, ‘u’, ‘U’):
print (ch,’ is a vowel’)
#to check if the letter typed is not ‘a’ or ‘b’ or ‘c’ if ch not in (‘a’, ’b’, ’c’):
print (ch,’ the letter is not a/b/c’)

Output 1:
Enter a character :e
e is a vowel

Output 2:
Enter a character :x
x the letter is not a/b/c
3. Iteration or Looping constructs

Iteration or loop are used in situation when the user need to execute a block of code several of times or till
the condition is satisfied. A loop statement allows to execute a statement or group of statements multiple
times.

Python provides two types of looping constructs:


(i) while loop
(ii) for loop

(i) while loop

The syntax of while loop in Python has the following syntax:


Syntax:
while <condition>:
statements block 1
[else:
statements block2]

In the while loop, the condition is any valid Boolean expression returning True or False. The else part of
while is optional part of while. The statements block1 is kept executed till the condition is True. If
the else part is written, it is executed when the condition is tested False. Recall while loop belongs to
entry check loop type, that is it is not executed even once if the condition is tested False in the beginning.
Example - Program to illustrate the use of while loop - to print all numbers from 10 to 15
i=10  # intializing part of the control variable
while (i<=15):       # test condition
print (i,end='\t')    # statements - block 1
i=i+1 # Updation of the control variable

Output:
10 11 12      13      14      15

Note
That the control variable is i, which is initialized to 10, the condition is tested i<=15, if true value of i gets
printed, then the control variable i gets updated as i=i+1 (this can also be written as i +=1 using shorthand
assignment operator). When i becomes 16, the condition is tested False and this will terminate the loop.

Note

print can have end, sep as parameters. end parameter can be used when we need to give any escape
sequences like ‘\t’ for tab, ‘\n’ for new line and so on. sep as parameter can be used to specify any special
characters like, (comma) ; (semicolon) as separator between values (Recall the concept which you have
learnt in previous chapter about the formatting options in print()).
Following is an example for using else part within while loop.

Example- Program to illustrate the use of while loop - with else part
i=10  # intializing part of the control variable
while (i<=15):       # test condition
print (i,end='\t')    # statements - block 1
i=i+1 # Updation of the control variable
else:  
print ("\nValue of i when the loop exit ",i)

Output: 1
10 11 12 13 14 15
Value of i when the loop exit 16

(ii) for loop

for loop is the most comfortable loop. It is also an entry check loop. The condition is checked in the
beginning and the body of the loop(statements-block 1) is executed if it is only True otherwise the loop is
not executed.

Syntax:
for counter_variable in sequence:
statements-block 1
[else:         # optional block
statements-block 2]

The counter_variable mentioned in the syntax is similar to the control variable that we used in


the for loop of C++ and the sequence refers to the initial, final and increment value. Usually in
Python, for loop uses the range() function in the sequence to specify the initial, final and increment
values. range() generates a list of values starting from start till stop-1.

The syntax of range() is as follows:


range (start,stop,[step])
Where,       
start  –        refers to the initial value
stop   –        refers to the final value
step   –        refers to increment value, this is optional part.

Example 6.8:Examples for range()


range (1,30,1) will start the range of values from 1 and end at 29
range (2,30,2) will start the range of values from 2 and end at 28
range (30,3,-3) - will start the range of values from 30 and end at 6
range (20)   will consider this value 20 as the end value(or upper limit) and starts the range count from 0
to 19 (remember always range() will work till stop -1 value only)

Example -Program to illustrate the use of for loop - to print single digit even number
for i in range (2,10,2):
print (i, end=' ')

Output:
2468
Following is an illustration using else part in for loop

Example 6.10: #program to illustrate the use of for loop - to print single digit even number with else
part
for i in range(2,10,2):
print (i,end=' ')
else:
print ("\nEnd of the loop")

Output:
2468
End of the loop

(iii) Nested loop structure


A loop placed within another loop is called as nested loop structure. One can place a while within
another while; for within another for; for within while and while within for to construct such nested
loops.
Following is an example to illustrate the use of for loop to print the following pattern 1
12
123
1234
12345

Example -Program to illustrate the use nested loop -for within while loop
i=1
while (i<=6):
for j in range (1,i):
print (j,end='\t')
print (end='\n')
i +=1
 

3. Jump Statements in Python

The jump statement in Python, is used to unconditionally transfer the control from one part of the
program to another. There are three keywords to achieve jump statements in Python : break, continue,
pass. The following flowchart illustrates the use of break and continue.

(i) break statement

The break statement terminates the loop containing it. Control of the program flows to the statement
immediately after the body of the loop.
A while or for loop will iterate till the condition is tested false, but one can even transfer the control out
of the loop (terminate) with help of break statement. When the break statement is executed, the control
flow of the program comes out of the loop and starts executing the segment of code after the loop
structure.
If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost
loop.
The working of break statement in for loop and while loop is shown below.

Assessment

Find the output of the following pseudo code.

1.
num1 = 10
num2 = 14
num3 = 12

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number between",num1,",",num2,"and",num3,"is",largest)

Output
2.

def lcm(x, y):


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm

num1 = 54
num2 = 24

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))

print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2))

Output

3.

kilometers = 5.5
conv_fac = 0.621371

miles = kilometers * conv_fac


print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles))

Output
Part II

 This module begins with a brief discussion on functions, scoping and abstraction, each topics ends with
an example to the students clearly understand the topics. It aims to acquire programming skill of Python,
and application of in data structure and algorithm. At the end of this module an exercises was given to
assess if the students understood the discussion.

By the end of this module, students will able to:


To acquire programming skills in core Python.
To acquire the application of concepts in data structures and algorithm analysis

In Python each function definition is of the form

def name of function (list of formal parameters): body of function


For example, we could define the function maxVal by the code

def maxVal(x, y):


if x > y:
return x
else:
return y

def is a reserved word that tells Python that a function is about to be defined. The function name (maxVal
in this example) is simply a name that is used to refer to the function.
The sequence of names within the parentheses following the function name (x, y in this example) are the
formal parameters of the function. When the function is used, the formal parameters are bound (as in an
assignment statement) to the actual parameters (often referred to as arguments) of the function
invocation (also referred to as a function call). For example, the invocation:

maxVal(3, 4)
binds x to 3 and y to 4.

The function body is any piece of Python code. There is, however,a special statement, return, that can be
used only within the body of a function.

A function call is an expression, and like all expressions it has a value. That value is the value returned by
the invoked function. For example, the value of the expression maxVal(3,4)*maxVal(3,2) is 12, because
the first invocation of maxVal returns theint 4and the second returns theint 3. Note that execution of a
return statement terminates an invocation of the function.
To recapitulate, when a function is called:
1. The expressions that make up the actual parameters are evaluated, and the formal parameters of
the function are bound to the resulting values. For example, the invocation maxVal(3+4, z) will
bind the formal parameter x to 7 and the formal parameter y to whatever value the variable z has
when the invocation is evaluated.
2. The point of execution (the next instruction to be executed) moves from the point of invocation to
the first statement in the body of the function.
3. The code in the body of the function is executed until either a return statement is encountered, in
which case the value of the expression following the return becomes the value of the function
invocation, or there are no more statements to execute, in which case the function returns the
value None. (If no expression follows the return, the value of the invocation is None.)
4. The value of the invocation is the returned value.
5. The point of execution is transferred back to the code immediately following the invocation.

Parameters provide something called lambda abstraction, allowing programmers to write code that
manipulates not specific objects, but instead whatever objects the caller of the function chooses to use as
actual parameters.

Keyword Arguments and Default Values

In Python, there are two ways that formal parameters get bound to actual parameters. The most common
method, which is the only one we have used thus far, is called positional—the first formal parameter is
bound to the first actual parameter, the second formal to the second actual, etc. Python also supports
keyword arguments, in which formals are bound to actuals using the name of the formal parameter.
Consider the function definition:

def printName(firstName, lastName, reverse):


if reverse:
print(lastName + ', ' + firstName)
else:
print(firstName, lastName)

The function printName assumes that firstName and lastName are strings and that reverse is a Boolean. If
reverse == True, it prints lastName, firstName, otherwise it prints firstName lastName.
Each of the following is an equivalent invocation of printName:

printName('Olga', 'Puchmajerova', False)


printName('Olga', 'Puchmajerova', reverse = False)
printName('Olga', lastName = 'Puchmajerova', reverse = False) printName(lastName = 'Puchmajerova',
firstName = ' Olga', reverse = False)

Though the keyword arguments can appear in any order in the list of actual parameters, it is not legal to
follow a keyword argument with a non-keyword argument. Therefore, an error message would be
produced by:

printName('Olga', lastName = 'Puchmajerova', False)


Keyword arguments are commonly used in conjunction with default parameter values. We can, for
example, write:

def printName(firstName, lastName, reverse = False):


if reverse:
print(lastName + ', ' + firstName)
else:
print(firstName, lastName)

Scoping

Let’s look at another small example,

def f(x): #name x used as formal parameter


y=1
x=x+y
print("x = %s" %x)
return x
x=3
y =2
z = f(x) #value of x used as actual parameter
print('z =', z)
print('x =', x)
print('y =', y)
# When run, this code prints,
x=4
z=4
x=3
y=2

In Python, one can always determine the scope of a name by looking at the program text. This is called
static or lexical scoping. Figure 4.2 contains an example illustrating Python’s scope rules.

def f(x):
def g():
x = 'abc'
print('x1 =', x)
def h():
z=x
print('z1 =', z)
x=x+1
print('x2 =', x)
h()
g()
print('x3 =', x)
return g
x=3
z = f(x)
print('x4 =', x)
print('z2 =', z)
z()
So, what does the code in Figure 4.2 print? It prints
x2 = 4
z1 = 4
x1 = abc
x3 = 4
x4 = 3
z2 = <function f.<locals>.g at 0x10188d0d0>
The history of the stack frames associated with the code is depicted in Figure 4.3. The first column
contains the set of names known outside the body of the function f, i.e., the variables x and z, and the
function name f. The first assignment statement binds x to 3.

Figuue 4.3
def f():
print('x1 =', x)
def g():
print('x2 =', x)
x=1

x=3
f()
x=3
g()

# When run, this code prints,


x1 = 3
Traceback (most recent call last):
File "4.FunctionScoping.py", line 43, in <module>
g()
File "4.FunctionScoping.py", line 37, in g
print('x2 =', x)
UnboundLocalError: local variable 'x' referenced before assignment
It prints 3 when f is invoked, but the error message UnboundLocalError: local variable 'x' referenced
before assignment is printed when the print statement in g is encountered. This happens because the
assignment statement following the print statement causes x to be local to g. And because x is local tog, it
has no value when the print statement is executed.
Confused yet? It takes most people a bit of time to get their head around scope rules. Don’t let this bother
you. For now, charge ahead and start using functions. Most of the time you will find that you only want to
use variables that are local to a function, and the subtleties of scoping will be irrelevant.

Specifications
It defines a function, findRoot, that generalizes the bisection search we used to find square roots in Figure
4.1. It also contains a function, testFindRoot, that can be used to test whether or not findRoot works as
intended.

Finding an approximation to a root


print('Figure 4.4 Finding an approximation to a root')
def findRoot(x, power, epsilon):
"""Assume x and epsilon int or float, power an int,
epsilon > 0 and power >= 1
Return float y such that y**power is with epsilon of x.
If such a float does not exists, it returns None"""
if x < 0 and power%2 == 0: #Negative number has no even-powered roots.
return None
low = min(-1.0, x)
high = max(1.0, x)
ans = (high + low)/2
while abs(ans**power -x) >= epsilon:
if ans**power < x:
low = ans
else:
high = ans
ans = (high + low)/2.0
return ans

def testFindRoot():
epsilon = 0.01**2
for x in [0.25, -0.25, 2, -2, 8, -8]:
for power in range(1, 4):
print('Testing x=%s, and power=%s' %(x, power))
result = findRoot(x, power, epsilon)
if result == None:
print(' No root')
else:
print(' %s ** %s ~= %s' %(result, power, x))

testFindRoot()
# When runs, the code print:

MODULES
 One problem with entering code interactively into a Python shell is that the definitions are lost
when we quit the shell
 If we want to use these definitions again, we have to type them all over again!
 To this end, programs are usually created by typing definitions into a separate file called
a module or script
 This file is saved on disk so that it can be used over and over again
 A Python module file is just a text file with a .py extension, which can be created using
any program for editing text (e.g., notepad or vim)

Assessment

1. Which of the following statement is true?

a. Function are used to create objects in Python


b. Function makes your program run faster
c. Function is a piece of code that performs specific task
d. All of the above

2. What is the output of the following code?


def printLine(text):
print(text, 'is awesome.')
printLine('Python')

a. Python
b. Python is awesome
c. Text is awesome
d. Is awesome

3. What is the output of the following code?

def greetPerson(*name):
print('Hello', name)
greetPerson('Frodo', 'Sauron')

a. Hello Frodo Hello Sauron


b. Hello (‘Frodo’, ‘Sauron’)
c. Hello Frodo
d. Syntax error! greetPerson() can take only one argument

4. What is a recursive function?


a. A function that calls all the function in the program
b. A function that calls itself
c. A function that call the function in the program except itself
d. There are no such thing as recursive function in Python.

5. A high-level programming language developed by Guido van Rossum and started the
development in the 1980’s.
a. Python
b. C++
c. Java
d. Assembly Language
6. It is used to indicate a specific value, which can be assigned to a variable.
a. Elements
b. Literals
c. Function
d. Statements

7. This built in function will evaluate a formula and return its value which is then assigned to a
variable.
a. Input
b. Int
c. Float
d. Eval

8. Adding a float and an integer will automatically result in a float value, Adding a string and an
integer (or a float) will result in an error since string is not numeric. This statements is true for
a. Explicit Data Conversion
b. Implicit Data Conversion
c. Mathematical Conversion
d. Both A and B

9. It helps programmers write programs and includes features such as automatic indenting, color
highlighting, and interactive development.
a. Programming Language
b. Syntax
c. Programming Environment
d. Identifiers and Expression

10. A sub-program in Python which performs task which may need to be repeated.
a. Methods
b. Functions
c. Libraries
d. Literals
Part III
The module begins with a brief introduction to structure types of Python, mutability and higher order
functions. It differentiate List, Tuple, Set and Dictionary and different example using different iteration of
each structure. It also discusses the use of each structure in different functions (e.g. add, delete, display).
This module also introduce the built-in methods available in python. This module aims to improve the
programming skills and knowledge of the student.
At the end of the module an examination is given to assess if the students understood the topics.

By the end of this module, students will able to:


To acquire programming skills in core Python.
To acquire the application of concepts in data structures and algorithm analysis

Python Collections (Arrays)

There are four collection data types in the Python programming language:
 List is a collection which is ordered and changeable. Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
 Set is a collection which is unordered and unindexed. No duplicate members.
 Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.
When choosing a collection type, it is useful to understand the properties of that type. Choosing the right
type for a particular data set could mean retention of meaning, and, it could mean an increase in
efficiency or security.

List
A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

Example
Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)

Access Items
You access the list items by referring to the index number:
Example
Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last
item etc.
Example
Print the last item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
Return the third, fourth, and fifth item:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to "orange":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[:4])

By leaving out the end value, the range will go on to the end of the list:
Example
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])

Range of Negative Indexes


Specify negative indexes if you want to start the search from the end of the list:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])

Change Item Value


To change the value of a specific item, refer to the index number:
Example
Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)

Loop Through a List


You can loop through the list items by using a for loop:
Example
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
  print(x)
You will learn more about for loops in our Python For Loops Chapter.

Check if Item Exists


To determine if a specified item is present in a list use the in keyword:
Example
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
  print("Yes, 'apple' is in the fruits list")

List Length
To determine how many items a list has, use the len() function:
Example
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))

Add Items
To add an item to the end of the list, use the append() method:
Example
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)

To add an item at the specified index, use the insert() method:


Example
Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)

Remove Item
There are several methods to remove items from a list:
Example
The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)

Example
The pop() method removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)

Example
The del keyword removes the specified index:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)

Example
The del keyword can also delete the list completely:
thislist = ["apple", "banana", "cherry"]
del thislist

Example
The clear() method empties the list:
thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)

Copy a List
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference to list1, and
changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Example
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

Another way to make a copy is to use the built-in method list().


Example
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)

Join Two Lists


There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
Example
Join two list:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list3 = list1 + list2


print(list3)

Another way to join two lists are by appending all the items from list2 into list1, one by one:
Example
Append list2 into list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
  list1.append(x)

print(list1)

Or you can use the extend() method, which purpose is to add elements from one list to another list:
Example
Use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]

list1.extend(list2)
print(list1)

The list() Constructor


It is also possible to use the list() constructor to make a new list.
Example
Using the list() constructor to make a List:
thislist = list(("apple", "banana", "cherry")) # note the double round-brackets
print(thislist)

List Methods
Python has a set of built-in methods that you can use on lists.
Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list


Tuple

A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round
brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Access Tuple Items


You can access tuple items by referring to the index number, inside square brackets:
Example
Print the second item in the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])

Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last
item etc.
Example
Print the last item of the tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])

Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Return the third, fourth, and fifth item:
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[2:5])

Note: The search will start at index 2 (included) and end at index 5 (not included).
Remember that the first item has index 0.
Range of Negative Indexes
Specify negative indexes if you want to start the search from the end of the tuple:
Example
This example returns the items from index -4 (included) to index -1 (excluded)
thistuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
print(thistuple[-4:-1])

Change Tuple Values


Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also
is called.
But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back
into a tuple.
Example
Convert the tuple into a list to be able to change it:
x = ("apple", "banana", "cherry")
y = list(x)
y[1] = "kiwi"
x = tuple(y)

print(x)

Loop Through a Tuple


You can loop through the tuple items by using a for loop.
Example
Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
  print(x)

You will learn more about for loops in our Python For Loops Chapter.

Check if Item Exists


To determine if a specified item is present in a tuple use the in keyword:
Example
Check if "apple" is present in the tuple:
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
  print("Yes, 'apple' is in the fruits tuple"

Tuple Length
To determine how many items a tuple has, use the len() method:
Example
Print the number of items in the tuple:
thistuple = ("apple", "banana", "cherry")
print(len(thistuple))

Add Items
Once a tuple is created, you cannot add items to it. Tuples are unchangeable.
Example
You cannot add items to a tuple:
thistuple = ("apple", "banana", "cherry")
thistuple[3] = "orange" # This will raise an error
print(thistuple)

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not
recognize it as a tuple.
Example
One item tuple, remember the commma:
thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Remove Items
Note: You cannot remove items in a tuple.
Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:
Example
The del keyword can delete the tuple completely:
thistuple = ("apple", "banana", "cherry")
del thistuple
print(thistuple) #this will raise an error because the tuple no longer exists

Join Two Tuples


To join two or more tuples you can use the + operator:
Example
Join two tuples:
tuple1 = ("a", "b" , "c")
tuple2 = (1, 2, 3)

tuple3 = tuple1 + tuple2


print(tuple3)

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.
Example
Using the tuple() method to make a tuple:
thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
print(thistuple)

Tuple Methods
Python has two built-in methods that you can use on tuples.
Method Description

count() Returns the number of times a specified value occurs in a tuple

index() Searches the tuple for a specified value and returns the position of where it was found

Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are
written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]

There is also a method called get() that will give you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")

Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["year"] = 2018

Loop Through a Dictionary


You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but there are methods
to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
  print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
  print(thisdict[x])

Example
You can also use the values() method to return values of a dictionary:
for x in thisdict.values():
  print(x)

Example
Loop through both keys and values, by using the items() method:
for x, y in thisdict.items():
  print(x, y)

Check if Key Exists


To determine if a specified key is present in a dictionary use the in keyword:
Example
Check if "model" is present in the dictionary:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
if "model" in thisdict:
  print("Yes, 'model' is one of the keys in the thisdict dictionary")

Dictionary Length
To determine how many items (key-value pairs) a dictionary has, use the len() function.
Example
Print the number of items in the dictionary:
print(len(thisdict))

Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.pop("model")
print(thisdict)

Example
The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed
instead):
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.popitem()
print(thisdict)

Example
The del keyword removes the item with the specified key name:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict["model"]
print(thisdict)

Example
The del keyword can also delete the dictionary completely:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
del thisdict
print(thisdict) #this will cause an error because "thisdict" no longer exists.

Example
The clear() method empties the dictionary:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
thisdict.clear()
print(thisdict)
Copy a Dictionary
You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be
a reference to dict1, and changes made in dict1 will automatically also be made in dict2.
There are ways to make a copy, one way is to use the built-in Dictionary method copy().
Example
Make a copy of a dictionary with the copy() method:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = thisdict.copy()
print(mydict)

Another way to make a copy is to use the built-in function dict().


Example
Make a copy of a dictionary with the dict() function:
thisdict = {
  "brand": "Ford",
  "model": "Mustang",
  "year": 1964
}
mydict = dict(thisdict)
print(mydict)

Nested Dictionaries
A dictionary can also contain many dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
  "child1" : {
    "name" : "Emil",
    "year" : 2004
  },
  "child2" : {
    "name" : "Tobias",
    "year" : 2007
  },
  "child3" : {
    "name" : "Linus",
    "year" : 2011
 }
}

Or, if you want to nest three dictionaries that already exists as dictionaries:
Example
Create three dictionaries, then create one dictionary that will contain the other three dictionaries:
child1 = {
  "name" : "Emil",
  "year" : 2004
}
child2 = {
  "name" : "Tobias",
  "year" : 2007
}
child3 = {
  "name" : "Linus",
  "year" : 2011
}

myfamily = {
  "child1" : child1,
  "child2" : child2,
  "child3" : child3
}

The dict() Constructor


It is also possible to use the dict() constructor to make a new dictionary:
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.
Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

Assessment

1. The following code should print the numbers beginning at 100 and ending with 0. However it is
missing a line of code. Add the missing code, using the shortcut operator. Indicate where the code
belongs. (5 pts)

countdown = 100
while countdown > 0:
print(countdown)
print(“Done!”)

2. Examine the following codes.

doAgain = "y"
while doAgain == "y":
word = input("Enter a word:")
print("First letter of " + word + " is " + word[0])
doAgain = input("Type ‘y’ to enter another word and anything else to quit.")
print("Done!")

a. What does the program do?


b. What is the name of the variable used to store the user’s input?
c. In the print statement, what does word[0]represent?

3. The following line of code prints the first element in the digits list. (5 pts)

fruits = [“apple’, ‘banana’, “cantelope”, “pear”]


print (fruits[0])

a. What value does fruits[3] represent?


b. Enter and type the fruits list and write a line of code that prints the last value.
c. Edit your print statement in ‘b’ so that it prints fruits[4]. What is printed? Why?
d. Edit your print statement so that it prints fruits[-1]. What is printed?
e. Change -1 to -2 in “d.”. What is printed?
Part IV

The module begins with a brief introduction of Testing and Debugging and discusses its differences. It
also discusses the basics of Testing, the steps in performing testing and the different technique in software
testing. It also introduce the steps and strategies in debugging. This module aims to improve the
programming skills and knowledge and for the students to understand the importance of testing and
debugging in programming.

At the end of the module an examination is given to assess if the students understood the topics.

By the end of this module, students will able to:

To acquire programming skills in core Python.


To acquire the application of concepts in data structures and algorithm analysis

Testing
Testing is the process of verifying and validating that a software or application is bug free, meets the
technical requirements as guided by its design and development and meets the user requirements
effectively and efficiently with handling all the exceptional and boundary cases.

Debugging
Debugging is the process of fixing a bug in the software. It can defined as the identifying, analyzing and
removing errors. This activity begins after the software fails to execute properly and concludes by solving
the problem and successfully testing the software. It is considered to be an extremely complex and tedious
task because errors need to be resolved at all stages of debugging.

Below is the difference between testing and debugging:

TESTING DEBUGGING

Testing is the process to find bugs and Debugging is the process to correct the bugs
errors. found during testing.

It is the process to identify the failure of It is the process to give the absolution to code
implemented code. failure.
TESTING DEBUGGING

Testing is the display of errors. Debugging is a deductive process.

Debugging is done by either programmer or


Testing is done by the tester. developer.

There is no need of design knowledge in Debugging can’t be done without proper


the testing process. design knowledge.

Testing can be done by insider as well as Debugging is done only by insider. Outsider
outsider. can’t do debugging.

Debugging is always manual. Debugging


Testing can be manual or automated. can’t be automated.

It is based on different testing levels i.e.


unit testing, integration testing, system Debugging is based on different types of
testing etc. bugs.

Debugging is not an aspect of software


Testing is a stage of software development life cycle, it occurs as a
development life cycle (SDLC). consequence of testing.

While debugging process seeks to match


Testing is composed of validation and symptom with cause, by that it leads to the
verification of software. error correction.

Testing is initiated after the code is Debugging commences with the execution of
written. a test case.

Software Testing | Basics

Software testing can be stated as the process of verifying and validating that a software or application is
bug free, meets the technical requirements as guided by it’s design and development and meets the user
requirements effectively and efficiently with handling all the exceptional and boundary cases.
The process of software testing aims not only at finding faults in the existing software but also at finding
measures to improve the software in terms of efficiency, accuracy and usability. It mainly aims at
measuring specification, functionality and performance of a software program or application.

Software testing can be divided into two steps:

1. Verification: it refers to the set of tasks that ensure that software correctly implements a specific
function.

2. Validation: it refers to a different set of tasks that ensure that the software that has been built is
traceable to customer requirements.
Verification: “Are we building the product right?”
Validation: “Are we building the right product?”

What are different techniques of Software Testing?

Software techniques can be majorly classified into two categories:

1. Black Box Testing: The technique of testing in which the tester doesn’t have access to the source
code of the software and is conducted at the software interface without concerning with the
internal logical structure of the software is known as black box testing.

2. White-Box Testing: The technique of testing in which the tester is aware of the internal
workings of the product, have access to it’s source code and is conducted by making sure that all
internal operations are performed according to the specifications is known as white box testing.

BLACK BOX TESTING WHITE BOX TESTING

Internal workings of an application are not


required. Knowledge of the internal workings is must.
Also known as closed box/data driven testing. Also knwon as clear box/structural testing.
End users, testers and developers. Normally done by testers and developers.
THis can only be done by trial and error Data domains and internal boundaries can be better
method. tested.

Debugging

In the context of software engineering, debugging is the process of fixing a bug in the software. In other
words, it refers to identifying, analyzing and removing errors. This activity begins after the software fails
to execute properly and concludes by solving the problem and successfully testing the software. It is
considered to be an extremely complex and tedious task because errors need to be resolved at all stages of
debugging.

Debugging Process: Steps involved in debugging are:


 Problem identification and report preparation.
 Assigning the report to software engineer to the defect to verify that it is genuine.
 Defect Analysis using modeling, documentations, finding and testing candidate flaws, etc.
 Defect Resolution by making required changes to the system.
 Validation of corrections.

Debugging Strategies:
1. Study the system for the larger duration in order to understand the system. It helps debugger to
construct different representations of systems to be debugging depends on the need. Study of the
system is also done actively to find recent changes made to the software.
2. Backwards analysis of the problem which involves tracing the program backward from the
location of failure message in order to identify the region of faulty code. A detailed study of the
region is conducting to find the cause of defects.
3. Forward analysis of the program involves tracing the program forwards using breakpoints or print
statements at different points in the program and studying the results. The region where the
wrong outputs are obtained is the region that needs to be focused to find the defect.
4. Using the past experience of the software debug the software with similar problems in nature.
The success of this approach depends on the expertise of the debugger.

Assessment:

Python programming

Purpose: To practice testing and debugging code that someone else wrote.
In the provided le a8q2_functions.py you’ll nd two functions:
• isValidPhoneNumber(): Returns True if the provided phone number (represented as a string) is correctly
formatted, otherwise False. To be considered correctly formatted, phone numbers must be
written as ###-###-####, where # is a digit between 0 and 9.
• validatePhoneBook(): A phone book is a list where each entry is a phone book record (represented as
a dictionary; see below for more details). This function checks each phone book record in the phone
book for correctly formatted phone numbers.
A phone book record is a dictionary which initially has two keys: the key "name" mapped to the
contact’s name (string) and the key "phone number" mapped to that contact’s phone number (also
a string). validatePhoneBook() adds a new key "valid" to the record with the value True if the phone
number is formatted correctly, otherwise False.

Here is how a sample phone book might look before and after validatePhoneBook():
✞☎
# before
[ { " name " : " Department of Computer Science ",
" phone number " : " 306 -966 -4886 " },
{ " name " : " Department of History ",
" phone number " : " 306.966.8712 " } ]
# after
[ { " name " : " Department of Computer Science ",
" phone number " : " 306 -966 -4886 ",
" valid " : True },
{ " name " : " Department of History ",
" phone number " : " 306.966.8712 ",
" valid " : False } ]
✝ ✆
The provided
Searching Algorithm - is an algorithm made up of a series of instructions that retrieves information
stored within some data structure, or calculated in the search space of a problem domain.

There are many sorting algorithms, such as:

 Linear Search,
 Binary Search,
 Jump Search,
 Interpolation Search,
 Exponential Search,
 Ternary Search

Linear Search is a method for finding a target value within a list. It sequentially checks each element of
the list for the target value until a match is found or until all the elements have been searched.

Algorithm:

Step1: Start from the leftmost element of array and one by one compare x with each element of array.
Step2: If x matches with an element, return the index
Step3: If x doesn’t match with any of elements, return -1.

Assume the following Array:


Search for 9
Binary Search is the most popular Search algorithm. It is efficient and also one of the most
commonly used techniques that is used to solve problems. Binary search use sorted array by repeatedly
dividing the search interval in half

Algorithm:

Step1: Compare x with the middle element.


Step2: If x matches with middle element, we return the mid index.
Step3: Else If x is greater than the mid element, search on right half.
Step4: Else If x is smaller than the mid element, search on left half.

Assume the following Array:


Search for 40
Jump Search is a searching algorithm for sorted arrays. The basic idea is to check fewer elements
(than linear search) by jumping ahead by fixed steps or skipping some elements in place of searching all
elements

Algorithm:

Step1: Calculate Jump size


Step2: Jump from index i to index i+jump
Step3: If x = = arr[i+jump] return x
Else jump back a step
Step4: Perform linear search

Assume the following sorted array:


Search for 77

Calculate:
Size of array n =16
Jump size = sqrt(n)= 4

Jump size = 4
Search from index 0
Compare index value with search number 0<77
Jump size = 4
Jump from index 0 to index 3
Compare index value with search number 2<77

Jump size = 4
Jump from index 3 to index 6
Compare index value with search number 8<77

Jump size = 4
Jump from index 6 to index 9
Compare index value with search number 34<77

Jump size = 4
Jump from index 9 to index 12
Compare index value with search number 89>77

Jump back a step


Perform linear search
Compare found at index 11
Interpolation Search is an improvement over Binary Search for instances. On the other hand
interpolation search may go to different locations according the value of key being searched.

Algorithm:

Step1: In a loop, calculate the value of “pos” using the position formula.
Step2: If it is a match, return the index of the item, and exit.
Step3: If the item is less than arr[pos], calculate the position of the left sub-array. Otherwise calculate the
same in the right sub-array.
Step4: Repeat until a match is found or the sub-array reduces to zero.

// The idea of formula is to return higher value of pos


// when element to be searched is closer to arr[hi]. And
// smaller value when closer to arr[lo]

pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]

arr[] ==> Array where elements need to be searched


x ==> Element to be searched
lo ==> Starting index in arr[]
hi ==> Ending index in arr[]

Assume the following sorted array:


Search for x= 18
Calculate pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]
Lo=0, hi=14, arr[lo]=10, arr[hi]= 47

Calculate pos = 3
Compare with x=18

Calculate pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]


Lo=4, hi=14, arr[lo]=18, arr[hi]= 47

Calculate pos = 4
Compare with x=18 , found at index 4

Time Complexity: If elements are uniformly distributed, then O (log log n)). In worst case it can take up
to O(n).

Python Code
Refences:

Spector, P. (2005, March 16). Introduction to Python Programming Course Notes.


Hammoud, M. (2020, August). 15-110: Principles of Computing. Basic Elements of Python Programs.
Carnegie Mellon University in Qatar; Carnegie Mellon University in Qatar.
Massachusetts Institute of Technology. (2020, August). Branching, Iteration. 6.0001 Introduction to
Computer Science and Programming in Python. Massachusetts Institute of Technology.
Python Control Structures - Python. BrainKart. http://www.brainkart.com/article/Python-Control-
Structures_37234/.
4.Functions, Scoping, and Abstraction. 简书. https://www.jianshu.com/p/4617b75258f2.
Python List. Python Lists. https://www.w3schools.com/python/python_lists.asp.

pp_pankajCheck out this Author's contributed articles., pp_pankaj, & Check out this Author's contributed
articles. (2020, February 27). Differences between Testing and Debugging. GeeksforGeeks.
https://www.geeksforgeeks.org/differences-between-testing-and-debugging/.

https://www.chegg.com/homework-help/questions-and-answers/python-programming-purpose-practice-
testing-debugging-code-someone-else-wrote-provided-le--q25356921

Dr. Mohamed Loey, Analysis and Design of Algorithm, Faculty of Computer and Information Benha
University, Egypt

You might also like