Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
Introduction to Python
Damian Gordon
Python: Print
Damian Gordon
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:
print(“Hello, World”)
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
# HelloWorldProgram – Version 1
# A program to print out “Hello, World”
# Written by: Damian Gordon
# Date: 10/09/2015
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
The PRINT statement
• If we want to add a blank line after our print statement:
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
# PROGRAM HelloWorldProgram:
print(“Hello, World”)
# END.
# PROGRAM HelloWorldProgramNewLine:
print(“Hello, Worldn”)
# END.
The PRINT statement
• To print out two lines of text we do:
# PROGRAM HelloWorldProgramTwoLines:
print(“Hello, World”)
print(“I’m here”)
# END.
The PRINT statement
• To join two strings together:
# PROGRAM HelloWorldProgramJoined:
print(“Hello, World” + “ I’m here”)
# END.
The PRINT statement
• To print out the same message 10 times:
# PROGRAM HelloWorldProgram10Times:
print(“Hello, World” * 10)
# END.
The PRINT statement
• To print out the same message 10 times, each one on a new
line:
# PROGRAM HelloWorldProgramNewLine10Times:
print(“Hello, Worldn” * 10)
# END.
Code Description
 Print a backslash
’ Print a single quote
” Print a double quote
a Play a beep
n Print a new line
t Print a tab
Python: Maths
Damian Gordon
Some Simple Maths
• Let’s look at some simple maths first:
# PROGRAM AddingNumbers:
print(10 + 7)
# END.
Some Simple Maths
• Let’s make that a bit more fancy
# PROGRAM AddingNumbers:
print(“10 + 7 = “, 10 + 7)
# END.
Some Simple Maths
• Let’s try subtraction:
# PROGRAM SubtractingNumbers:
print(“10 - 7 = “, 10 - 7)
# END.
Some Simple Maths
• Let’s try multiplication:
# PROGRAM MultiplyingNumbers:
print(“10 * 7 = “, 10 * 7)
# END.
Some Simple Maths
• Division is a lot cooler, we can do three kinds of division,
– Regular Division
– Integer Division
– Division Remainder
# PROGRAM RegularDivision:
print(“10 / 7 = “, 10 / 7)
# END.
# PROGRAM RegularDivision:
print(“10 / 7 = “, 10 / 7)
# END.
This should give us:
1.428571
# PROGRAM IntegerDivision:
print(“10 // 7 = “, 10 // 7)
# END.
# PROGRAM IntegerDivision:
print(“10 // 7 = “, 10 // 7)
# END.
This should give us:
1
# PROGRAM IntegerDivision:
print(“10 // 7 = “, 10 // 7)
# END.
This should give us:
1
which is how many times
7 divides evenly into 10
# PROGRAM DivisionRemainder:
print(“10 % 7 = “, 10 % 7)
# END.
# PROGRAM DivisionRemainder:
print(“10 % 7 = “, 10 % 7)
# END.
This should give us:
3
# PROGRAM DivisionRemainder:
print(“10 % 7 = “, 10 % 7)
# END.
This should give us:
3
which is what is left over
when we divide 7 into 10
Some Simple Maths
• Can you work this one out?
# PROGRAM DivisionProblem:
print(((10 / 7 – 10 // 7) * 7) + 7)
# END.
Python: Variables
Damian Gordon
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!).
# PROGRAM VariableAssignment:
x = 6
# END.
Using Variables
• And if we want to check the value of the variable:
# PROGRAM VariablePrint:
x = 6
print(x)
# END.
Using Variables
• Let’s add 1 to x:
# PROGRAM AddOneVariablePrint:
x = 6
print(x + 1)
# END.
Using Variables
• Let’s try two variables:
# PROGRAM TwoVariablePrint:
x = 6
y = 5
print(x + y)
# END.
Using Variables
• If we want to move from integers to real numbers
# PROGRAM RealVariablePrint:
x = 6.56
print(x)
# END.
# PROGRAM AnotherRealVariablePrint:
x = 6.0
print(x)
# END.
Using Variables
• If we want to create character variables
# PROGRAM CharacterVariablePrint:
x = ‘@’
print(x)
# END.
# PROGRAM AnotherCharacterVariablePrint:
x = ‘5’
print(x)
# END.
Using Variables
• Now we can see that we can’t do arithmetic with characters:
# PROGRAM ErrorProgram:
x = ‘5’
print(x + 1)
# END.
Using Variables
• If we want to create String variables
# PROGRAM StringVariablePrint:
x = “This is a string”
print(x)
# END.
Using Variables
• To get input from the screen, we can do the following:
# PROGRAM PrintMessage:
print(“Please input a message: ”)
NewMsg = input()
print(NewMsg)
# END.
Using Variables
• Let’s do the converting temperature program:
# PROGRAM ConvertFromCelsiusToFahrenheit:
print(“Please input your temperature in C:”)
InputVal = int(input());
print(“That temperature in F is:”)
print((InputVal *2) + 30)
# END.
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
Python: Selection
Damian Gordon
Python: Selection
• We’ll consider two ways to do selection:
• The IF statement
• The CASE statement
Python: IF statement
Damian Gordon
Python: IF statement
• In Python the general form of the IF statement is as follows:
if CONDITION:
STATEMENT(S)
else:
STATEMENT(S)
Python: IF statement
• But we’ll do:
if CONDITION:
# THEN
STATEMENT(S)
else:
STATEMENT(S)
# ENDIF;
# PROGRAM SimpleIfStatement:
x = 6
y = 7
if x > y:
# THEN
print(“x is bigger”)
else:
print(“y is bigger”)
# ENDIF;
# END.
Python: IF statement
• Let’s get the user to input the values of x and y:
# 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.
Python: IF statement
• Let’s add some PRINT statements to make this clearer:
# 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.
Python: IF statement
• We can make this shorter:
# 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.
Python: IF statement
• Lets try the Odd or Even program:
# PROGRAM IsOddOrEven:
x = int(input(“Please input the numbern”))
if (x % 2) != 0:
# THEN
print(x, “is odd”)
else:
print(x, “is even”)
# ENDIF;
# END.
Operator Description
!= is not equal to
== is equal to
> is greater than
< is less than
>= is greater than or equal to
<= is less than or equal to
Python: IF statement
• Let’s try the bigger of three numbers:
# 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
Damian Gordon
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;
Python: IF-ESIF statement
• Let’s look at doing a multi-choice question program:
# PROGRAM MultiChoiceQuestion:
InputValue = input("Please input your answer:n")
if InputValue == "a":
# THEN
print("Wrong Answer")
elif InputValue == "b":
# THEN
print("Wrong Answer")
elif InputValue == "c":
# THEN
print("Right Answer")
elif InputValue == "d":
# THEN
print("Wrong Answer")
else:
print("Bad Option")
# ENDIF;
# END.
Python: IF-ESIF statement
• Here’s how to calculate a grade:
# 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.
Python: Iteration
Damian Gordon
Python: Iteration
• We’ll consider four ways to do iteration:
– The WHILE loop
– The FOR loop
– The DO loop
– The LOOP loop
Python: WHILE loop
Damian Gordon
Python: WHILE loop
• The WHILE loop works as follows:
while CONDITION:
STATEMENTS
Python: WHILE loop
• But we’ll do:
while CONDITION:
# DO
STATEMENTS
# ENDWHILE;
Python: WHILE loop
• Let’s print out the numbers 1 to 5:
# PROGRAM Print1To5:
a = 1
while a != 6:
# DO
print(a)
a = a + 1
# ENDWHILE;
# END.
Python: WHILE loop
• Let’s print the sum of the numbers 1 to 5:
# PROGRAM Sum1To5:
a = 1
total = 0
while a != 6:
# DO
total = total + a
a = a + 1
# ENDWHILE;
print(total)
# END.
Python: WHILE loop
• Let’s do factorial:
Python: WHILE loop
• Let’s do factorial:
– Remember:
– 5! = 5*4*3*2*1
– 7! = 7*6 *5*4*3*2*1
– N! = N*(N-1)*(N-2)*…*2*1
# PROGRAM Factorial:
value = int(input("Please input value:"))
total = 1
while value != 0:
# DO
total = total * value
value = value - 1
# ENDWHILE;
print(total)
# END.
Python: FOR loop
Damian Gordon
Python: WHILE loop
• The FOR loop works as follows:
for RANGE:
STATEMENTS
Python: WHILE loop
• But we’ll do:
for RANGE:
# DO
STATEMENTS
# ENDFOR;
Python: FOR loop
• Let’s remember the program to print out the numbers 1 to 5:
# PROGRAM Print1To5:
a = 1
while a != 6:
# DO
print(a)
a = a + 1
# ENDWHILE;
# END.
Python: FOR loop
• We can do it as follows as well:
# PROGRAM Print1To5For:
for a in range(1,6):
# DO
print(a)
# ENDFOR;
# END.
Python: DO loop
Damian Gordon
Python: DO loop
• Python doesn’t implement the DO loop.

Python: DO loop
• But a WHILE loop is OK to do the same thing.
Python: LOOP loop
Damian Gordon
Python: LOOP loop
• Python doesn’t implement the LOOP loop.

Python: LOOP loop
• But it does have a BREAK statement, so we can create our own
LOOP loop:
Python: LOOP loop
x = 1
while x == 1:
# DO
if CONDITION:
# THEN
break
# ENDIF;
# ENDWHILE;
Python: Algorithms
Damian Gordon
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.
Python: Modularisation
Damian Gordon
Modularisation
• Remember the prime checker program:
# 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.
Modularisation
• Let’s break this program into modules (functions).
#########################
# 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.
Python: Software Testing
Damian Gordon
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.
Software Testing
• Remember the prime checker program:
# 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
Software Testing
• And remember the Fibonacci program:
# 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
Python: Arrays
Damian Gordon
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]
Arrays
• To see the first value:
print(Age[0])
Arrays
• To see the first value:
print(Age[0])
44
Arrays
• To see the second value:
print(Age[1])
Arrays
• To see the second value:
print(Age[1])
23
Arrays
• To see the last value:
print(Age[7])
Arrays
• To see the last value:
print(Age[7])
18
Arrays
• To print out all the values in the array:
# PROGRAM SampleArrayProg:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
for a in range(0,8):
# DO
print(Age[a])
# ENDFOR;
# END.
Arrays
• To make that print out a bit nicer:
# PROGRAM SampleArrayProg:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
for a in range(0,8):
# DO
print("Age[",a,"] =", Age[a])
# ENDFOR;
# END.
Arrays
• Because Python is so cool, I can also just do the
following:
print(Age)
Arrays
• Let’s add 1 to each value in the array
# PROGRAM Add1ToArray:
Age = [44, 23, 42, 33, 16, 54, 34, 18]
for a in range(0,8):
# DO
print(Age)
Age[a] = Age[a] + 1
# ENDFOR;
print(Age)
# END.
Arrays
• Let’s get the average value of the array
# 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.
Arrays
• Let’s make that better:
# 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.
Arrays
• To declare an array of real numbers, it’s very similar:
# 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.
Arrays
• To declare an array of characters, it’s very similar:
# PROGRAM BetterAverageArrayChar:
letters = ['d','g','e','s','b','j','r','j']
for a in range(0,len(letters)):
# DO
print(letters[a])
# ENDFOR;
# END.
Arrays
• And the same for strings:
# PROGRAM BetterAverageArrayString:
Pets = ["dog","cat","fish","cat","dog","fish","cat","dog"]
for a in range(0,len(Pets)):
# DO
print(Pets[a])
# ENDFOR;
# END.
Arrays
• Here’s an array of Booleans:
# PROGRAM BetterAverageArrayBoolean:
IsWeekend = [False, False, False, False, False, True, True]
for a in range(0,len(IsWeekend)):
# DO
print(IsWeekend[a])
# ENDFOR;
# END.
Python: Searching
Damian Gordon
Searching
• To search for everyone who is 18 in an integer array:
# 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
Python: Sorting - Bubblesort
Damian Gordon
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
• The bubble sort pushes the largest values up to the top of the
array.
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
# PROGRAM BetterBubblesortBoolean:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
DidSwap = False
Part 1 of 2
# PROGRAM BetterBubblesortBoolean:
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
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
Sorting: Bubblesort
• The Swap function is very useful so we should have that
as a module as follows:
# 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: Bubblesort
• Python is such a neat language it allows a much easier
swap, you can say:
a, b = b, a
Sorting: Bubblesort
• or:
Age[index],Age[index+1] = Age[index+1],Age[index]
# PROGRAM BetterBubblesortBooleanSwap:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
DidSwap = False
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] = Age[index+1],Age[index]
DidSwap = True
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
if DidSwap == False:
break
# ENDFOR;
print(Age)
# END.
# PROGRAM BetterBubblesortBooleanSwap:
Age = [44, 23, 42, 33, 18, 54, 34, 16]
reducingindex = len(Age)-1
DidSwap = False
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] = Age[index+1],Age[index]
DidSwap = True
# ENDIF;
# ENDFOR;
reducingindex = reducingindex - 1
if DidSwap == False:
break
# ENDFOR;
print(Age)
# END.
Python: Sorting – Selection Sort
Damian Gordon
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.
Python: Multi-dimensional Arrays
Damian Gordon
Multi-dimensional Arrays
• We declare a multi-dimensional array as follows:
Ages = [[0 for x in range(8)] for x in range(8)]
Multi-dimensional Arrays
• Or like this:
Ages = [[2,6,3],[7,5,9]]
Multi-dimensional Arrays
• To print out the whole array, I can say:
print(Ages)
Multi-dimensional Arrays
• To print out the first value in the array:
print(Ages[0][0])
Multi-dimensional Arrays
• To assign a new value to the first element in the array:
Ages[0][0] = 34
Multi-dimensional Arrays
• If we wanted to add 1 to each cell:
# 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.
Multi-dimensional Arrays
• If we want to add up all the values in the array:
# 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.
etc.

More Related Content

Introduction to Python programming