Publicité
Publicité

Contenu connexe

Publicité
Publicité

Introduction to Python programming

  1. Introduction to Python Damian Gordon
  2. Python: Print Damian Gordon
  3. 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:
  4. print(“Hello, World”)
  5. # PROGRAM HelloWorldProgram: print(“Hello, World”) # END.
  6. # HelloWorldProgram – Version 1 # A program to print out “Hello, World” # Written by: Damian Gordon # Date: 10/09/2015 # PROGRAM HelloWorldProgram: print(“Hello, World”) # END.
  7. The PRINT statement • If we want to add a blank line after our print statement:
  8. # PROGRAM HelloWorldProgram: print(“Hello, World”) # END.
  9. # PROGRAM HelloWorldProgram: print(“Hello, World”) # END. # PROGRAM HelloWorldProgramNewLine: print(“Hello, Worldn”) # END.
  10. The PRINT statement • To print out two lines of text we do:
  11. # PROGRAM HelloWorldProgramTwoLines: print(“Hello, World”) print(“I’m here”) # END.
  12. The PRINT statement • To join two strings together:
  13. # PROGRAM HelloWorldProgramJoined: print(“Hello, World” + “ I’m here”) # END.
  14. The PRINT statement • To print out the same message 10 times:
  15. # PROGRAM HelloWorldProgram10Times: print(“Hello, World” * 10) # END.
  16. The PRINT statement • To print out the same message 10 times, each one on a new line:
  17. # PROGRAM HelloWorldProgramNewLine10Times: print(“Hello, Worldn” * 10) # END.
  18. 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
  19. Python: Maths Damian Gordon
  20. Some Simple Maths • Let’s look at some simple maths first:
  21. # PROGRAM AddingNumbers: print(10 + 7) # END.
  22. Some Simple Maths • Let’s make that a bit more fancy
  23. # PROGRAM AddingNumbers: print(“10 + 7 = “, 10 + 7) # END.
  24. Some Simple Maths • Let’s try subtraction:
  25. # PROGRAM SubtractingNumbers: print(“10 - 7 = “, 10 - 7) # END.
  26. Some Simple Maths • Let’s try multiplication:
  27. # PROGRAM MultiplyingNumbers: print(“10 * 7 = “, 10 * 7) # END.
  28. Some Simple Maths • Division is a lot cooler, we can do three kinds of division, – Regular Division – Integer Division – Division Remainder
  29. # PROGRAM RegularDivision: print(“10 / 7 = “, 10 / 7) # END.
  30. # PROGRAM RegularDivision: print(“10 / 7 = “, 10 / 7) # END. This should give us: 1.428571
  31. # PROGRAM IntegerDivision: print(“10 // 7 = “, 10 // 7) # END.
  32. # PROGRAM IntegerDivision: print(“10 // 7 = “, 10 // 7) # END. This should give us: 1
  33. # PROGRAM IntegerDivision: print(“10 // 7 = “, 10 // 7) # END. This should give us: 1 which is how many times 7 divides evenly into 10
  34. # PROGRAM DivisionRemainder: print(“10 % 7 = “, 10 % 7) # END.
  35. # PROGRAM DivisionRemainder: print(“10 % 7 = “, 10 % 7) # END. This should give us: 3
  36. # 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
  37. Some Simple Maths • Can you work this one out?
  38. # PROGRAM DivisionProblem: print(((10 / 7 – 10 // 7) * 7) + 7) # END.
  39. Python: Variables Damian Gordon
  40. 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!).
  41. # PROGRAM VariableAssignment: x = 6 # END.
  42. Using Variables • And if we want to check the value of the variable:
  43. # PROGRAM VariablePrint: x = 6 print(x) # END.
  44. Using Variables • Let’s add 1 to x:
  45. # PROGRAM AddOneVariablePrint: x = 6 print(x + 1) # END.
  46. Using Variables • Let’s try two variables:
  47. # PROGRAM TwoVariablePrint: x = 6 y = 5 print(x + y) # END.
  48. Using Variables • If we want to move from integers to real numbers
  49. # PROGRAM RealVariablePrint: x = 6.56 print(x) # END.
  50. # PROGRAM AnotherRealVariablePrint: x = 6.0 print(x) # END.
  51. Using Variables • If we want to create character variables
  52. # PROGRAM CharacterVariablePrint: x = ‘@’ print(x) # END.
  53. # PROGRAM AnotherCharacterVariablePrint: x = ‘5’ print(x) # END.
  54. Using Variables • Now we can see that we can’t do arithmetic with characters:
  55. # PROGRAM ErrorProgram: x = ‘5’ print(x + 1) # END.
  56. Using Variables • If we want to create String variables
  57. # PROGRAM StringVariablePrint: x = “This is a string” print(x) # END.
  58. Using Variables • To get input from the screen, we can do the following:
  59. # PROGRAM PrintMessage: print(“Please input a message: ”) NewMsg = input() print(NewMsg) # END.
  60. Using Variables • Let’s do the converting temperature program:
  61. # PROGRAM ConvertFromCelsiusToFahrenheit: print(“Please input your temperature in C:”) InputVal = int(input()); print(“That temperature in F is:”) print((InputVal *2) + 30) # END.
  62. 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”
  63. 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
  64. Python: Selection Damian Gordon
  65. Python: Selection • We’ll consider two ways to do selection: • The IF statement • The CASE statement
  66. Python: IF statement Damian Gordon
  67. Python: IF statement • In Python the general form of the IF statement is as follows: if CONDITION: STATEMENT(S) else: STATEMENT(S)
  68. Python: IF statement • But we’ll do: if CONDITION: # THEN STATEMENT(S) else: STATEMENT(S) # ENDIF;
  69. # PROGRAM SimpleIfStatement: x = 6 y = 7 if x > y: # THEN print(“x is bigger”) else: print(“y is bigger”) # ENDIF; # END.
  70. Python: IF statement • Let’s get the user to input the values of x and y:
  71. # 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.
  72. Python: IF statement • Let’s add some PRINT statements to make this clearer:
  73. # 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.
  74. Python: IF statement • We can make this shorter:
  75. # 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.
  76. Python: IF statement • Lets try the Odd or Even program:
  77. # 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.
  78. 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
  79. Python: IF statement • Let’s try the bigger of three numbers:
  80. # 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.
  81. Python: CASE statement Damian Gordon
  82. 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.
  83. # 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.
  84. # 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.
  85. # 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.
  86. 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)
  87. 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;
  88. Python: IF-ESIF statement • Let’s look at doing a multi-choice question program:
  89. # 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.
  90. Python: IF-ESIF statement • Here’s how to calculate a grade:
  91. # 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.
  92. Python: Iteration Damian Gordon
  93. Python: Iteration • We’ll consider four ways to do iteration: – The WHILE loop – The FOR loop – The DO loop – The LOOP loop
  94. Python: WHILE loop Damian Gordon
  95. Python: WHILE loop • The WHILE loop works as follows: while CONDITION: STATEMENTS
  96. Python: WHILE loop • But we’ll do: while CONDITION: # DO STATEMENTS # ENDWHILE;
  97. Python: WHILE loop • Let’s print out the numbers 1 to 5:
  98. # PROGRAM Print1To5: a = 1 while a != 6: # DO print(a) a = a + 1 # ENDWHILE; # END.
  99. Python: WHILE loop • Let’s print the sum of the numbers 1 to 5:
  100. # PROGRAM Sum1To5: a = 1 total = 0 while a != 6: # DO total = total + a a = a + 1 # ENDWHILE; print(total) # END.
  101. Python: WHILE loop • Let’s do factorial:
  102. 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
  103. # PROGRAM Factorial: value = int(input("Please input value:")) total = 1 while value != 0: # DO total = total * value value = value - 1 # ENDWHILE; print(total) # END.
  104. Python: FOR loop Damian Gordon
  105. Python: WHILE loop • The FOR loop works as follows: for RANGE: STATEMENTS
  106. Python: WHILE loop • But we’ll do: for RANGE: # DO STATEMENTS # ENDFOR;
  107. Python: FOR loop • Let’s remember the program to print out the numbers 1 to 5:
  108. # PROGRAM Print1To5: a = 1 while a != 6: # DO print(a) a = a + 1 # ENDWHILE; # END.
  109. Python: FOR loop • We can do it as follows as well:
  110. # PROGRAM Print1To5For: for a in range(1,6): # DO print(a) # ENDFOR; # END.
  111. Python: DO loop Damian Gordon
  112. Python: DO loop • Python doesn’t implement the DO loop. 
  113. Python: DO loop • But a WHILE loop is OK to do the same thing.
  114. Python: LOOP loop Damian Gordon
  115. Python: LOOP loop • Python doesn’t implement the LOOP loop. 
  116. Python: LOOP loop • But it does have a BREAK statement, so we can create our own LOOP loop:
  117. Python: LOOP loop x = 1 while x == 1: # DO if CONDITION: # THEN break # ENDIF; # ENDWHILE;
  118. Python: Algorithms Damian Gordon
  119. 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.
  120. 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
  121. 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.
  122. # 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.
  123. 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
  124. # 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.
  125. Python: Modularisation Damian Gordon
  126. Modularisation • Remember the prime checker program:
  127. # 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.
  128. # 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.
  129. Modularisation • Let’s break this program into modules (functions).
  130. ######################### # 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.
  131. ######################### # 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.
  132. ################ # Main Program # ################ # PROGRAM CheckPrime: if IsItPrime() == True: # THEN print("Prime number") else: print("Not a prime number") # ENDIF; # END.
  133. Python: Software Testing Damian Gordon
  134. 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.
  135. Software Testing • Remember the prime checker program:
  136. # 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.
  137. Software Testing • Let’s add some error checking code in to help use see if it is working correctly.
  138. # 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
  139. # 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
  140. 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
  141. 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
  142. if IsPrime: # THEN print(a, "is a prime number") else: print(a, "is not a prime number") # ENDIF; # END. Part 3 of 3
  143. Software Testing • And remember the Fibonacci program:
  144. # 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.
  145. Software Testing • Let’s add some error checking code in to help use see if it is working correctly.
  146. # 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
  147. # 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
  148. 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
  149. 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
  150. Python: Arrays Damian Gordon
  151. 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.
  152. 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
  153. Arrays • To declare an zero-filled array in Python we can do the following: Age = [0 for x in range(8)]
  154. Arrays • To declare an array with values in Python: Age = [44, 23, 42, 33, 16, 54, 34, 18]
  155. Arrays • To see the first value: print(Age[0])
  156. Arrays • To see the first value: print(Age[0]) 44
  157. Arrays • To see the second value: print(Age[1])
  158. Arrays • To see the second value: print(Age[1]) 23
  159. Arrays • To see the last value: print(Age[7])
  160. Arrays • To see the last value: print(Age[7]) 18
  161. Arrays • To print out all the values in the array:
  162. # PROGRAM SampleArrayProg: Age = [44, 23, 42, 33, 16, 54, 34, 18] for a in range(0,8): # DO print(Age[a]) # ENDFOR; # END.
  163. Arrays • To make that print out a bit nicer:
  164. # 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.
  165. Arrays • Because Python is so cool, I can also just do the following: print(Age)
  166. Arrays • Let’s add 1 to each value in the array
  167. # 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.
  168. Arrays • Let’s get the average value of the array
  169. # 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.
  170. Arrays • Let’s make that better:
  171. # 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.
  172. # 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.
  173. Arrays • To declare an array of real numbers, it’s very similar:
  174. # 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.
  175. Arrays • To declare an array of characters, it’s very similar:
  176. # PROGRAM BetterAverageArrayChar: letters = ['d','g','e','s','b','j','r','j'] for a in range(0,len(letters)): # DO print(letters[a]) # ENDFOR; # END.
  177. Arrays • And the same for strings:
  178. # PROGRAM BetterAverageArrayString: Pets = ["dog","cat","fish","cat","dog","fish","cat","dog"] for a in range(0,len(Pets)): # DO print(Pets[a]) # ENDFOR; # END.
  179. Arrays • Here’s an array of Booleans:
  180. # PROGRAM BetterAverageArrayBoolean: IsWeekend = [False, False, False, False, False, True, True] for a in range(0,len(IsWeekend)): # DO print(IsWeekend[a]) # ENDFOR; # END.
  181. Python: Searching Damian Gordon
  182. Searching • To search for everyone who is 18 in an integer array:
  183. # 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.
  184. 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.
  185. 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.
  186. # 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
  187. 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
  188. if IsFound == False: # THEN print("Value not in array") # ENDIF; # END. Part 3 of 3
  189. Python: Sorting - Bubblesort Damian Gordon
  190. 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.
  191. # 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.
  192. Sorting: Bubblesort • The bubble sort pushes the largest values up to the top of the array.
  193. 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.
  194. # 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.
  195. # 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.
  196. 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
  197. # PROGRAM BetterBubblesortBoolean: Age = [44, 23, 42, 33, 18, 54, 34, 16] reducingindex = len(Age)-1 DidSwap = False Part 1 of 2
  198. # PROGRAM BetterBubblesortBoolean: Age = [44, 23, 42, 33, 18, 54, 34, 16] reducingindex = len(Age)-1 DidSwap = False Part 1 of 2
  199. 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
  200. 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
  201. Sorting: Bubblesort • The Swap function is very useful so we should have that as a module as follows:
  202. # 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
  203. # 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
  204. 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
  205. 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
  206. Sorting: Bubblesort • Python is such a neat language it allows a much easier swap, you can say: a, b = b, a
  207. Sorting: Bubblesort • or: Age[index],Age[index+1] = Age[index+1],Age[index]
  208. # 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.
  209. # 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.
  210. Python: Sorting – Selection Sort Damian Gordon
  211. 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.
  212. 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.
  213. # 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.
  214. Python: Multi-dimensional Arrays Damian Gordon
  215. Multi-dimensional Arrays • We declare a multi-dimensional array as follows: Ages = [[0 for x in range(8)] for x in range(8)]
  216. Multi-dimensional Arrays • Or like this: Ages = [[2,6,3],[7,5,9]]
  217. Multi-dimensional Arrays • To print out the whole array, I can say: print(Ages)
  218. Multi-dimensional Arrays • To print out the first value in the array: print(Ages[0][0])
  219. Multi-dimensional Arrays • To assign a new value to the first element in the array: Ages[0][0] = 34
  220. Multi-dimensional Arrays • If we wanted to add 1 to each cell:
  221. # 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.
  222. Multi-dimensional Arrays • If we want to add up all the values in the array:
  223. # 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.
  224. etc.
Publicité