Top Banner
Introduction to Python Damian Gordon
224

Introduction to Python programming

Apr 16, 2017

Download

Education

Damian Gordon
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Python programming

Introduction to PythonDamian Gordon

Page 2: Introduction to Python programming

Python: PrintDamian Gordon

Page 3: Introduction to Python programming

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:

Page 4: Introduction to Python programming

print(“Hello, World”)

Page 5: Introduction to Python programming

# PROGRAM HelloWorldProgram:print(“Hello, World”)# END.

Page 6: Introduction to Python programming

# HelloWorldProgram – Version 1# A program to print out “Hello, World”# Written by: Damian Gordon# Date: 10/09/2015 # PROGRAM HelloWorldProgram:print(“Hello, World”)# END.

Page 7: Introduction to Python programming

The PRINT statement

• If we want to add a blank line after our print statement:

Page 8: Introduction to Python programming

# PROGRAM HelloWorldProgram:print(“Hello, World”)# END.

Page 9: Introduction to Python programming

# PROGRAM HelloWorldProgram:print(“Hello, World”)# END.

# PROGRAM HelloWorldProgramNewLine:print(“Hello, World\n”)# END.

Page 10: Introduction to Python programming

The PRINT statement

• To print out two lines of text we do:

Page 11: Introduction to Python programming

# PROGRAM HelloWorldProgramTwoLines:print(“Hello, World”)print(“I’m here”)# END.

Page 12: Introduction to Python programming

The PRINT statement

• To join two strings together:

Page 13: Introduction to Python programming

# PROGRAM HelloWorldProgramJoined:print(“Hello, World” + “ I’m here”)# END.

Page 14: Introduction to Python programming

The PRINT statement

• To print out the same message 10 times:

Page 15: Introduction to Python programming

# PROGRAM HelloWorldProgram10Times:print(“Hello, World” * 10)# END.

Page 16: Introduction to Python programming

The PRINT statement

• To print out the same message 10 times, each one on a new line:

Page 17: Introduction to Python programming

# PROGRAM HelloWorldProgramNewLine10Times:print(“Hello, World\n” * 10)# END.

Page 18: Introduction to Python programming

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

Page 19: Introduction to Python programming

Python: MathsDamian Gordon

Page 20: Introduction to Python programming

Some Simple Maths

• Let’s look at some simple maths first:

Page 21: Introduction to Python programming

# PROGRAM AddingNumbers:print(10 + 7)# END.

Page 22: Introduction to Python programming

Some Simple Maths

• Let’s make that a bit more fancy

Page 23: Introduction to Python programming

# PROGRAM AddingNumbers:print(“10 + 7 = “, 10 + 7)# END.

Page 24: Introduction to Python programming

Some Simple Maths

• Let’s try subtraction:

Page 25: Introduction to Python programming

# PROGRAM SubtractingNumbers:print(“10 - 7 = “, 10 - 7)# END.

Page 26: Introduction to Python programming

Some Simple Maths

• Let’s try multiplication:

Page 27: Introduction to Python programming

# PROGRAM MultiplyingNumbers:print(“10 * 7 = “, 10 * 7)# END.

Page 28: Introduction to Python programming

Some Simple Maths

• Division is a lot cooler, we can do three kinds of division,– Regular Division– Integer Division– Division Remainder

Page 29: Introduction to Python programming

# PROGRAM RegularDivision:print(“10 / 7 = “, 10 / 7)# END.

Page 30: Introduction to Python programming

# PROGRAM RegularDivision:print(“10 / 7 = “, 10 / 7)# END.

This should give us: 1.428571

Page 31: Introduction to Python programming

# PROGRAM IntegerDivision:print(“10 // 7 = “, 10 // 7)# END.

Page 32: Introduction to Python programming

# PROGRAM IntegerDivision:print(“10 // 7 = “, 10 // 7)# END.

This should give us: 1

Page 33: Introduction to Python programming

# PROGRAM IntegerDivision:print(“10 // 7 = “, 10 // 7)# END.

This should give us: 1

which is how many times 7 divides evenly into 10

Page 34: Introduction to Python programming

# PROGRAM DivisionRemainder:print(“10 % 7 = “, 10 % 7)# END.

Page 35: Introduction to Python programming

# PROGRAM DivisionRemainder:print(“10 % 7 = “, 10 % 7)# END.

This should give us: 3

Page 36: Introduction to Python programming

# 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

Page 37: Introduction to Python programming

Some Simple Maths

• Can you work this one out?

Page 38: Introduction to Python programming

# PROGRAM DivisionProblem:print(((10 / 7 – 10 // 7) * 7) + 7)# END.

Page 39: Introduction to Python programming

Python: VariablesDamian Gordon

Page 40: Introduction to Python programming

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!).

Page 41: Introduction to Python programming

# PROGRAM VariableAssignment:x = 6# END.

Page 42: Introduction to Python programming

Using Variables

• And if we want to check the value of the variable:

Page 43: Introduction to Python programming

# PROGRAM VariablePrint:x = 6print(x)# END.

Page 44: Introduction to Python programming

Using Variables

• Let’s add 1 to x:

Page 45: Introduction to Python programming

# PROGRAM AddOneVariablePrint:x = 6print(x + 1)# END.

Page 46: Introduction to Python programming

Using Variables

• Let’s try two variables:

Page 47: Introduction to Python programming

# PROGRAM TwoVariablePrint:x = 6y = 5print(x + y)# END.

Page 48: Introduction to Python programming

Using Variables

• If we want to move from integers to real numbers

Page 49: Introduction to Python programming

# PROGRAM RealVariablePrint:x = 6.56print(x)# END.

Page 50: Introduction to Python programming

# PROGRAM AnotherRealVariablePrint:x = 6.0print(x)# END.

Page 51: Introduction to Python programming

Using Variables

• If we want to create character variables

Page 52: Introduction to Python programming

# PROGRAM CharacterVariablePrint:x = ‘@’print(x)# END.

Page 53: Introduction to Python programming

# PROGRAM AnotherCharacterVariablePrint:x = ‘5’print(x)# END.

Page 54: Introduction to Python programming

Using Variables

• Now we can see that we can’t do arithmetic with characters:

Page 55: Introduction to Python programming

# PROGRAM ErrorProgram:x = ‘5’print(x + 1)# END.

Page 56: Introduction to Python programming

Using Variables

• If we want to create String variables

Page 57: Introduction to Python programming

# PROGRAM StringVariablePrint:x = “This is a string”print(x)# END.

Page 58: Introduction to Python programming

Using Variables

• To get input from the screen, we can do the following:

Page 59: Introduction to Python programming

# PROGRAM PrintMessage:print(“Please input a message: ”)NewMsg = input()print(NewMsg)# END.

Page 60: Introduction to Python programming

Using Variables

• Let’s do the converting temperature program:

Page 61: Introduction to Python programming

# PROGRAM ConvertFromCelsiusToFahrenheit:print(“Please input your temperature in C:”)InputVal = int(input());print(“That temperature in F is:”)print((InputVal *2) + 30)# END.

Page 62: Introduction to Python programming

Convert Description Resultint(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 = 10str(x)

“10”

Page 63: Introduction to Python programming

Using Variables

• The following words cannot be used as variable names:

and del from not whileas elif global or with

assert else if pass yieldbreak except import printclass exec in raise

continue finally is returndef for lambda try

Page 64: Introduction to Python programming

Python: SelectionDamian Gordon

Page 65: Introduction to Python programming

Python: Selection

• We’ll consider two ways to do selection:• The IF statement• The CASE statement

Page 66: Introduction to Python programming

Python: IF statementDamian Gordon

Page 67: Introduction to Python programming

Python: IF statement

• In Python the general form of the IF statement is as follows:

if CONDITION: STATEMENT(S)else: STATEMENT(S)

Page 68: Introduction to Python programming

Python: IF statement

• But we’ll do:

if CONDITION:# THEN STATEMENT(S)else: STATEMENT(S)# ENDIF;

Page 69: Introduction to Python programming

# PROGRAM SimpleIfStatement:x = 6y = 7if x > y:# THEN print(“x is bigger”)else: print(“y is bigger”)# ENDIF;# END.

Page 70: Introduction to Python programming

Python: IF statement

• Let’s get the user to input the values of x and y:

Page 71: Introduction to Python programming

# 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.

Page 72: Introduction to Python programming

Python: IF statement

• Let’s add some PRINT statements to make this clearer:

Page 73: Introduction to Python programming

# 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.

Page 74: Introduction to Python programming

Python: IF statement

• We can make this shorter:

Page 75: Introduction to Python programming

# PROGRAM AnotherSimpleIfStatementPrintsShorter:x = int(input(“Please input the first value\n”))y = int(input(“Please second the second value\n”))if x > y:# THEN print(x, “is bigger than”, y)else: print(y, “is bigger than”, x)# ENDIF;# END.

Page 76: Introduction to Python programming

Python: IF statement

• Lets try the Odd or Even program:

Page 77: Introduction to Python programming

# PROGRAM IsOddOrEven:x = int(input(“Please input the number\n”))if (x % 2) != 0:# THEN print(x, “is odd”)else: print(x, “is even”)# ENDIF;# END.

Page 78: Introduction to Python programming

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

Page 79: Introduction to Python programming

Python: IF statement

• Let’s try the bigger of three numbers:

Page 80: Introduction to Python programming

# PROGRAM BiggerOfThree:a = int(input(“Please input the first value\n”))b = int(input(“Please second the second value\n”))c = int(input(“Please second the third value\n”))

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.

Page 81: Introduction to Python programming

Python: CASE statementDamian Gordon

Page 82: Introduction to Python programming

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.

Page 83: Introduction to Python programming

# PROGRAM BiggerOfThree:a = int(input(“Please input the first value\n”))b = int(input(“Please second the second value\n”))c = int(input(“Please second the third value\n”))

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.

Page 84: Introduction to Python programming

# PROGRAM BiggerOfThree:a = int(input(“Please input the first value\n”))b = int(input(“Please second the second value\n”))c = int(input(“Please second the third value\n”))

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.

Page 85: Introduction to Python programming

# PROGRAM BiggerOfThreeElif:a = int(input(“Please input the first value\n”))b = int(input(“Please second the second value\n”))c = int(input(“Please second the third value\n”))

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.

Page 86: Introduction to Python programming

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)

Page 87: Introduction to Python programming

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;

Page 88: Introduction to Python programming

Python: IF-ESIF statement

• Let’s look at doing a multi-choice question program:

Page 89: Introduction to Python programming

# 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.

Page 90: Introduction to Python programming

Python: IF-ESIF statement

• Here’s how to calculate a grade:

Page 91: Introduction to Python programming

# PROGRAM GetGrade:InputValue = int(input("Please input the first value\n"))

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.

Page 92: Introduction to Python programming

Python: IterationDamian Gordon

Page 93: Introduction to Python programming

Python: Iteration

• We’ll consider four ways to do iteration:– The WHILE loop– The FOR loop– The DO loop– The LOOP loop

Page 94: Introduction to Python programming

Python: WHILE loopDamian Gordon

Page 95: Introduction to Python programming

Python: WHILE loop

• The WHILE loop works as follows:

while CONDITION: STATEMENTS

Page 96: Introduction to Python programming

Python: WHILE loop

• But we’ll do:

while CONDITION:# DO STATEMENTS# ENDWHILE;

Page 97: Introduction to Python programming

Python: WHILE loop

• Let’s print out the numbers 1 to 5:

Page 98: Introduction to Python programming

# PROGRAM Print1To5:a = 1while a != 6:# DO print(a) a = a + 1# ENDWHILE;# END.

Page 99: Introduction to Python programming

Python: WHILE loop

• Let’s print the sum of the numbers 1 to 5:

Page 100: Introduction to Python programming

# PROGRAM Sum1To5:a = 1total = 0while a != 6:# DO total = total + a a = a + 1# ENDWHILE;print(total)# END.

Page 101: Introduction to Python programming

Python: WHILE loop

• Let’s do factorial:

Page 102: Introduction to Python programming

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

Page 103: Introduction to Python programming

# PROGRAM Factorial:value = int(input("Please input value:"))total = 1while value != 0:# DO total = total * value value = value - 1# ENDWHILE;print(total)# END.

Page 104: Introduction to Python programming

Python: FOR loopDamian Gordon

Page 105: Introduction to Python programming

Python: WHILE loop

• The FOR loop works as follows:

for RANGE: STATEMENTS

Page 106: Introduction to Python programming

Python: WHILE loop

• But we’ll do:

for RANGE:# DO STATEMENTS# ENDFOR;

Page 107: Introduction to Python programming

Python: FOR loop

• Let’s remember the program to print out the numbers 1 to 5:

Page 108: Introduction to Python programming

# PROGRAM Print1To5:a = 1while a != 6:# DO print(a) a = a + 1# ENDWHILE;# END.

Page 109: Introduction to Python programming

Python: FOR loop

• We can do it as follows as well:

Page 110: Introduction to Python programming

# PROGRAM Print1To5For:for a in range(1,6):# DO print(a)# ENDFOR;# END.

Page 111: Introduction to Python programming

Python: DO loopDamian Gordon

Page 112: Introduction to Python programming

Python: DO loop

• Python doesn’t implement the DO loop.

Page 113: Introduction to Python programming

Python: DO loop

• But a WHILE loop is OK to do the same thing.

Page 114: Introduction to Python programming

Python: LOOP loopDamian Gordon

Page 115: Introduction to Python programming

Python: LOOP loop

• Python doesn’t implement the LOOP loop.

Page 116: Introduction to Python programming

Python: LOOP loop

• But it does have a BREAK statement, so we can create our own LOOP loop:

Page 117: Introduction to Python programming

Python: LOOP loop

x = 1while x == 1:# DO if CONDITION: # THEN break # ENDIF;# ENDWHILE;

Page 118: Introduction to Python programming

Python: AlgorithmsDamian Gordon

Page 119: Introduction to Python programming

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.

Page 120: Introduction to Python programming

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

Page 121: Introduction to Python programming

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.

Page 122: Introduction to Python programming

# PROGRAM CheckPrime:a = int(input("Please input value:"))b = a - 1IsPrime = Truewhile 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.

Page 123: Introduction to Python programming

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

Page 124: Introduction to Python programming

# PROGRAM FibonacciNumbers:a = int(input("Please input value:"))FirstNum = 1SecondNum = 1while a != 1:# DO total = SecondNum + FirstNum FirstNum = SecondNum SecondNum = total a = a - 1# ENDWHILE;print(total)# END.

Page 125: Introduction to Python programming

Python: ModularisationDamian Gordon

Page 126: Introduction to Python programming

Modularisation

• Remember the prime checker program:

Page 127: Introduction to Python programming

# PROGRAM CheckPrime:a = int(input("Please input value:"))b = a - 1IsPrime = Truewhile 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.

Page 128: Introduction to Python programming

# PROGRAM CheckPrime:a = int(input("Please input value:"))b = a - 1IsPrime = Truewhile 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.

Page 129: Introduction to Python programming

Modularisation

• Let’s break this program into modules (functions).

Page 130: Introduction to Python programming

########################## 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.

Page 131: Introduction to Python programming

########################## 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.

Page 132: Introduction to Python programming

################# Main Program #################

# PROGRAM CheckPrime:

if IsItPrime() == True:# THEN print("Prime number")else: print("Not a prime number")# ENDIF;

# END.

Page 133: Introduction to Python programming

Python: Software TestingDamian Gordon

Page 134: Introduction to Python programming

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.

Page 135: Introduction to Python programming

Software Testing

• Remember the prime checker program:

Page 136: Introduction to Python programming

# PROGRAM CheckPrime:a = int(input("Please input value:"))b = a - 1IsPrime = Truewhile 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.

Page 137: Introduction to Python programming

Software Testing

• Let’s add some error checking code in to help use see if it is working correctly.

Page 138: Introduction to Python programming

# PROGRAM CheckPrime:

################### ERROR CHECKING ###################c = str(input("Do you want error checking on? (y/n)"))if c == 'y':# THEN MyErrorCheck = Trueelse: MyErrorCheck = False# ENDIF;

################### PRIME CHECKING ###################a = int(input("Please input value:"))b = a - 1IsPrime = True

Part 1 of 3

Page 139: Introduction to Python programming

# PROGRAM CheckPrime:

################### ERROR CHECKING ###################c = str(input("Do you want error checking on? (y/n)"))if c == 'y':# THEN MyErrorCheck = Trueelse: MyErrorCheck = False# ENDIF;

################### PRIME CHECKING ###################a = int(input("Please input value:"))b = a - 1IsPrime = True

Part 1 of 3

Page 140: Introduction to Python programming

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

Page 141: Introduction to Python programming

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

Page 142: Introduction to Python programming

if IsPrime:# THEN print(a, "is a prime number")else: print(a, "is not a prime number")# ENDIF;# END.

Part 3 of 3

Page 143: Introduction to Python programming

Software Testing

• And remember the Fibonacci program:

Page 144: Introduction to Python programming

# PROGRAM FibonacciNumbers:a = int(input("Please input value:"))FirstNum = 1SecondNum = 1while a != 1:# DO total = SecondNum + FirstNum FirstNum = SecondNum SecondNum = total a = a - 1# ENDWHILE;print(total)# END.

Page 145: Introduction to Python programming

Software Testing

• Let’s add some error checking code in to help use see if it is working correctly.

Page 146: Introduction to Python programming

# PROGRAM FibonacciNumbers:

################### ERROR CHECKING ###################c = str(input("Do you want error checking on? (y/n)"))if c == 'y':# THEN MyErrorCheck = Trueelse: MyErrorCheck = False# ENDIF;

Part 1 of 2

Page 147: Introduction to Python programming

# PROGRAM FibonacciNumbers:

################### ERROR CHECKING ###################c = str(input("Do you want error checking on? (y/n)"))if c == 'y':# THEN MyErrorCheck = Trueelse: MyErrorCheck = False# ENDIF;

Part 1 of 2

Page 148: Introduction to Python programming

a = int(input("Please input value:"))FirstNum = 1SecondNum = 1while 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

Page 149: Introduction to Python programming

a = int(input("Please input value:"))FirstNum = 1SecondNum = 1while 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

Page 150: Introduction to Python programming

Python: ArraysDamian Gordon

Page 151: Introduction to Python programming

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.

Page 152: Introduction to Python programming

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 ……..… 38Age

44 23 42 33 16 54 34 8218 ……..… 34Age

Page 153: Introduction to Python programming

Arrays

• To declare an zero-filled array in Python we can do the following:

Age = [0 for x in range(8)]

Page 154: Introduction to Python programming

Arrays

• To declare an array with values in Python:

Age = [44, 23, 42, 33, 16, 54, 34, 18]

Page 155: Introduction to Python programming

Arrays

• To see the first value:

print(Age[0])

Page 156: Introduction to Python programming

Arrays

• To see the first value:

print(Age[0])

44

Page 157: Introduction to Python programming

Arrays

• To see the second value:

print(Age[1])

Page 158: Introduction to Python programming

Arrays

• To see the second value:

print(Age[1])

23

Page 159: Introduction to Python programming

Arrays

• To see the last value:

print(Age[7])

Page 160: Introduction to Python programming

Arrays

• To see the last value:

print(Age[7])

18

Page 161: Introduction to Python programming

Arrays

• To print out all the values in the array:

Page 162: Introduction to Python programming

# PROGRAM SampleArrayProg:

Age = [44, 23, 42, 33, 16, 54, 34, 18]

for a in range(0,8):# DO print(Age[a])# ENDFOR;# END.

Page 163: Introduction to Python programming

Arrays

• To make that print out a bit nicer:

Page 164: Introduction to Python programming

# 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.

Page 165: Introduction to Python programming

Arrays

• Because Python is so cool, I can also just do the following:

print(Age)

Page 166: Introduction to Python programming

Arrays

• Let’s add 1 to each value in the array

Page 167: Introduction to Python programming

# 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.

Page 168: Introduction to Python programming

Arrays

• Let’s get the average value of the array

Page 169: Introduction to Python programming

# PROGRAM AverageArray:

Age = [44, 23, 42, 33, 16, 54, 34, 18]total = 0for a in range(0,8):# DO total = total + Age[a]# ENDFOR;AveValue = total/8print(AveValue)# END.

Page 170: Introduction to Python programming

Arrays

• Let’s make that better:

Page 171: Introduction to Python programming

# PROGRAM BetterAverageArray:

Age = [44, 23, 42, 33, 16, 54, 34, 18]total = 0for a in range(0,len(Age)):# DO total = total + Age[a]# ENDFOR;AveValue = total/len(Age)print(AveValue)# END.

Page 172: Introduction to Python programming

# PROGRAM BetterAverageArray:

Age = [44, 23, 42, 33, 16, 54, 34, 18]total = 0for a in range(0,len(Age)):# DO total = total + Age[a]# ENDFOR;AveValue = total/len(Age)print(AveValue)# END.

Page 173: Introduction to Python programming

Arrays

• To declare an array of real numbers, it’s very similar:

Page 174: Introduction to Python programming

# PROGRAM BetterAverageArrayReal:

BankBal = [44.44,423.33,545.23,423.3,121.6,32.4,121.4,13.8]total = 0for a in range(0,len(BankBal)):# DO total = total + BankBal[a]# ENDFOR;AveValue = total/len(BankBal)print(AveValue)# END.

Page 175: Introduction to Python programming

Arrays

• To declare an array of characters, it’s very similar:

Page 176: Introduction to Python programming

# PROGRAM BetterAverageArrayChar:

letters = ['d','g','e','s','b','j','r','j']

for a in range(0,len(letters)):# DO print(letters[a])# ENDFOR;# END.

Page 177: Introduction to Python programming

Arrays

• And the same for strings:

Page 178: Introduction to Python programming

# PROGRAM BetterAverageArrayString:

Pets = ["dog","cat","fish","cat","dog","fish","cat","dog"]

for a in range(0,len(Pets)):# DO print(Pets[a])# ENDFOR;# END.

Page 179: Introduction to Python programming

Arrays

• Here’s an array of Booleans:

Page 180: Introduction to Python programming

# PROGRAM BetterAverageArrayBoolean:

IsWeekend = [False, False, False, False, False, True, True]

for a in range(0,len(IsWeekend)):# DO print(IsWeekend[a])# ENDFOR;# END.

Page 181: Introduction to Python programming

Python: SearchingDamian Gordon

Page 182: Introduction to Python programming

Searching

• To search for everyone who is 18 in an integer array:

Page 183: Introduction to Python programming

# 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.

Page 184: Introduction to Python programming

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.

Page 185: Introduction to Python programming

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.

Page 186: Introduction to Python programming

# PROGRAM BinarySearch:

Age = [16, 18, 23, 31, 33, 34, 46, 54]SearchVal = int(input("Please input the search value: "))

first = 0last = len(Age)IsFound = False

Part 1 of 3

Page 187: Introduction to Python programming

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

Page 188: Introduction to Python programming

if IsFound == False: # THEN print("Value not in array")# ENDIF;# END.

Part 3 of 3

Page 189: Introduction to Python programming

Python: Sorting - Bubblesort Damian Gordon

Page 190: Introduction to Python programming

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.

Page 191: Introduction to Python programming

# 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.

Page 192: Introduction to Python programming

Sorting: Bubblesort

• The bubble sort pushes the largest values up to the top of the array.

Page 193: Introduction to Python programming

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.

Page 194: Introduction to Python programming

# PROGRAM BetterBubblesort:Age = [44, 23, 42, 33, 18, 54, 34, 16]reducingindex = len(Age)-1for 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.

Page 195: Introduction to Python programming

# PROGRAM BetterBubblesort:Age = [44, 23, 42, 33, 18, 54, 34, 16]reducingindex = len(Age)-1for 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.

Page 196: Introduction to Python programming

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

Page 197: Introduction to Python programming

# PROGRAM BetterBubblesortBoolean:

Age = [44, 23, 42, 33, 18, 54, 34, 16]reducingindex = len(Age)-1DidSwap = False

Part 1 of 2

Page 198: Introduction to Python programming

# PROGRAM BetterBubblesortBoolean:

Age = [44, 23, 42, 33, 18, 54, 34, 16]reducingindex = len(Age)-1DidSwap = False

Part 1 of 2

Page 199: Introduction to Python programming

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

Page 200: Introduction to Python programming

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

Page 201: Introduction to Python programming

Sorting: Bubblesort

• The Swap function is very useful so we should have that as a module as follows:

Page 202: Introduction to Python programming

# 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)-1DidSwap = False

Part 1 of 2

Page 203: Introduction to Python programming

# 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)-1DidSwap = False

Part 1 of 2

Page 204: Introduction to Python programming

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

Page 205: Introduction to Python programming

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

Page 206: Introduction to Python programming

Sorting: Bubblesort

• Python is such a neat language it allows a much easier swap, you can say:

a, b = b, a

Page 207: Introduction to Python programming

Sorting: Bubblesort

• or:

Age[index],Age[index+1] = Age[index+1],Age[index]

Page 208: Introduction to Python programming

# PROGRAM BetterBubblesortBooleanSwap:Age = [44, 23, 42, 33, 18, 54, 34, 16]reducingindex = len(Age)-1DidSwap = Falsefor 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.

Page 209: Introduction to Python programming

# PROGRAM BetterBubblesortBooleanSwap:Age = [44, 23, 42, 33, 18, 54, 34, 16]reducingindex = len(Age)-1DidSwap = Falsefor 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.

Page 210: Introduction to Python programming

Python: Sorting – Selection Sort

Damian Gordon

Page 211: Introduction to Python programming

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.

Page 212: Introduction to Python programming

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.

Page 213: Introduction to Python programming

# 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.

Page 214: Introduction to Python programming

Python: Multi-dimensional Arrays

Damian Gordon

Page 215: Introduction to Python programming

Multi-dimensional Arrays

• We declare a multi-dimensional array as follows:

Ages = [[0 for x in range(8)] for x in range(8)]

Page 216: Introduction to Python programming

Multi-dimensional Arrays

• Or like this:

Ages = [[2,6,3],[7,5,9]]

Page 217: Introduction to Python programming

Multi-dimensional Arrays

• To print out the whole array, I can say:

print(Ages)

Page 218: Introduction to Python programming

Multi-dimensional Arrays

• To print out the first value in the array:

print(Ages[0][0])

Page 219: Introduction to Python programming

Multi-dimensional Arrays

• To assign a new value to the first element in the array:

Ages[0][0] = 34

Page 220: Introduction to Python programming

Multi-dimensional Arrays

• If we wanted to add 1 to each cell:

Page 221: Introduction to Python programming

# 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.

Page 222: Introduction to Python programming

Multi-dimensional Arrays

• If we want to add up all the values in the array:

Page 223: Introduction to Python programming

# 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.

Page 224: Introduction to Python programming

etc.