Your first Python program
• When learning a new computer programming language, the
first thing typically taught is how to write a message to the
screen saying “Hello, World”.
• Let’s see how to do that:
# HelloWorldProgram – Version 1
# A program to print out “Hello, World”
# Written by: Damian Gordon
# Date: 10/09/2015
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
Using Variables
• Variables are easy to use in Python, there is no need to declare
the type of the variable.
• Python will work it out for you (mostly!).
Convert Description Result
int(x) Convert variable into an integer, e.g.
x = “10”
int(x)
10
float(x) Convert variable into a real e.g.
x = “10.5”
float(x)
10.5
str(x) Convert variable into an string, e.g.
x = 10
str(x)
“10”
Using Variables
• The following words cannot be used as variable names:
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
# PROGRAM AnotherSimpleIfStatement:
x = int(input())
y = int(input())
if x > y:
# THEN
print(x, “is bigger than”, y)
else:
print(y, “is bigger than”, x)
# ENDIF;
# END.
# PROGRAM AnotherSimpleIfStatementPrints:
print(“Please input the first value”)
x = int(input())
print(“Please second the second value”)
y = int(input())
if x > y:
# THEN
print(x, “is bigger than”, y)
else:
print(y, “is bigger than”, x)
# ENDIF;
# END.
# PROGRAM AnotherSimpleIfStatementPrintsShorter:
x = int(input(“Please input the first valuen”))
y = int(input(“Please second the second valuen”))
if x > y:
# THEN
print(x, “is bigger than”, y)
else:
print(y, “is bigger than”, x)
# ENDIF;
# END.
# PROGRAM BiggerOfThree:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
else:
if b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# ENDIF;
# END.
Python: CASE statement
• Python doesn’t support a CASE statement
• But it does have a special form of IF statement that uses ELIF
instead of ELSE.
# PROGRAM BiggerOfThree:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
else:
if b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# ENDIF;
# END.
# PROGRAM BiggerOfThree:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
else:
if b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# ENDIF;
# END.
# PROGRAM BiggerOfThreeElif:
a = int(input(“Please input the first valuen”))
b = int(input(“Please second the second valuen”))
c = int(input(“Please second the third valuen”))
if a > b:
# THEN
if a > c:
# THEN
print(a, “is bigger than”, b, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, c)
# ENDIF;
elif b > c:
# THEN
print(b, “is bigger than”, a, “ and ”, c)
else:
print(c, “is bigger than”, a, “ and ”, b)
# ENDIF;
# END.
Python: IF-ESIF statement
• In Python the general form of the IF-ESIF statement is as follows:
if CONDITION:
STATEMENT(S)
elif CONDITION:
STATEMENT(S)
elif CONDITION:
STATEMENT(S)
else:
STATEMENT(S)
Python: IF-ESIF statement
• But we’ll do:
if CONDITION:
# THEN
STATEMENT(S)
elif CONDITION:
# THEN
STATEMENT(S)
elif CONDITION:
# THEN
STATEMENT(S)
else:
STATEMENT(S)
# ENDIF;
# PROGRAM GetGrade:
InputValue = int(input("Please input the first valuen"))
if InputValue > 70:
# THEN
print("It's a first")
elif InputValue > 60:
# THEN
print("It's a 2.1")
elif InputValue > 50:
# THEN
print("It's a 2.2")
elif InputValue > 40:
# THEN
print("It's a third")
else:
print("Dude, sorry, it's a fail")
# ENDIF;
# END.
# PROGRAM Factorial:
value = int(input("Please input value:"))
total = 1
while value != 0:
# DO
total = total * value
value = value - 1
# ENDWHILE;
print(total)
# END.
Prime Numbers
• So let’s say we want to express the following algorithm:
– Read in a number and check if it’s a prime number.
– What’s a prime number?
– A number that’s only divisible by itself and 1, e.g. 7.
– Or to put it another way, every number other than itself and 1 gives a remainder, e.g. For 7, if 6, 5,
4, 3, and 2 give a remainder then 7 is prime.
– So all we need to do is divide 7 by all numbers less than it but greater than one, and if any of them
have no remainder, we know it’s not prime.
Prime Numbers
• So,
• If the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder,
7 is prime.
• If the number is 9, we know that 8, 7, 6, 5, and 4, all give
remainders, but 3 does not give a remainder, it goes evenly
into 9 so we can say 9 is not prime
Prime Numbers
• So remember,
– if the number is 7, as long as 6, 5, 4, 3, and 2 give a remainder, 7 is
prime.
• So, in general,
– if the number is A, as long as A-1, A-2, A-3, A-4, ... 2 give a remainder,
A is prime.
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
Fibonacci Numbers
• The Fibonacci numbers are numbers where the next number in
the sequence is the sum of the previous two.
• The sequence starts with 1, 1,
• And then it’s 2
• Then 3
• Then 5
• Then 8
• Then 13
# PROGRAM FibonacciNumbers:
a = int(input("Please input value:"))
FirstNum = 1
SecondNum = 1
while a != 1:
# DO
total = SecondNum + FirstNum
FirstNum = SecondNum
SecondNum = total
a = a - 1
# ENDWHILE;
print(total)
# END.
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
#########################
# Prime Checking Module #
#########################
def IsItPrime():
a = int(input("Please input value: "))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
return IsPrime
# END IsItPrime.
#########################
# Prime Checking Module #
#########################
def IsItPrime():
a = int(input("Please input value: "))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
return IsPrime
# END IsItPrime.
################
# Main Program #
################
# PROGRAM CheckPrime:
if IsItPrime() == True:
# THEN
print("Prime number")
else:
print("Not a prime number")
# ENDIF;
# END.
Software Testing
• Software testing is an investigate process to measure
the quality of software.
• Test techniques include, but are not limited to, the
process of executing a program or application with the
intent of finding software bugs.
# PROGRAM CheckPrime:
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
# ENDIF;
b = b - 1
# ENDWHILE;
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
Software Testing
• Let’s add some error checking code in to help use see if
it is working correctly.
# PROGRAM CheckPrime:
##################
# ERROR CHECKING #
##################
c = str(input("Do you want error checking on? (y/n)"))
if c == 'y':
# THEN
MyErrorCheck = True
else:
MyErrorCheck = False
# ENDIF;
##################
# PRIME CHECKING #
##################
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
Part 1 of 3
# PROGRAM CheckPrime:
##################
# ERROR CHECKING #
##################
c = str(input("Do you want error checking on? (y/n)"))
if c == 'y':
# THEN
MyErrorCheck = True
else:
MyErrorCheck = False
# ENDIF;
##################
# PRIME CHECKING #
##################
a = int(input("Please input value:"))
b = a - 1
IsPrime = True
Part 1 of 3
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
if MyErrorCheck == True:
# THEN
print("*** Division with no remainder found, with ", b, "*****”)
# ENDIF;
# ENDIF;
if MyErrorCheck == True:
# THEN
print(">> a is ",a,">> b is ",b, ">> IsPrime is ",IsPrime)
# ENDIF;
b = b - 1
# ENDWHILE;
Part 2 of 3
while b != 1:
# DO
if a % b == 0:
# THEN
IsPrime = False
if MyErrorCheck == True:
# THEN
print("*** Division with no remainder found, with ", b, "*****”)
# ENDIF;
# ENDIF;
if MyErrorCheck == True:
# THEN
print(">> a is ",a,">> b is ",b, ">> IsPrime is ",IsPrime)
# ENDIF;
b = b - 1
# ENDWHILE;
Part 2 of 3
if IsPrime:
# THEN
print(a, "is a prime number")
else:
print(a, "is not a prime number")
# ENDIF;
# END.
Part 3 of 3
# PROGRAM FibonacciNumbers:
a = int(input("Please input value:"))
FirstNum = 1
SecondNum = 1
while a != 1:
# DO
total = SecondNum + FirstNum
FirstNum = SecondNum
SecondNum = total
a = a - 1
# ENDWHILE;
print(total)
# END.
Software Testing
• Let’s add some error checking code in to help use see if
it is working correctly.
# PROGRAM FibonacciNumbers:
##################
# ERROR CHECKING #
##################
c = str(input("Do you want error checking on? (y/n)"))
if c == 'y':
# THEN
MyErrorCheck = True
else:
MyErrorCheck = False
# ENDIF;
Part 1 of 2
# PROGRAM FibonacciNumbers:
##################
# ERROR CHECKING #
##################
c = str(input("Do you want error checking on? (y/n)"))
if c == 'y':
# THEN
MyErrorCheck = True
else:
MyErrorCheck = False
# ENDIF;
Part 1 of 2
a = int(input("Please input value:"))
FirstNum = 1
SecondNum = 1
while a != 1:
# DO
total = SecondNum + FirstNum
if MyErrorCheck == True:
# THEN
print(">> Countdown is ",a)
print(">> First Number is ",FirstNum,">> Second Number is
",SecondNum,">> Total is ",total)
# ENDIF;
FirstNum = SecondNum
SecondNum = total
a = a - 1
# ENDWHILE;
print(total)
# END.
Part 2 of 2
a = int(input("Please input value:"))
FirstNum = 1
SecondNum = 1
while a != 1:
# DO
total = SecondNum + FirstNum
if MyErrorCheck == True:
# THEN
print(">> Countdown is ",a)
print(">> First Number is ",FirstNum,">> Second Number is
",SecondNum,">> Total is ",total)
# ENDIF;
FirstNum = SecondNum
SecondNum = total
a = a - 1
# ENDWHILE;
print(total)
# END.
Part 2 of 2
Arrays
• In Python arrays are sometimes called “lists” or “tuple”
but we’ll stick to the more commonly used term “array”.
• But if you see it called “list” or “tuple” in books or on
the web, they mean an array.
Arrays
• We’ll remember that an array is a collection of the same
type of variables (like a set in maths).
0 1 2 3 4 5 6 397 ……..… 38
44 23 42 33 16 54 34 8218 ……..… 34
Arrays
• To declare an zero-filled array in Python we can do the
following:
Age = [0 for x in range(8)]
Arrays
• To declare an array with values in Python:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
# PROGRAM AverageArray:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
total = 0
for a in range(0,8):
# DO
total = total + Age[a]
# ENDFOR;
AveValue = total/8
print(AveValue)
# END.
# PROGRAM BetterAverageArray:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
total = 0
for a in range(0,len(Age)):
# DO
total = total + Age[a]
# ENDFOR;
AveValue = total/len(Age)
print(AveValue)
# END.
# PROGRAM BetterAverageArray:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
total = 0
for a in range(0,len(Age)):
# DO
total = total + Age[a]
# ENDFOR;
AveValue = total/len(Age)
print(AveValue)
# END.
# PROGRAM BetterAverageArrayReal:
BankBal = [44.44,423.33,545.23,423.3,121.6,32.4,121.4,13.8]
total = 0
for a in range(0,len(BankBal)):
# DO
total = total + BankBal[a]
# ENDFOR;
AveValue = total/len(BankBal)
print(AveValue)
# END.
# PROGRAM SequentialSearch:
Age = [44, 23, 42, 33, 18, 54, 34, 18]
for a in range(0,len(Age)):
# DO
if Age[a] == 18:
# THEN
print("User", a, "is 18")
# ENDIF;
# ENDFOR;
# END.
Searching
• This is a sequential search, we visit each value, that’s OK
for a small array, but for a massive array we might need
to try a different approach.
Searching
• If the data is sorted, we can do a BINARY SEARCH
• This means we jump to the middle of the array, if the
value being searched for is less than the middle value,
all we have to do is search the first half of that array.
• We search the first half of the array in the same way,
jumping to the middle of it, and repeat this.
# PROGRAM BinarySearch:
Age = [16, 18, 23, 31, 33, 34, 46, 54]
SearchVal = int(input("Please input the search value: "))
first = 0
last = len(Age)
IsFound = False
Part 1 of 3
while first <= last and IsFound == False:
# DO
index = (first + last) // 2
if Age[index] == SearchVal:
# THEN
IsFound = True
print("Value found")
elif Age[index] > SearchVal:
# THEN
last = index - 1
else:
first = index + 1
# ENDIF;
# ENDWHILE;
Part 2 of 3
if IsFound == False:
# THEN
print("Value not in array")
# ENDIF;
# END.
Part 3 of 3
Sorting: Bubblesort
• The simplest algorithm for sort an array is called BUBBLE SORT.
• It works as follows for an array of size N:
– Look at the first and second element
• Are they in order?
• If so, do nothing
• If not, swap them around
– Look at the second and third element
• Do the same
– Keep doing this until you get to the end of the array
– Go back to the start again keep doing this whole process for N times.
# PROGRAM Bubblesort:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
for outerindex in range(0,len(Age)):
# DO
for index in range(0,len(Age)-1):
# DO
if Age[index+1] < Age[index]:
# THEN
TempValue = Age[index+1]
Age[index+1] = Age[index]
Age[index] = TempValue
# ENDIF;
# ENDFOR;
# ENDFOR;
print(Age)
# END.
Sorting: Bubblesort
• So each time around the loop the amount of the array
that is sorted is increased, and we don’t have to check
for swaps in the locations that have already been
sorted.
• So we reduce the checking of swaps by one each time
we do a pass of the array.
# PROGRAM BetterBubblesort:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
for outerindex in range(0,len(Age)):
# DO
for index in range(0,reducingindex):
# DO
if Age[index+1] < Age[index]:
# THEN
TempValue = Age[index+1]
Age[index+1] = Age[index]
Age[index] = TempValue
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
# ENDFOR;
print(Age)
# END.
# PROGRAM BetterBubblesort:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
for outerindex in range(0,len(Age)):
# DO
for index in range(0,reducingindex):
# DO
if Age[index+1] < Age[index]:
# THEN
TempValue = Age[index+1]
Age[index+1] = Age[index]
Age[index] = TempValue
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
# ENDFOR;
print(Age)
# END.
Sorting: Bubblesort
• Also, what if the data is already sorted?
• We should check if the program has done no swaps in
one pass, and if t doesn’t that means the data is sorted.
• So even if the data started unsorted, as soon as the data
gets sorted we want to exit the program
for outerindex in range(0,len(Age)):
# DO
for index in range(0,reducingindex):
# DO
if Age[index+1] < Age[index]:
# THEN
TempValue = Age[index+1]
Age[index+1] = Age[index]
Age[index] = TempValue
DidSwap = True
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
if DidSwap == False:
break
# ENDFOR;
print(Age)
# END.
Part 2 of 2
for outerindex in range(0,len(Age)):
# DO
for index in range(0,reducingindex):
# DO
if Age[index+1] < Age[index]:
# THEN
TempValue = Age[index+1]
Age[index+1] = Age[index]
Age[index] = TempValue
DidSwap = True
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
if DidSwap == False:
break
# ENDFOR;
print(Age)
# END.
Part 2 of 2
# PROGRAM BetterBubblesortBooleanModule:
def Swap(a,b):
TempValue = b
b = a
a = TempValue
return a, b
# END Swap
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
DidSwap = False
Part 1 of 2
# PROGRAM BetterBubblesortBooleanModule:
def Swap(a,b):
TempValue = b
b = a
a = TempValue
return a, b
# END Swap
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
DidSwap = False
Part 1 of 2
for outerindex in range(0,len(Age)):
# DO
for index in range(0,reducingindex):
# DO
if Age[index+1] < Age[index]:
# THEN
Age[index],Age[index+1] = Swap(Age[index],Age[index+1])
DidSwap = True
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
if DidSwap == False:
break
# ENDFOR;
print(Age)
# END.
Part 2 of 2
for outerindex in range(0,len(Age)):
# DO
for index in range(0,reducingindex):
# DO
if Age[index+1] < Age[index]:
# THEN
Age[index],Age[index+1] = Swap(Age[index],Age[index+1])
DidSwap = True
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
if DidSwap == False:
break
# ENDFOR;
print(Age)
# END.
Part 2 of 2
Sorting: Selection Sort
• OK, so we’ve seen a way of sorting that easy for the computer,
now let’s look at a ways that’s more natural for a person to
understand.
• It’s called SELECTION SORT.
Sorting: Selection Sort
• It works as follows:
– Find the smallest number, swap it with the value in the first location
of the array
– Find the second smallest number, swap it with the value in the
second location of the array
– Find the third smallest number, swap it with the value in the third
location of the array
– Etc.
# PROGRAM SelectionSort:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
for outerindex in range(0,len(Age)):
# DO
MinValLocation = outerindex
for index in range(outerindex,len(Age)):
# DO
if Age[index] < Age[MinValLocation]:
# THEN
MinValLocation = index
# ENDIF;
# ENDFOR;
if MinValLocation != outerindex:
Age[outerindex], Age[MinValLocation] = Age[MinValLocation],
Age[outerindex]
# ENDFOR;
print(Age)
# END.
# PROGRAM Add1ToMatrix:
Ages = [[2,4,7],[3,6,3]]
for n in range(0,2):
# DO
for m in range(0,3):
# DO
Ages[n][m] = Ages[n][m] + 1
# ENDFOR;
# ENDFOR;
print(Ages)
# END.
# PROGRAM TotalOfMatrix:
Ages = [[2,4,7],[3,6,3]]
print(Ages)
total = 0
for n in range(0,2):
# DO
for m in range(0,3):
# DO
total = total + Ages[n][m]
# ENDFOR;
# ENDFOR;
print("The total value of the matrix is", total)
# END.