1 of 385

Programming technique workbook.�Part 3

Name:

Class:

Created by Mr Suffar

2 of 385

Revisit phase – Starter

Created by Mr Suffar

3 of 385

  • Use random number generator to solve problems.
  • Use different programming constructs with random number generator.
  • Solve real world problems using random number generator.

Random numbers

Lesson 16

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

4 of 385

RANDOM NUMBERS

When working with random numbers in python, the first thing that you need to do is type the following line at the top of your program:

To display a random number between 1 and 100 INCLUSIVE, use this code :

import random

import random

num = random.randint(1,100)

print(num)

Created by Mr Suffar

5 of 385

RANDOM NUMBERS

The following code will store 2 random numbers then multiplies them by each other.

Created by Mr Suffar

6 of 385

RANDOM NUMBERS

The following code display the SAME random number 5 times. This is because the random number is generated outside the loop.

Created by Mr Suffar

7 of 385

RANDOM NUMBERS

The following code display the 5 DIFFERENT random numbers.

Created by Mr Suffar

8 of 385

Theory:

Watch the video: https://youtu.be/Og_mi14cxMA

Created by Mr Suffar

9 of 385

Tasks

Complete the tasks

Created by Mr Suffar

10 of 385

348. Copy the code below, run it and test it, then explain the purpose of the program/what the program does.

Explain the purpose of the code below:

import random

for x in range(1,11):

result = random.randint(0, 1)

if result == 0:

print("Coin "+str(x)+" landed on Heads")

else:

print("Coin "+str(x)+" landed on Tails")

Answer:

Created by Mr Suffar

11 of 385

349. The program below must: generate a random number and display it on the screen. For each random number generated, you must also ask the user to enter a separate number and display it. Multiply the two numbers together and add them to a total. Repeat the above 5 times. Display the total at the end.

Copy the code below, run it and fix the errors.

import random

total 0

for x in range(5)

num1= random.randinteger(1,100)

while True:

num2 = intinput("Enter a number between 1 and 100"))

if num2 >=1 and num2 <= 100

break

else:

print(TRY AGAIN, NOT BETWEEN 1 AND 100")

print("Num1:",num1)

print("Num2:",num)

total = total + (num1*num2

print(total)

Paste the correct version below:

Created by Mr Suffar

12 of 385

350. Create a program that:

Generate a random number and add it to a total that starts from 0 and display the total.

Repeat the above until the total is 1000 or above.

import random

total = ___

while _____ < 1000:

num = _____._____(1,100)

total = _____ + _____

print("Total is:",_____)

Copy the code above, fill the gaps then paste your code below:

Created by Mr Suffar

13 of 385

351.

  • Store a random number from 1 to 100 in variable called “num1” using random.randint.
  • Display the random number THEN
  • Ask the user for a number between 1 to 10 and store it in another variable called num2.
  • Calculate the average of the 2 numbers.
  • Display the average.

Paste your code below:

Created by Mr Suffar

14 of 385

352. Create a program that:

  • Picks a random number between 1 and 3 and stores it in a variable
  • Asks the user to enter a number
  • Tells the user whether they got the same as the random number
  • If yes, say “Well done!”
  • If no, say “You did not get the number”

Paste your code below:

Created by Mr Suffar

15 of 385

353.

  • Generate a random number between 1 and 1000.
  • Ask the user if they want to see the random number.
  • If the answer is yes, display the random number.
  • If the answer is “no”, display “ game over” and end the game.
  • Display “Wrong option” for any other choices.
  • The game repeats until the user enters “no”.

Paste your code below:

Created by Mr Suffar

16 of 385

354.

  • Generate a random number between 1-5.
  • Ask the user to guess the number.
  • if the guess is correct, display “correct” and add a point to a score variable.
  • If the guess is incorrect, display “incorrect” and take a point a way.
  • Then ask the user if they want to play again.
  • The game will repeat until the user enters “no”.

Paste your code below:

Created by Mr Suffar

17 of 385

355. Create a program that:

  • Picks a random number between 1 and 3 and stores it in a variable
  • Asks the user to enter a number
  • Tells the user whether they got the same as the random number
  • If yes, say “Well done!” and then display how many attempts it took them to get it right.
  • If no, say “You did not get the number” then display how many attempts they had so far.
  • If they did not get it right, generate a new random number and start the process again.

Paste your code below:

Created by Mr Suffar

18 of 385

356. Create a program that :

  • Generates 10 random numbers. All of the random numbers must be between 1 and 100.
  • Display each random number.
  • Then display whether the number is even or odd.

Paste your code below:

Created by Mr Suffar

19 of 385

357. Create a program with the following criteria:

  • Create a total variable and set it to 0.
  • Store a random number between 1 and 100 in a variable using random.randint(1,100).
  • Ask the user to enter a number.
  • Multiply the 2 numbers together and then add them to the total.
  • Display the total.
  • Repeat the process 5 times.

Paste your code below:

Created by Mr Suffar

20 of 385

358.

  • Store 2 random numbers (between 1 and 10) in 2 different variables.
  • Ask the user to work out the answer when these two numbers are multiplied by each other.
  • Display whether the answer as right or wrong.
  • The above process must repeat 5 times.

Paste your code below:

Created by Mr Suffar

21 of 385

359. Create a program that:

  • Generates and displays 6 random numbers between 1 and 1000 using a For loop.
  • Then displays the highest number and the lowest number generated in a full sentence.

Paste your code below:

Created by Mr Suffar

22 of 385

360. Create a guessing game.

  • Store a random number between 1 and 100 in a variable using random.randint(1,100).
  • Ask the user to guess it.
  • Display a “too high”, “too low” or “Correct” depending on the guess.
  • Repeat the question until they guess correctly.

Paste your code below:

Created by Mr Suffar

23 of 385

361. Create a program that generates a random number between 1 and 10 inclusive.

Repeatedly ask the user to guess it until the user guesses correctly.

After each guess display whether they guessed correctly or not.

Paste your code below:

Created by Mr Suffar

24 of 385

362. Create a program that:

  • Generate a random number between 1-2.
  • Ask the user to guess the number.
  • if the guess is correct, display “correct” and add a point to a score variable.
  • If the guess is incorrect, display “incorrect” and take a point a way.
  • The game will repeats 5 times.
  • Display “You Won” if the user has 1 or more points.
  • Display you have lost if the user has a negative score.
  • Display “DRAW” if the user has a score of 0 after the 10 tries.

Paste your code below:

Created by Mr Suffar

25 of 385

363. Create a program that:

  • Asks the user for a number between 1 and 100 and store it in a variable called “usernum”
  • Validate that the number entered is between 1 and 100, if not repeat the question.
  • Generates a random number between 1 and 100 and store in a variable called “newnum”
  • Display the random number.
  • If usernum is greater than newnum, then add both numbers to a total that starts from 0.
  • Repeat the above 10 times using a count controlled loop.
  • Calculate and display the highest and lowest number entered by the user (usernum).
  • Display the total.

Paste your code below:

Created by Mr Suffar

26 of 385

Homework: Watch the video:

https://youtu.be/ZfQ5XM7i7gk

Created by Mr Suffar

27 of 385

Revisit phase – Starter

What are the 3 different programming constructs? Give an example of each.

  • Sequence
  • Iteration
  • Selection

Created by Mr Suffar

28 of 385

Revisit phase – Starter

Which programming construct was used in the above program?

  • Sequence

Created by Mr Suffar

29 of 385

Revisit phase – Starter

Which programming construct was used in the above program?

  • Iteration (Count controlled iteration)

Created by Mr Suffar

30 of 385

Revisit phase – Starter

Which programming construct was used in the above program?

  • Sequence (line 1) & Selection

Created by Mr Suffar

31 of 385

  • Describe the purpose of an array.
  • Create a program using arrays.
  • Explain the difference between arrays and records.

Arrays

Lesson 16

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

32 of 385

Created by Mr Suffar

33 of 385

Arrays

Variable: Location in memory that stores a value which can be changed. A variable can only store 1 Value.

Array: A data structure that stores MULTIPLE data under one identifier. All of the data in the array MUST be of the same data type.

names

0

1

2

3

Tom

Sam

Ron

Chi

Array name

Index number

(Starts from 0)

Contents of the array (Data type string)

Created by Mr Suffar

34 of 385

Arrays

Advantages of using array?

  • Allows multiple items of data to be stored under 1 identifier.

  • Reduce the need for multiple variables.

Created by Mr Suffar

35 of 385

List / record

List / record: A data structure that stores multiple data. Data can be of MULTIPLE data types.

Name

Price

Biscuit

2.5

Crisps

1.5

This table can be stored in a list, however it can’t be stored in an array as it contains multiple data types

Created by Mr Suffar

36 of 385

How to create an array

numbers = [5,4,8,3,6,1,4]

Identifier

Square brackets

Values separated by a comma

Created by Mr Suffar

37 of 385

Arrays & Variables

Which one is easier to read and more efficient?

Using variables:

number1 = 5

number2 = 4

number3 = 8

number4 = 3

number5 = 6

number6 = 1

number7 = 4

Using array:

numbers = [5,4,8,3,6,1,4]

Created by Mr Suffar

38 of 385

Arrays

Array index starts from 0.

What do you think the following code will display?

print(names[0])

  • Rom

print(names[2])

  • Sam

names = ["Rom","Ash","Sam","Ali","Mark"]

Quotation marks are needed around strings but not around integers.

Created by Mr Suffar

39 of 385

Arrays

Array index starts from 0.

What do you think the following code will display?

print(len(names))

  • 5

print(names[len(names)])

  • Error – index out of range as we don’t have index 5

names = ["Rom","Ash","Sam","Ali","Mark"]

Created by Mr Suffar

40 of 385

Arrays

Array index starts from 0.

What do you think the following code will display?

print(names[len(names)-1])

  • Mark

names = ["Rom","Ash","Sam","Ali","Mark"]

Created by Mr Suffar

41 of 385

Cold call

Created by Mr Suffar

42 of 385

Tasks

Complete tasks

Created by Mr Suffar

43 of 385

364. Copy the code below, run it and test it, then explain the purpose of the program/what the program does.

Explain the purpose of the code below:

games = ["Rainbow Siege","Crash","Rocket League"]

index = int(input("Enter index number"))

if index >=0 and index<=2:

print(games[index])

else:

print("Index out of range")

Answer:

Created by Mr Suffar

44 of 385

365. The program below must: Create an array with 3 games, display the first game in the array, display the number of items in the array, display the last game in the array.

Copy the code below, run it and fix the errors.

Created by Mr Suffar

45 of 385

366. Create a program that: Creates an array that contains 4 different colours. Ask the user if they want to see the first or last colour in the array. Display the first or last colour 10 times depending on the user’s answer.

colours = ["Red","Black","Blue","Pink"]

choice = ____("first or last colour")

if ____ == "____":

for ___ in ____(10):

____(____[0])

else:

for x in ____(10):

____(colours[3])

Copy the code above, fill the gaps then paste your code below:

Created by Mr Suffar

46 of 385

367)

  • Create an array called films and store your top 3 films in it.
  • Display your array.
  • Then display the first film in the array on a separate line.
  • Then display the last film in the array on a separate line.

Paste your code below:

Created by Mr Suffar

47 of 385

368) Create an array called numbers and store 5 numbers in the array. Display the 2nd number in the array.

Paste your code below:

Created by Mr Suffar

48 of 385

369)

  • Create an array called names and store 3 names inside it.
  • Ask the user which index number do they want to see. If the user picks a number that is outside the index range (above 2) then repeat the question again until a valid number is entered.
  • Display the item on that index number.

Paste your code below:

Created by Mr Suffar

49 of 385

Slicing

array = [2,3,4,5]

print(array[0:2]) #displays index 0 & 1 print(array[0:3]) #prints index 0 & 1&2

print(array[1:3]) #prints index 1&2

Created by Mr Suffar

50 of 385

RANDOM CHOICE

random.choice can be used to select a random item from an array.

The code above will display either rock, paper or scissor.

import random

selection = random.choice ( ["Rock","Paper","Scissor"])

print(selection)

Created by Mr Suffar

51 of 385

Displaying items in an array

This will display all items in an array. However, this method of displaying all items in an array is not efficient especially if you have many items in an array.

films = ["Saw","Sharks","Lion King"]

King"]

print(films[0])

print(films[1])

print(films[2])

Created by Mr Suffar

52 of 385

Looping through an array

You can use a FOR LOOP to loop through an array.

This makes your code more efficient.

The following code will display all of the contents of the array on separate lines:

films = ["Saw","Sharks","Lion King"]

for x in range(0,3):

print(films[x])

Created by Mr Suffar

53 of 385

Lets see how it works in a trace table:

x

Output

films = ["Saw", "Sharks", "Lion king"]

for x in range(0,3):

print(films[x])

0

Saw

1

Sharks

2

Lion King

Created by Mr Suffar

54 of 385

Arrays

What will the following code display?

films = ["Saw","Sharks","Lion King"]

print(len(films))

  • 3

Created by Mr Suffar

55 of 385

Arrays

You can use a FOR LOOP to loop through an array.

You can use len(films) if you are unsure how many items there are in the array.

The following code will display all of the contents in the array on separate lines:

Created by Mr Suffar

56 of 385

Arrays

Below is another way to display the contents of the array.

pets = ['dog', 'Cat', 'Hamster', 'Fish']

for names in pets:

print(names)

Created by Mr Suffar

57 of 385

Adding data to an empty array.

Adding data to an empty array.

Created by Mr Suffar

58 of 385

Tasks

Complete the tasks

Created by Mr Suffar

59 of 385

370. Create an array called singers that contains the following singers: "Rihanna","Katy","Adele","Ed"

Use 3 print commands to:

  • Display the first singer in the array
  • Then display the first 3 singers in the array.
  • Then display the last singer in the array

Paste your code below:

Created by Mr Suffar

60 of 385

371.

  • Create an array called games and store the following games inside it: "OW","CSGO","FIFA","FORTNITE"
  • Use a FOR LOOP to loop through the array and display all 4 games on separate lines.

Paste your code below:

Created by Mr Suffar

61 of 385

372. Create an array called singers that contains the name of 4 teachers in your school.

Use 3 print commands to:

  • Display the first teacher in the array
  • Then display the first 3 singers in the array.
  • Display the length of the array using the len() function.

Paste your code below:

Created by Mr Suffar

62 of 385

373. The following array called games is empty: games = ["","","","",""]

Use the above array to create a program that uses a count controlled loop to ask for the name of 5 games. Add each game to the array. Display the array.

Paste your code below:

Created by Mr Suffar

63 of 385

374. numbers = [5,2,78,8,2,5,9,4,22,66,11,88,77,38,266,12,1]

Create a program that loops through the array above and calculates and displays the following:

  • The total (sum) of the numbers in the array
  • The average of the numbers in the array then
  • display each of the above in a full sentence.

Paste your code below:

Created by Mr Suffar

64 of 385

375. In python:

  • Create an array called athletes and store the name of 4 athletes inside it.
  • Use a FOR LOOP to loop through the array and display all 4 athlete names on separate lines.

Paste your code below:

Created by Mr Suffar

65 of 385

376. In Monster Wonderland game, a player is able to move to the next by receiving an item at random. The user can either receive a “key” which will open a door. A “Sword” which help the user move through the dungeon, and a “Rope” to climb with.

  • Create a program that will uses random.choice to select at random either “key,sword or rope” and store it in a variable called “selection”.
  • If key is selected, display “Key is selected” then “door is open”
  • If sword is selected, display “Sword is selected” then “bad luck, you will run into monsters”.
  • If rope is selected, display “Rope is selected” then “You will need to climb”

Paste your code below:

Created by Mr Suffar

66 of 385

377. The following array called numbers is empty: numbers = ["","","","","",""]

Use the array above to create a program that uses a count controlled loop to ask for 6 numbers. Add each number to the array. Display the array.

Paste your code below:

Created by Mr Suffar

67 of 385

378. Create a program that counts and displays how many even numbers are found in the following array:

numbers = [5,24,62,425,46,33,42,56,2423,32]

Paste your code below:

Created by Mr Suffar

68 of 385

379. In python:

  • Using the array below, calculate the total of all the odd numbers in the array.

numbers = [5,2,5,7,4,65,7,3,3,5,6,3]

Paste your code below:

Created by Mr Suffar

69 of 385

380. Create a program that doubles each number in the array and stores it back in the array.

For example the following area:

  • numbers = [5,24,63,42]
  • Should be displayed as: [10,48,126,84]
  • Use the array above in your program.

Paste your code below:

Created by Mr Suffar

70 of 385

381. numbers = [52,42,42,543,63467,457,6545,2]

Create a program that loops through the array above and calculates and displays the following:

  • The lowest number in the array.
  • The highest number in the array.
  • display each of the above in a full sentence.

Paste your code below:

Created by Mr Suffar

71 of 385

382. numbers = [700000,500000,2222233,1145555,22222276,4277777,7000000]

The array above shows the number of people vaccinated against Covid19 from day 1 to day 7 where index 0 represents day 1.

Create an algorithm that:

  • Loops the array to find the day which had the highest number of people vaccinated against COVID19.
  • Displays the number of vaccines given on that day and then displays whether it’s day 1,2,3,4,5,6 or 7.

Paste your code below:

Created by Mr Suffar

72 of 385

383. The array films contain some film names.

  • films = ["Dead pool","Saw","Lion King","Fast and furious","Bleach","Naruto"]
  • Create a program that checks the length of each film name then display the film with the highest number of characters and the film with the least number of characters in a full sentence.

Paste your code below:

Created by Mr Suffar

73 of 385

384. The array numbers contain 10 numbers, 5 of them are odd, 5 of them are even. Using the arrays below, create a program that takes all the odd numbers from the array numbers and puts it in the odd array and takes all the even numbers from the numbers array and puts it in the even array then display the even and odd arrays.

  • numbers = [5,2,7,6,4,5,8,7,9,10]

Paste your code below:

numbers = [5,2,7,6,4,5,8,7,9,10]

odd = ["","","","",""]

even = ["","","","",""]

Created by Mr Suffar

74 of 385

385. goals = [0,4,2,3,1,5,2,3,6,0,3,1,0,2,3,0,3,0,1,2,3]

The above array shows the number of goals scored in each match by Aston Villa.

Create a program that loops through the array above and calculates and displays the following:

  • The number of matches where 0 goals were scored.
  • The number of matches where 3 or more goals were scored.
  • Display both of the above in a full sentence.

Paste your code below:

Created by Mr Suffar

75 of 385

Homework: Watch the video:

https://youtu.be/Ghocrd6KDw0

Created by Mr Suffar

76 of 385

Starter – Revisit phase

What will the following code display?

Answer:

  • Error

What type of error is it?

  • Syntax error

s missing

Created by Mr Suffar

77 of 385

  • Complete trace tables.
  • Solve real life problems using arrays.
  • Use iteration to loop through an array.

Arrays & trace table

Lesson 17

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

78 of 385

Created by Mr Suffar

79 of 385

Trace table – Class demonstration:

x

Output

names = ["Tom", "Mark", "Sam"]

for x in range(0,len(films)):

print(names[x])

0

Tom

1

Mark

2

Sam

Created by Mr Suffar

80 of 385

Trace table – Class demonstration:

x

letter

Output

0

x

z

0

zy

1

y

yy

2

x

z

2

zy

Created by Mr Suffar

81 of 385

Tasks

Complete tasks

Created by Mr Suffar

82 of 385

386. Complete the trace table

new

x

num

Created by Mr Suffar

83 of 385

387. Complete the trace table – Assume the user enters the following as inputs: Metallica, Idles

band

name

Output

Created by Mr Suffar

84 of 385

388. Complete the trace table

highest

lowest

num

item

Created by Mr Suffar

85 of 385

389. Complete the trace table – Assume the user enters 5,2,8,1,4 as inputs

total

num

number

item

Created by Mr Suffar

86 of 385

The code below asks the user to enter a name, if the name is inside the array, it will display Found.

Created by Mr Suffar

87 of 385

The code below asks the user to enter a name, if the name is inside the array, it will display Found, otherwise it will display “not found”.

Created by Mr Suffar

88 of 385

The code below will loop through the array. If any part of the array is empty, it will ask for a name, then adds that name to that part.

Created by Mr Suffar

89 of 385

390.

  • Create the following array: numbers = [2,3,4,5,6,7,90]
  • Ask the user to guess a number.
  • If the number is inside the array, display “found”.

Paste your code below:

Created by Mr Suffar

90 of 385

391. A teacher wants to add his pupil names to an array. His class has 10 students. He created the array, however some names are missing.

The array has been created:

students = ["Tom","","Andy","","Lisa","","","","","Abodi"]

Create an algorithm that:

  • Checks each index in the array for a name, if it has a name, move on to the next index, if it doesn’t, then ask the user for a name and add it to that index.
  • Once all 10 names have been added to the array, display the array.

Paste your code below:

Created by Mr Suffar

91 of 385

392. A survey on favourite pets has been completed. The results are stored in an array called pets.

pets = ["Cat","Dog","Cat","Cat","Cat","Cat","Dog"]

Use the array above to create an algorithm that:

Calculates and outputs how many votes Cat received.

Calculates and outputs how many votes Dog received.

Calculates the number of votes.

Paste your code below:

Created by Mr Suffar

92 of 385

393. Mr Suffar created an array of his favourite 6 games.

The array has been created:

students = [“CSGO",“Overwatch","",“FIFA","",""]

Create an algorithm that:

  • Checks each index in the array for a game name, if it has a game name, display the game name and then move on to the next index, if it doesn’t, then ask the user for a game name and add it to that index.
  • Display the whole array when all empty indexes are filled with games.

Paste your code below:

Created by Mr Suffar

93 of 385

394. numbers = [5,2,78,8,2,5,9,4,22,66,11,88,77,38,266,12,1]

Create a program that loops through the array above and calculates and displays the following:

  • The lowest number in the array
  • The highest number in the array
  • The total (sum) of the numbers in the array
  • The average of the numbers in the array then
  • display each of the above in a full sentence.

Paste your code below:

Created by Mr Suffar

94 of 385

395.

names = ["Ted","Arin","Mark","Son","Jim","Lilly"]

Create an algorithm that:

  • Asks the user to pick a name
  • If the name is inside the array, display, "name found" then display the index of that name.
  • Use the following array: names = ["Ted","Arin","Mark","Son","Jim","Lilly"]
  • Display "Name not found" if the name is not in the array.
  • The process is repeated until the user enters a name that is inside the array.

Paste your code below:

Created by Mr Suffar

95 of 385

396. Martin is creating an algorithm to calculate how many birds he fed in the park. Add the array to your code:

birds = ["Robin","Pigeon","Starling"]

Create an algorithm that:

  • Asks the user if they fed any birds.
  • If the answer is yes, ask them for the name of the bird.
  • If the name of the bird is inside the array birds, then ask the user how many of that bird did they feed.
  • Calculate and display the total number of birds that have been fed.
  • The process repeats as long as the user enters “yes” when asked if they fed any birds.

Paste your code below:

Created by Mr Suffar

96 of 385

397. array = [66,67,68,88,77,76,89,78]

Convert each number in the above array to its ASCII letter using “chr()” then display the word on the screen in a full sentence.

Paste your code below:

Created by Mr Suffar

97 of 385

398. A phone number is stored in the array below.

phonenumber = [0,7,9,1,2,3,4,5,6,7,8]

Create a program that extracts each number from the phonenumber array and add it to a variable of string data type. Then display the variable in a full sentence.

Paste your code below:

Created by Mr Suffar

98 of 385

399. Convert the array below to a string.

Convert the following array to a single string then display it on the screen, make the code is efficient by using a count controlled loop:

array = ["H","e","l","l","o"]

Paste your code below:

Created by Mr Suffar

99 of 385

400. Convert (cast) all the values in the array to a string then display the new array on the screen.

For example: array = [2,5,"A","B"]

should be displayed as ["2","5","A","B"]

Paste your code below:

Created by Mr Suffar

100 of 385

401. Create a program that rotates the array values clockwise by 1. Stores it in an array called array2 and then display the content of array2 on the screen. For example: the array array = [5,3,7,8,2,1] can be rotated by 1 to allow array2 to be display as [1, 5, 3, 7, 8, 2].

Create an algorithm to solve the above problem using the arrays below.

array = [5,3,7,8,2,1]

array2 = ["","","","","",""]

Paste your code below:

Created by Mr Suffar

101 of 385

Homework: Watch the video:

https://youtu.be/in2-sWY2eHg

Created by Mr Suffar

102 of 385

  • Understand the difference between arrays & lists.
  • Solve real life problems using lists.
  • Use iteration to loop through a list.

Arrays & lists

Lesson 18

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

103 of 385

Created by Mr Suffar

104 of 385

Arrays

An arrays is a data structure which can store multiple values, however all of the data must be of the same data type.

Arrays are static data structures meaning it can not GROW or SHRINK.

Created by Mr Suffar

105 of 385

Arrays & Lists

  • A list is also a data structure that stores multiple values, under 1 identifier.

  • However the data can be of DIFFERENT data types.

  • A list can grow and shrink.

  • The way you create a list in python is exactly the same as an array using [ ]

However if it grows or shrinks while the program is running, it means it’s a list.

Created by Mr Suffar

106 of 385

Lists

#Creates an empty list/array called numbers.

numbers = [ ]

#Loops 4 times.

for x in range(4):

#Ask the user for a number

num = int(input("Enter a number"))

#Adds the number to the end of the list.

numbers.append(num)

#Displays the list

print(numbers)

Append means adding something to the end.

Created by Mr Suffar

107 of 385

Lists

Empty list

Adds the name to the end of the list

Created by Mr Suffar

108 of 385

Tasks

Complete task

Created by Mr Suffar

109 of 385

402. Write a program that asks the user to enter the name of 4 games and store these within an list (array). Display the list (array).

Paste your code below:

Created by Mr Suffar

110 of 385

403.

  • Create an empty list (array)
  • Ask the user to enter 4 numbers
  • Store them in the list (array).
  • Display the list (array).

Paste your code below:

Created by Mr Suffar

111 of 385

404.

  • Create an empty list (array)
  • Ask the user to add 6 numbers to the list (array) using a for loop.
  • Display the first number in the list (array)
  • On a separate line display the 4th number in the list (array)
  • Calculate & display the AVERAGE of the numbers inside the list.

Paste your code below:

Created by Mr Suffar

112 of 385

405.

  • Liverpool = [55,65,75,65,78,45,76,66,98,102]
  • ManCity = [52,61,85,75,68,65,96,86,99,85]
  • The above 2 arrays shows the points earned by 2 teams at the end of each season over 10 years.

Write an algorithm that:

  • Adds together all the number in each array (Liverpool and ManCity) and store them in separate variables.
  • Displays the total points earned by each team over 10 years.
  • Then displays which team has the highest number of points over 10 years or whether they have the same number of points.

Paste your code below:

Created by Mr Suffar

113 of 385

406. A teacher wants to store student names in a list. He wants 2 separate lists, 1 for males and 1 for females. Create a program that:

  • Ask the user how many students are in his class.
  • Asks for the name of each student.
  • Ask if the student is male or female.
  • Stores the names of the students in a list, male students in a list called male and female students in a list called female.
  • Displays both lists at the end of the program.

Paste your code below:

Created by Mr Suffar

114 of 385

407)

  • Ask the user to enter 6 numbers and store them in a list (array).
  • Ask the user if they want to see the total (sum) or the average of the 6 numbers.
  • Loop through the list to calculate the sum of the numbers.
  • Display the answer depending on the user’s choice.

Paste your code below:

Created by Mr Suffar

115 of 385

Sorting

array = [1,7,2,5,6]

array.sort()

print(array)

array.reverse()

print(array)

Sorts the list in number/alphabetical order.

Sorts the list in reverse order.

Created by Mr Suffar

116 of 385

408.

  • Create an empty list (array).
  • Ask the user to enter 3 games and store it in an list (array).
  • Sort the list (array) in alphabetical order.
  • Display the list (array)
  • Then ask the user which index number in the list (array) do they want to see.
  • Display the value of that index number.

Paste your code below:

Created by Mr Suffar

117 of 385

409.

  • Create an empty list.
  • Ask the user to enter 5 numbers and store them in the list.
  • Sort the list in order then display the list.
  • Then Reverse the order of the list then display the new list in reverse order.

Paste your code below:

Created by Mr Suffar

118 of 385

Remove() function

names = ["Tom","Sam","Ash","Mel"]

print(names)

names.remove(names[0])

print(names)

Remove() function is used to remove specific items in the array. In this case, index 0 is removed from the array.

Created by Mr Suffar

119 of 385

Remove() function

names = ["Tom","Sam","Ash","Mel"]

print(names)

choice = input("enter name to remove")

names.remove(choice)

print(names)

Removes the name that the user picks, if the user types Sam, then Sam will be removed.

Created by Mr Suffar

120 of 385

Pop() function

names = ["Tom","Sam","Ash","Mel"]

names.pop(0)

print(names)

print(names.pop(0))

print(names)

Removes index 0 from the array

Removes index 0 from the array and also displays the value removed. “Sam”

Created by Mr Suffar

121 of 385

Difference between remove() and pop()

The remove() method removes the first matching element from the array.

  • array.remove("Bassim") #Removes Bassim from the array

The pop() method removes an element at a given index, and will also return the removed item.

  • array.pop(0) #Removes index 0 from the array
  • print(array.pop(2)) #Removes index 2 from the array and also displays it

Created by Mr Suffar

122 of 385

410.

  • Create an empty list (array).
  • Ask the user to input the name of 4 films and store them in a list (array).
  • Display the first 2 films in the list.
  • Remove the last film in the list hint: use
  • Display the list

Paste your code below:

Created by Mr Suffar

123 of 385

411. Create the following array: numbers = [5,5,2,52,6,7645,234,4,6,30]

  • Create a program that loops infinitely. The program must:
  • Ask the user whether they want to pop from the stack (remove the last item of the array) or
  • Push to the stack (Append an item to the end of the array) or
  • Display the array
  • Add appropriate validation methods to ensure the program does not crash. E.G you can’t pop (remove last item from the array) if the stack is empty and you can’t push (Add to the end of an array) if the stack is full.
  • The array (stack) must have a maximum of 10 items.

Paste your code below:

Created by Mr Suffar

124 of 385

412)

  • Ask the user to enter the name of 3 singers, stores them in an array.
  • Sort the array in alphabetical order
  • then display each singer in the array on a separate line with their position.

Paste your code below:

Created by Mr Suffar

125 of 385

413.

  • Generate 5 random numbers between 1 and 100.
  • Displays each random number.
  • Store the numbers in an array (list).
  • Sort the array (list) in order.
  • Display the array.

Paste your code below:

Created by Mr Suffar

126 of 385

414.

  • Ask the user how many numbers they want to generate.
  • Ask the user for the lowest and highest number they want to generate.
  • Display each number generated.
  • Store the numbers in a array (list).
  • Display the list.

Paste your code below:

Created by Mr Suffar

127 of 385

415.

  • Create an empty list (array).
  • Repeatedly ask the user for a number until the user enters 0 or a negative number.
  • Append each number to the list (array).
  • Calculate and display the amount of numbers the user entered.
  • Calculates and display the total and average of the numbers.

Paste your code below:

Created by Mr Suffar

128 of 385

Task 416

Answer:

Created by Mr Suffar

129 of 385

Task 417

?

?

?

Created by Mr Suffar

130 of 385

Task 418

Answer:

Created by Mr Suffar

131 of 385

Task 419

Answer:

Created by Mr Suffar

132 of 385

Task 420

Answer:

Created by Mr Suffar

133 of 385

Task 421

Answer:

Created by Mr Suffar

134 of 385

Task 422

Answer:

Created by Mr Suffar

135 of 385

Task 423

Answer:

Created by Mr Suffar

136 of 385

Task 424

Answer:

Answer:

Created by Mr Suffar

137 of 385

Task 425

Answer:

Created by Mr Suffar

138 of 385

Task 426

Answer:

Answer:

Created by Mr Suffar

139 of 385

Task 427

Answer:

Answer:

Created by Mr Suffar

140 of 385

Task 428

Answer:

Created by Mr Suffar

141 of 385

Task 429

Created by Mr Suffar

142 of 385

Task 430

Answer:

Created by Mr Suffar

143 of 385

Task 431

Answer:

Created by Mr Suffar

144 of 385

Task 432

Answer:

Created by Mr Suffar

145 of 385

Task 433

Answer:

Created by Mr Suffar

146 of 385

Task 434

Answer:

Created by Mr Suffar

147 of 385

Task 435

?

?

Created by Mr Suffar

148 of 385

Task 436

Answer:

Created by Mr Suffar

149 of 385

Homework watch the video:

https://youtu.be/m4d7F_J7xjQ

Created by Mr Suffar

150 of 385

Revisit phase - Starter

Define the following terms:

Array:

  • A data structure that stores multiple data under one identifier. All of the data must be of same data type.

List / Record:

  • A data structure that stores multiple data under one identifier. Data can be of MULTIPLE data types.

Created by Mr Suffar

151 of 385

  • Distinguish between a 1D and a 2D array.
  • Create a 2D array in python.
  • Complete a trace table of a 2D array.

2 Dimensional Array

Lesson 19

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

152 of 385

Created by Mr Suffar

153 of 385

2 Dimensional Array

2D array is an array inside another array.

It can be visualised as a table of data.

Column 1

Column 2

Column 3

Column 4

Row 1

Index: [0][0]

Index: [0][1]

Index: [0][2]

Index: [0][3]

Row 2

Index: [1][0]

Index: [1][1]

Index: [1][2]

Index: [1][3]

Row 3

Index: [2][0]

Index: [2][1]

Index: [2][2]

Index: [2][3]

Created by Mr Suffar

154 of 385

2D Array

array = [ [3,2,1], [2,3,4], [7,5,2] ]

print(array[0])

What will this code display?

  • [3,2,1]

Row 0

Created by Mr Suffar

155 of 385

2D Array

array = [ [3,2,1], [2,3,4], [7,5,2] ]

print(array[0][1])

What will this code display?

  • 2

Row 0 column 1

Created by Mr Suffar

156 of 385

2D Array

array = [ [3,2,1], [5,3,4], [7,8,2] ]

print(array[1][2])

What will this code display?

  • 4

Created by Mr Suffar

157 of 385

2 Dimensional Array

letters = [ [ "A","B","C"],["G","S","T"] ]

Column 1

Column 2

Column 3

Row 1

A

B

C

Row 2

G

S

T

What will the following code display?

print(letters[1][1])

  • S

print(letters[0][2])

  • C

Created by Mr Suffar

158 of 385

You can use a nested For Loop to loop through a 2d array

row

column

output

0

0

A

0

1

B

0

2

C

1

0

G

1

1

S

1

2

T

Created by Mr Suffar

159 of 385

Looping through a 2d array

The above program calculates the total of all numbers in the array.

Created by Mr Suffar

160 of 385

Looping through a 2d array

The above program calculates the average grade of 3 students.

Note: You don’t need to use a nested for loop if you know which column you are extracting from.

Created by Mr Suffar

161 of 385

Tasks

Complete tasks

Created by Mr Suffar

162 of 385

437) Convert the table below into a 2D ARRAY then display it on the screen:

Paste your code below:

Column 1

Column 2

Column 3

Row 1

2

5

4

Row 2

8

7

1

Row 3

7

3

9

Created by Mr Suffar

163 of 385

438.

  • Modify number 5 on row 1 column 2 and change it to number 10 using the following code: array[0][1] = 10
  • Then display the new list on the screen.

Paste your code below:

Created by Mr Suffar

164 of 385

439) Complete the trace table.

row

grades[row][0]

grades[row][1]

Output

Created by Mr Suffar

165 of 385

440) Complete the trace table. Assume the user enters the following inputs: 15,40,20,7,55,21

x

y

num

numbers[x][y]

Created by Mr Suffar

166 of 385

441) Complete the trace table. Assume the user enters the following inputs: 25,90,50

row

Output

score

grades[row][1]

Created by Mr Suffar

167 of 385

442. The table on the right shows student’s names and grades

and is represented the following 2d array:

grades = [["Tom",""],["Mark",“B"],["Kim",""],["Sam",“C"],["Andy",""]]

Use the above array to create an algorithm that:

  • Check if a grade has been added for each student.
  • If a grade has been added, display the name and the grade of that student.
  • If the grade hasn’t been added, display the student name

and ask the user to enter a grade for that student.

  • Add that grade to the 2d array then display the name of the student with their grade.

Paste your code below:

Tom

Mark

B

Kim

Sam

C

Andy

Created by Mr Suffar

168 of 385

443. An analyst wants to add the names of 3 singers and the number of votes they received in a 2d array.

votes = [["",""],["",""],["",""]]

Assume all of the data including the names and numbers are of string data type. Use the array above.

Create a program that:

  • Asks the user to enter the name of the 3 singers and the amount of votes each singer then adds them to the 2d array above.
  • Display the 2d array.
  • Then display the name of singers only.

Paste your code below:

Created by Mr Suffar

169 of 385

444. players = [["Ronaldo","9","N"],["Messi","10","N"],["Ramos","4","Y"]]

The above 2d arrays contain player names, player number and whether they are currently on a RED card or not. Y represents a red card.

Create an algorithm that

  • Loops through the 2D array and checks whether a player is on a red card.
  • If a player is on a red card, display the player name followed by the player number followed by “is on a red card”.

Paste your code below:

Created by Mr Suffar

170 of 385

445. The table on the right can be represented by the following 2d Array:

numbers = [[1,2,4,5],[3,4,6,7],[2,7,8,9],[8,7,1,2]]

Create an algorithm that:

  • Calculates and outputs the total (sum) of the numbers in the table.
  • Calculates and outputs how many individual

numbers are present in the table.

  • Calculates and outputs the average of the numbers in the table.

Paste your code below:

col1

col2

col3

col4

Row1

1

2

4

5

Row2

3

4

6

7

Row3

2

7

8

9

row4

8

7

1

2

Created by Mr Suffar

171 of 385

446. numbers = [[5,12,45,6,32],[5,7,2,4,5]]

Create a program that loops the array above which has 2 rows and 5 columns and resets all the numbers in the 2d array to 0 then display the array on the screen.

Paste your code below:

Created by Mr Suffar

172 of 385

447. The table on the right can be represented by the following 2d Array:

numbers = [[1,2,4,5],[3,4,6,7],[2,7,8,9],[8,7,1,2]]

Create an python program that:

  • Calculates and displays the highest and lowest number in the array in a full sentence.

Paste your code below:

col1

col2

col3

col4

Row1

1

2

4

5

Row2

3

4

6

7

Row3

2

7

8

9

row4

8

7

1

2

Created by Mr Suffar

173 of 385

448- A company wants to identify the length of time in seconds that sensor were activated in a day. Data for 2 of the days are shown in the table & array.

Using the array below, create a program that:

  • Asks the user for a date
  • Calculate the total time the sensors were activated on that day
  • Outputs the calculated time in an appropriate message including the date.

Example: Sensors were activated for 15 seconds on 15/03/2023

Use the array below to test your program.

sensors = [ ["15/10/2023",6],["15/10/2023",9],["16/10/2023",7],["16/10/2023",9] ]

Paste your code below:

Date

timeinseconds

15/10/2023

6

15/10/2023

9

16/10/2023

7

16/10/2023

9

Created by Mr Suffar

174 of 385

449. numbers = [[5.5,12.3,45.2,6.7,32.99],[5.33,7.22,2.76,4.77,5.66]]

Calculate the total of the array numbers which has 2 rows and in each row it has 5 numbers. Round the answer to the nearest whole number then display it on the screen.

Paste your code below:

Created by Mr Suffar

175 of 385

450. numbers = [[3,0,0,0,3],[0,3,3,3,0]]

The array above is storing the score of 2 teams in a 2d array. Each team played 5 matches. Number 3 means the team has “won” a match. Number 0 means a team has lost a match.

Create a program that loops through the 2d array to calculate the number of wins each team has then display it on the screen in a full sentence.

Paste your code below:

Team1

Team2

3

0

0

3

0

3

0

3

3

0

Created by Mr Suffar

176 of 385

451. match = [[1,0,0,1,1],[0,1,1,1,1]]

The 2d array match contain 2 teams in a game. Each team has 5 players. The match will start when all players click on the “ready” button. When the “ready” button is clicked. The number for the player position turn from 0 to a 1.

The area match currently shows the how many players are ready in each team

Loop the array above and display how many players from team1 are NOT READY and how many players in team2 are NOT READY. Display the answer in a full sentence.

Paste your code below:

Player

Team1

Team2

Player1

Ready

Not ready

Player2

Not ready

Ready

Player3

Not ready

Ready

Player4

Ready

Ready

Player5

Ready

Ready

Created by Mr Suffar

177 of 385

452. points = [[80,30],[74,88],[99,88]]

The array points contain the number of positive behaviour points and number of negative behaviour points of 3 students.

Create a program that loops through the string and calculates the total overall behaviour points of each student and display it in a full sentence.

If the total behaviour point of a student is negative, then display “You have received a detention”, if the total behaviour point is positive, then display “You have received a certificate”.

Paste your code below:

Behaviour

Student1

Student2

Student3

Positive points

80

74

99

Negative points

30

88

88

Created by Mr Suffar

178 of 385

453. The table below shows the number of new

Instagram followers of 3 celebrities.

Print(celeb[1][6]) will display 232 which is the

number of followers for celebrity 1 on Sunday.

11a) Create a 2d Array to represent the table.

Then display the number of followers for

Celebrity 0 on Monday (day 0).

Paste your code below:

0

1

2

0

20

31

5

1

32

22

6

2

11

34

8

3

23

56

7

4

42

534

8

5

22

43

6

6

11

232

7

Celebrities

Days of the

Week

(Mon-Sun)

Created by Mr Suffar

179 of 385

454. The table below shows the number of new

Instagram followers of 3 celebrities.

Print(celeb[1][6]) will display 232 which is the

number of followers for celebrity 1 on Sunday.

11b) Use your 2D array from previous question

And a loop(iteration) to count the total of

Followers celebrity 2 received in a week.

Paste your code below:

0

1

2

0

20

31

5

1

32

22

6

2

11

34

8

3

23

56

7

4

42

534

8

5

22

43

6

6

11

232

7

Celebrities

Days of the

Week

(Mon-Sun)

Created by Mr Suffar

180 of 385

455. The table below shows the number of new

Instagram followers of 3 celebrities.

Print(celeb[1][6]) will display 232 which is the

number of followers for celebrity 1 on Sunday.

11c) Use your 2D array from previous question

And a nested loop (2 for loops) to calculate &

Display the total followers of all 3 celebrities

In a week (7 days).

Paste your code below:

0

1

2

0

20

31

5

1

32

22

6

2

11

34

8

3

23

56

7

4

42

534

8

5

22

43

6

6

11

232

7

Celebrities

Days of the

Week

(Mon-Sun)

Created by Mr Suffar

181 of 385

456. player = [["A",65],["B",68],["C",72],["D",46],["E",75],["F",79],["G",90]]

(Note, for reference: player[6][1] is 90)

Write a program which:

- Finds the lowest score in the list

- Finds the highest score in the list

- Outputs the player with the lowest score and their score

- Outputs the player with the highest score and their score

Paste your code below:

Created by Mr Suffar

182 of 385

  • Consolidate understanding of iteration and selection.
  • Consolidate understanding of 1D and 2D arrays.
  • Consolidate understanding of random number generator.

Revision

Lesson 20

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

183 of 385

Tasks

Complete the revision tasks

Created by Mr Suffar

184 of 385

457.

  • Ask the user to enter a game
  • Display the numbers from 0 to the number of characters in the game entered. (On separate lines)

Paste your code below:

Created by Mr Suffar

185 of 385

458. Use the following array: numbers = [1,5,2,3,7,3,54,2,1,8,6,3,4]

Create a program that:

  • Loops through the array to calculate how many odd numbers and how many even numbers are in the array.
  • Display the answer in a full sentence.

Paste your code below:

Created by Mr Suffar

186 of 385

459. An isosceles triangle is a triangle with (at least) two equal sides.

  • Create 3 variables to allow to the user to enter the 3 lengths.
  • Works out if the triangle is isosceles or not.
  • If it’s not then display “The triangle is not isosceles, enter new lengths”
  • Repeat the process until the user enters lengths of an isosceles triangle
  • Then display “The triangle is isosceles.”

Paste your code below:

Created by Mr Suffar

187 of 385

460. Create an algorithm that:

  • Asks the user how many items need to be scanned.
  • Asks if the item has been scanned correctly.
  • If yes, display the item x has been scanned. Where x represent the item number. If no, display item x has not been scanned correctly. And ask the question again.
  • The process repeats until all items has been scanned correctly.

Paste your code below:

Created by Mr Suffar

188 of 385

461.

goalsScored= [2,4,5,2,3,1,5,2,1,5,3,4,2,1,1,4,2,3,1,4]

goalsConceded=[3,2,3,3,0,2,1,0,4,6,2,4,2,1,3,4,2,6,1,2]

The array above shows the how many goals Aston Villa scored in each of their last 20 games and how many goals they conceded.

Create an algorithm that:

  • Loops through both arrays to count and display the number of matches where Aston villa scored at least 3 goals and the number of matches where Aston villa conceded at least 3 goals.
  • Display your answer in a full sentence.

Paste your code below:

Created by Mr Suffar

189 of 385

462.

Ask the user for a number and store it in a variable called “num1”.

Ask the user for another number and store it in a variable called “num2”.

Swap the values of the variables so that num1 variable will contain the value of num2 and num2 contains the value of num1.

Display the final value of num1 and num2 in a full sentence.

Paste your code below:

Created by Mr Suffar

190 of 385

463. players = [["Sandra",7],["Bilal",4],["Hala",9]]

The above array “players” shows 3 students with their grade in a Maths competition.

Using the array above, create a program that asks the user for a name, if the name is inside the array, display the grade of the student. If the name is not inside the array, display “Not found” and repeat the question again.

Paste your code below:

Created by Mr Suffar

191 of 385

Paste your python code below:

image1 = [ [0,0,0],[0,1,1],[1,1,0] ]

image2 = [ [1,1,1],[1,1,0],[0,0,1] ]

inverse = True

i = 0

while i <=2:

j = 0

while j <=2:

6 Marks

Task 464

Created by Mr Suffar

192 of 385

Task 465

Answer:

Created by Mr Suffar

193 of 385

Task 466

listData = [ "","","","","","","",""]

Answer:

Created by Mr Suffar

194 of 385

Task 467

?

?

?

?

Created by Mr Suffar

195 of 385

Task 468

?

?

?

?

Created by Mr Suffar

196 of 385

Homework watch the video: https://youtu.be/PVLqrEVOlQM

Created by Mr Suffar

197 of 385

469. Starter: Revisit phase – Complete the trace table Assume the user enters the following values: 5,106,200,100

start

num

output

True

5

Low

True

106

High

True

200

High

True

100

Good

False

Created by Mr Suffar

198 of 385

  • Explain the purpose of text files.
  • Write to a text file in python.
  • Use a For loop to write multiple data to a text file.

File Handling

Lesson 21

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

199 of 385

Created by Mr Suffar

200 of 385

Text files

Text files can be used to save data in a text file such as score, username and passwords.

Created by Mr Suffar

201 of 385

Text files

Advantages of storing data on a text file:

  • Data is not lost when the computer is switched off as data is stored permanently.
  • Data can be used by more than one program or reused when a program is run again.
  • Data can be backed up or archived.
  • Data can be transported from one computer to another.

Created by Mr Suffar

202 of 385

Writing to a file

file = open("test1.txt", "w")

file.write("Welcome\n")

file.write("My Friend")

file.close()

Variable /

file handler

Opens/create a file

File name

Tells the program we want to “write”

Values/text that will be inside the file.

Move to a new line.

Write inside the file.

Closes the file

Created by Mr Suffar

203 of 385

Example:

The code will create a file called Names.txt then it will ask the user for a name and writes that name in a text file.

Created by Mr Suffar

204 of 385

Example:

When writing a number to a text file. You must CAST it to a string, otherwise you will get an error.

Cast num from an integer to a string.

Created by Mr Suffar

205 of 385

Writing to a file

file = open("names.txt","w")

for x in range (4):

name = input("Enter name")

file.write(name+"\n")

file.close()

Variable /

file handler

Opens/create a file

File name

Repeat the process 4 times.

Asks user for a name.

Move to a new line.

Write inside the file.

Closes the file

write mode

Created by Mr Suffar

206 of 385

COLD CALL

Created by Mr Suffar

207 of 385

Tasks

Complete the tasks

Created by Mr Suffar

208 of 385

470. Copy the code below, run it and test it, then explain the purpose of the program/what the program does.

Explain the purpose of the code below:

file = open("dancers.txt","w")

pupil = 0

while pupil < 3:

dancer = input("Do you dance?")

if dancer=="yes":

name = input("Enter your name")

file.write(name+"\n")

pupil = pupil + 1

else:

print("Why do you not dance?")

file.close()

Answer:

Created by Mr Suffar

209 of 385

471. The program below must: Creates a file called “colours.txt”, ask the user for 6 colours and add them to the text file. Close the text file.

Copy the code below, run it and fix the errors.

file_name = "colours.txt

file = open(file_name, "ws")

for i in range(6)

colour = inpu("Enter colour")

file.wrie(colour + "\n"

file.closee()

print("Colours have been written to", filename)

Paste the correct version below:

Created by Mr Suffar

210 of 385

472. In python: Create a text file called “numbers.txt”, ask the user to enter a number and store it in a text file. Then ask them if they want to enter another number, if the answer is “no” then stop the

file = open("____.txt","__")

while True:

number= ____(____("Enter a number to store in the file?"))

file.____(str(____)+"\n")

repeat = ____("Do you want to enter another number?")

if repeat == "____":

break

file.____()

Copy the code above, fill the gaps then paste your code below:

Created by Mr Suffar

211 of 385

473. In python

  • Create a text file called "hobby.txt "
  • Write " football " to the text file.
  • On another line write "Basketball "
  • Then close the file.

Paste your code below:

Created by Mr Suffar

212 of 385

474. In python

  • Create a text file called "singers.txt "
  • Ask the user for their favourite singer then write it to the text file.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

213 of 385

475. In python

  • Create a text file called "celebrities.txt "
  • Ask the user for their top 5 favourite celebrities (use a for loop)
  • then write each celebrity name in the text file on a separate line.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

214 of 385

476. In python

  • Create a text file called "numbers.txt "
  • Ask the user to enter 6 numbers (use a for loop).
  • then write each number in the text file on a separate line.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

215 of 385

477. In python

  • Create a text file called "numbers.txt "
  • Asks the user for a number.
  • If the number is greater than 100 then write it in the text file.
  • Otherwise display "Number is not big enough" on the screen.
  • Repeat the process 4 times.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

216 of 385

478. In python

  • Create a text file called "data.txt"
  • Ask the user if they want to write to the text file.
  • If the answer is "yes", ask the user for a sentence to write.
  • Repeat the process until the user enters any input other than "yes" when asked if they want to write to the text file.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

217 of 385

479. In python

  • Create a text file called "newfile.txt"
  • Ask the user for a username and password.
  • Repeat the questions until they enter the correct username and password. Assume the correct username is "Luther" and the correct password is "bob123" .
  • When the correct username & password have been entered, write them to the text file.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

218 of 385

480. In python

  • Create an empty list (array)
  • Asks the user to enter 4 names and append them to the list (array).
  • Creates a text file called "names.txt"
  • Loop through the array and write each name in the array to the text file.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

219 of 385

481. A teacher wants to write the names and grades of his students in a text file:

  • Create a text file called "grades.txt"
  • Asks the user how many students are in his class.
  • Ask for the name and grade of each student and write it to a text file on separate lines.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

220 of 385

482. In python:

  • Create a text file called “evennumbers.txt”.
  • Open the text file
  • Ask the user to enter an even number.
  • If the number is even add it to the text file.
  • Otherwise, ask the user to enter the number again. Ask for a number repeatedly until the user enters an even number.

Paste your code below:

Created by Mr Suffar

221 of 385

Homework watch the video:

https://youtu.be/WJXjdaEE2bg

Created by Mr Suffar

222 of 385

Revisit phase – Starter – Identify the 5 errors in the code.

The purpose is to ask the user for a name and write it to a text file.

Missing .txt

Should be 1 parenthesis

Should be write

Should be name without an s.

Missing ()

Created by Mr Suffar

223 of 385

  • Demonstrate appending to a text file.
  • Demonstrate reading from a text file.
  • Demonstrate Looping through a text file.

File Handling

Lesson 22

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

224 of 385

Created by Mr Suffar

225 of 385

Appending to a text file

When you open a file in write mode, it will either create a new file for you or overwrite an existing file with the same name.

If you want to open an existing file but don’t want to overwrite the contents that is already inside it, you need to open it in APPEND MODE.

This will allow you to add data to the end of the file rather than overwrite existing content.

Created by Mr Suffar

226 of 385

Appending to a file

file = open("test1.txt", "a")

file.write("Welcome\n")

file.write("My Friend")

file.close()

Variable /

file handler

Opens/create a file

File name

Tells the program we want to “append”

Move to a new line.

Write inside the file.

Closes the file

Created by Mr Suffar

227 of 385

Reading from a text file

file= open("hobby.txt", "r")

print(file.read())

file.close()

Variable/ file handler

Opens the file

File name

Read mode

Closes the file

Displays the content of readit

Created by Mr Suffar

228 of 385

Reading from a text file

file= open("names.txt", "r")

readit = file.read()

file.close()

print(readit)

Variable/ file handler

Opens the file

File name

Read mode

Read the content of the file and stores it in a variable called readit.

Closes the file

Displays the content of readit

Created by Mr Suffar

229 of 385

Reading from a text file

Before you can read from a text file, you must first check the file exists.

If the file does not exist, then an error will occur.

Created by Mr Suffar

230 of 385

COLD CALL

Created by Mr Suffar

231 of 385

Tasks

Complete tasks

Created by Mr Suffar

232 of 385

483.

  • Create a text file called “company.txt" (write mode).
  • Ask the user to enter the name of a company then ask them to enter a star rating for that company and store both in the text file.
  • Close the text file.
  • Now open the text file in read mode.
  • Read the content of the file then display it on the screen.

Paste your code below:

Created by Mr Suffar

233 of 385

484.

  • Create a text file called "singers" (write mode).
  • Ask the user to enter the name of a singer and store it in the text file.
  • Close the text file.
  • Now open the text file in read mode.
  • Read the content of the file then display it on the screen.

Paste your code below:

Created by Mr Suffar

234 of 385

485.

  • Ask the user to specify a filename.
  • Create a text file with the name that the user entered.
  • Ask the user to enter a hobby.
  • Write the hobby in the text file then close the text file.

Paste your code below:

Created by Mr Suffar

235 of 385

486. For this question, copy and paste your code from question 192 and put it at the top. You will be adding to it now.

  • Open the text file from question 192 in append mode.
  • Ask the user to enter a name.
  • Write the name in the text file.
  • Close the text file.
  • Open the text file in read mode and read the contents of the text file.
  • Close the text file then display the contents of the file on the screen.

Paste your code below:

Created by Mr Suffar

236 of 385

487.

  • Ask a user if they want to read or write.
  • If the answer is write, then create a text file called "colour.txt"
  • Ask the user for their favourite colour then write it to the text file.
  • If the answer is read, ask the user which file do they want to read.
  • Read the content of that file (make sure that the file exists to be able to read from it) then display the content of the file on the screen.
  • Display "Wrong answer" for any other choices.
  • Close the text file.

Paste your code below:

Created by Mr Suffar

237 of 385

488.

  • Create a file called numbers.txt (write mode)
  • Ask the user how many numbers they want to enter.
  • Depending on the user’s answer, ask the user for that many numbers and write them inside the text file.
  • Close the file.
  • Open the file in read mode, read the numbers inside the text file and display them on the screen.

Paste your code below:

Created by Mr Suffar

238 of 385

489.

  • Create a file called data.txt (write mode)
  • Ask the user if they want to enter their firstname or surname in the file.
  • Depending on the user’s answer, ask them for their firstname or surname and write it inside the file.
  • Close the file.
  • Repeatedly ask the question until the user enters “firstname” or “surname” when asked whether they want to enter their first name or surname.

Paste your code below:

Created by Mr Suffar

239 of 385

490.

  • Create a file called "games.txt " (write mode) .
  • Ask the user to enter the name of 3 games and write them inside the file.
  • Close the file.
  • Open the file in read mode and read the contents of the file.
  • Ask the user if they want to see the contents of the file in uppercase or lowercase.
  • Display the content of the file according to the user’s answer.

Paste your code below:

Created by Mr Suffar

240 of 385

491. Part 1 - A company hired Jim to watch 5 films then rate each film out of 10.

Create an algorithm that:

  • Asks for film name.
  • Asks for the film rating,
  • if the rating is above 7, store the film name in an a list (array) called
  • films and the rating in a list (array) called rating.
  • The process repeats until all 5 films have been rated.
  • Loop through the arrays to display the film names and the ratings.

Paste your code below:

Created by Mr Suffar

241 of 385

492. Part 2 – Update your previous program to allow the user to choose if they want to write the film names and rating of films that had a score of 8 or above to a file or not.

  • Your program must ask the same question for each film name that received a score of 8 or above.
  • If the user answers yes, write the film name and its rating to a text file called “filmratings.txt”.

Paste your code below:

Created by Mr Suffar

242 of 385

Reading from a text file

file= open("names.txt", "r")

name = input("Enter name")

for line in file:

if line == name +"\n":

print("Found")

file.close()

Variable/ file handler

Opens the file

File name

Read mode

Loops through each line in the text file.

Closes the file

if the name is in the file, then it will display Found.

Created by Mr Suffar

243 of 385

493.

  • Create a file called "newdata.txt" (write mode) .
  • Ask the user for 5 usernames and write them in the text file. Then close the file.
  • Open the file in read mode.
  • Ask the user to enter a usernames that is inside the file.
  • Loop through each line in the file, if the usernames is inside the file, display “Found”.

Paste your code below:

Created by Mr Suffar

244 of 385

Homework watch the video: https://youtu.be/ualSFRIclz8

Created by Mr Suffar

245 of 385

Revisit phase / Starter

What are the 3 programming constructs:

  • Sequence
  • Selection
  • Iteration

Created by Mr Suffar

246 of 385

  • Demonstrate programming a simple procedure.
  • Describe the purpose of subroutines, parameters and arguments.
  • Explain the advantages of using subroutines.

Subroutine: Procedure

Lesson 23

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

247 of 385

Created by Mr Suffar

248 of 385

Procedure

def names():

choice=input("Enter a name")

print(choice)

names()

names()

def is a command which allows you to define a procedure or a function.

procedure name

Ask the user to input a name.

Displays the user’s answer.

Calls the procedure. This will run line 2 and 3.

Created by Mr Suffar

249 of 385

Procedure

def welcome(name):

print("Welcome to school" , name )

welcome("Alex")

welcome("Tom")

def is a command which allows you to define a procedure or a function.

Procedure name.

Displays welcome to school + the value of the argument.

Argument.

Calls the procedure. This will run line 2.

Parameter.

Created by Mr Suffar

250 of 385

Procedure

Local Variable

What will the program display?

def calculate(num,num2):

print(num * num2)

calculate(2,4)

calculate(5,6)

Parameters

The values 2 and 4 are passed into num and num2.

Created by Mr Suffar

251 of 385

Procedures

  • Parameters: A special variable that passes data into a sub program.

  • Arguments: Actual values that the parameters take when the sub program is called.

Created by Mr Suffar

252 of 385

Procedures

Subprogram: A self-contained piece of code that can be called from the main program. It returns control to the main program when complete and can have parameters and values sent to it.

Created by Mr Suffar

253 of 385

Procedures

Why we use subroutine/subprograms?

  • Sub-programs are part of the program but are not the whole program.
  • They perform a frequently used operation within a program that can be called when needed and that can be reused by another program.

Created by Mr Suffar

254 of 385

Advantages of subroutine

  • Breaks down a program to make it easier to create and test as each subroutine can be tested separately.
  • Reuse code and avoids repetition so quicker to develop programs as its shorter.
  • Easier to maintain as code is shorter and easier to understand.
  • Easier to debug as code is shorter.
  • Work can be split up in a team to work on different subprograms at the same time.

Created by Mr Suffar

255 of 385

Procedure trace table - Assume the user enters the following values: 5,18,15,100,17

choice

num

output

5

7

Bad

18

20

Good

15

17

Almost

100

102

Good

17

19

Almost

Created by Mr Suffar

256 of 385

Tasks

Complete tasks

Created by Mr Suffar

257 of 385

494. Copy the code below, run it and test it, then explain the purpose of the program/what the program does.

Explain the purpose of the code below:

def areaofrect(length,width):

area = length * width

print("Area of rectangle is",area)

areaofrect(5,7)

Answer:

Created by Mr Suffar

258 of 385

495.

  • Create a procedure called “name” that will ask the user for their name.
  • Display the name.

Paste your code below:

Created by Mr Suffar

259 of 385

496.

  • Create a procedure called “numbers” that will ask the user for 2 numbers.
  • It will then divide the first number by the second.
  • Display the answer.

Paste your code below:

Created by Mr Suffar

260 of 385

497. The program below must: Create a procedure that takes Celsius as parameter. It then converts Celsius to Fahrenheit and displays the answer on the screen.

In the main program, it asks the user for the temperature in Celsius and passes it as an argument to the procedure.

Copy the code below, run it and fix the errors.

define celsius_to_fahrenheit(celsius:

fahrenheit (celsius * 9/5) + 32

print("The temperature in Fahrenheit is:" fahrenheit)

temp_celsius = float(input("Enter the temperature in Celsius: ")

celsius_to_fahrenheit(tempcelsius)

Paste the correct version below:

Created by Mr Suffar

261 of 385

498. In python: Create a procedure called square_number() that takes a number as a parameter. In the main program, ask the user for a number and pass it as an argument to the procedure. The procedure calculates and displays the square of the number passed into the parameter.

def square_number(____):

square = ____ ** ____

print("The square of", ____, "is:", ____)

num = ____(____("Enter a number: "))

square_number(____)

Copy the code above, fill the gaps then paste your code below:

Created by Mr Suffar

262 of 385

499.

  • Create a procedure called “adultorteen” that takes an age between 13 and 100 as a parameter.
  • If the age is between 13 and 19, display teenager.
  • If the age is between 20 and 100 display adult.
  • Display invalid age if age entered is not between 13 and 100.

Paste your code below:

Created by Mr Suffar

263 of 385

500.

  • Create a procedure called “game” that takes a number as a parameter.
  • It will display “over 9000s” if the argument is over 9000, otherwise it will display “You need to power up”.
  • Use number 8 as the argument.

Paste your code below:

Created by Mr Suffar

264 of 385

501.

  • Create a procedure called “oddoreven” that will take a number as a parameter.
  • It will then display “Odd” if the number is odd or “even” if the number is even.
  • Use number 4 as the argument.

Paste your code below:

Created by Mr Suffar

265 of 385

502. Procedure trace table - Assume the user enters the following values: 88,155,15,102,100

Repeat

Repeat == True

num

output

num==100

Created by Mr Suffar

266 of 385

503. Procedure trace table - Assume the user enters the following values: fortnite, minecraft, overwatch

x

game

age

output

Created by Mr Suffar

267 of 385

504.

  • Create a procedure called “count” that takes a number as a parameter.
  • Checks if that number is above 100, and displays an error message if the number (parameter) is above 100.
  • Otherwise it will display all the numbers from that number (parameter) up to and including the number 100.
  • In the main program, ask the user for a number and use it as the argument.

Paste your code below:

Created by Mr Suffar

268 of 385

505.

  • Create a procedure called “multiply” that takes a number as a parameter.
  • The procedure will then display the times table of that number from 1 to 100.
  • Use 4 as the argument.

Paste your code below:

Created by Mr Suffar

269 of 385

506.

  • Create a procedure called “name” that ask the user for a name then displays it on the screen.
  • Create another procedure called age that asks the user for age then displays it on the screen.
  • In the main program, ask the user if they want to run the name procedure or age procedure.
  • If they pick name, run the “name” procedure, if they pick “age”, run the age procedure.
  • Display “Wrong option” for any other choices.

Paste your code below:

Created by Mr Suffar

270 of 385

507.

  • Create a procedure called “countup” that takes a number as a parameter.
  • The procedure will display all numbers from 1 up to that number.
  • Use 6 as the argument.
  • Example: if the argument was 6, the procedure will return: 1,2,3,4,5 and 6.

Paste your code below:

Created by Mr Suffar

271 of 385

508.

  • Create a procedure called “writing” that takes the user’s name & age as a parameter.
  • Writes the user’s name & age in a full sentence to a text file called “information.txt”.
  • Use Aryan and 24 as the arguments.

Paste your code below:

Created by Mr Suffar

272 of 385

509.

  • Create a procedure called “totalsalary” that takes number of employees as a parameter.
  • The procedure must ask each employee for yearly salary which must be of float data type and then add it to a total. It then calculates the average salary of the employees. The procedure then rounds the total to the nearest whole number and rounds the average to 2 decimal points.
  • Test your program by calling the procedure and passing 4 as an argument for the number of employees. Use the call: totalsalary(4)

Paste your code below:

Created by Mr Suffar

273 of 385

510- A program has a procedure, SaveLogs(), that stores the name of the user to an external text file. Create the procedure SaveLogs() that:

Takes the name as a string to be stored to the text file as a parameter

Takes the filename of the text file as a parameter

It creates a text file using the filename that was received from the parameter

It stores the name of the user in the text file

In the main program do the following:

Ask the user for their name and for a file name and pass them as arguments to the procedure SaveLogs().

Paste your code below:

Created by Mr Suffar

274 of 385

511- An online shop sells clothes and food. The shop provides free delivery if the total transaction of all items exceed 100$

Create a procedure called “onlineshopping” that takes a total which starts at 0 as a parameter. The procedure must:

Ask the user for number of items to be purchased. For each item, ask for the name of item and the price of the item. Calculate the total price of all items then display whether the delivery will be free or not.

Test your program by calling the procedure “onlineshopping” and using the argument 0.

Paste your code below:

Created by Mr Suffar

275 of 385

Task 512

Answer:

Created by Mr Suffar

276 of 385

Homework

Created by Mr Suffar

277 of 385

Revisit – Task 513

Answer:

Created by Mr Suffar

278 of 385

  • Demonstrate programming a simple function.
  • Explain the difference between global and local variables.
  • Explain the the difference between a procedure and a function

Subroutine: Function

Lesson 24

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

279 of 385

Theory

Created by Mr Suffar

280 of 385

Functions

A function is a subroutine that returns a value.

Created by Mr Suffar

281 of 385

Function

Local Variable

def name():

choice = input("Enter name")

return choice

print(name() )

Calls and displays the returned value of the function

Causes the function to exit and hand back the value of choice to its caller

Function name.

Created by Mr Suffar

282 of 385

Function

Local Variable

def multiply(num1,num2):

answer = num1 * num2

return answer

print(multiply ( 2 , 8 ) )

Parameters

Arguments, the values 2 and 8 are passed into num1 and num2.

causes the function to exit and hand back the value of answer to its caller

Created by Mr Suffar

283 of 385

PROCEDURE

def numbers():

for x in range(1,101):

print(x)

numbers()

What will this procedure display?

  • 1 to 100

Created by Mr Suffar

284 of 385

FUNCTION

def numbers():

for x in range(1,101):

return x

print(numbers())

What will this program display?

  • 1

It will only display 1 and not 1 to 100 as return causes the function to break.

Created by Mr Suffar

285 of 385

Functions & Procedures

Similarities and differences between function and a procedure

  • Both functions and procedures are used to structure code and create reusable component.
  • Function returns a value, a procedure does not.

Created by Mr Suffar

286 of 385

Variable Scope

Global variable: Declared outside any subroutines and accessible throughout the program.

Local variable: Declared within a subroutine. Can only be accessed in that subroutine.

Created by Mr Suffar

287 of 385

Variable Scope

Local

Global

Created by Mr Suffar

288 of 385

Variable Scope

Local

Global

Identify the local and global variables in the example below:

Created by Mr Suffar

289 of 385

Variable Scope

Parameters have a local scope to the sub program they’re defined in.

Local

Local

Created by Mr Suffar

290 of 385

Variable scopes

The differences between local and global variables:

  • Local variables are declared in subroutines.
  • Global variables are used throughout the entire program.

Advantages of using local variables:

  • Local variables are used when they are not needed throughout the entire program.
  • It uses memory only when needed.
  • It is harder to find errors in global as they can be accessed throughout the entire program.

Created by Mr Suffar

291 of 385

Tasks

Complete tasks

Created by Mr Suffar

292 of 385

514. Copy the code below, run it and test it, then explain the purpose of the program/what the program does.

Explain the purpose of the code below:

def check_number(number):

if number > 0:

return "Positive"

elif number < 0:

return "Negative"

else:

return "Zero"

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

result = check_number(num)

print("The number is:", result)

Answer:

Created by Mr Suffar

293 of 385

515. The program below must: a

Copy the code below, run it and fix the errors.

def convert_to_miles(kilometers):

miles = kilometer * 0.621371

returns miles

km = real(input("Enter the distance in kilometers: "))

result = convert_to_miles(kmm)

print("The distance in miles is:", result

Paste the correct version below:

Created by Mr Suffar

294 of 385

516. In python: a

def calculate_total(____):

total = ____

for x in range(____):

num = ____(____("Enter a number"))

total = ____ + ____

return ____

num_list =____(____("How many numbers do you want to enter"))

result = calculate_total(____)

print("The total sum is:", ____)

Copy the code above, fill the gaps then paste your code below:

Created by Mr Suffar

295 of 385

517.

  • Create a function called “multiply” that takes a two numbers as a parameter.
  • The function will return the value of the first number multiplied by the second number.
  • Use 2 and 5 as the arguments.

Paste your code below:

Created by Mr Suffar

296 of 385

518.

  • Create a function called average that takes 3 numbers as parameters.
  • The function will return the average of the 3 numbers.
  • Use 4,7 and 10 as arguments.

Paste your code below:

Created by Mr Suffar

297 of 385

519.

  • Create a function called “areacircle” that takes radius as a parameter.
  • Your function must calculate and return the area of a circle.
  • Area of circle formula: Pi * RADIUS²
  • Pi = 3.14
  • Use 5 as the argument.

Paste your code below:

Created by Mr Suffar

298 of 385

520.

  • Create a function called “largest” that takes 3 numbers as parameters
  • The function then returns the largest of the three numbers.
  • Use 6,4 and 5 as arguments.

Paste your code below:

Created by Mr Suffar

299 of 385

521.

  • Create a function called “convert” that takes a temperature in Celsius as a parameter.
  • Converts the temperature from Celsius to Fahrenheit.
  • Return the temperature in Fahrenheit.
  • Use 10 as the argument.
  • Formula: Y°F =(X°C × 9/5) + 32
  • X represents the value in Celsius and Y represent the value in Fahrenheit.
  • Use 10 as the argument.

Paste your code below:

Created by Mr Suffar

300 of 385

522.

  • Create a function called “filesize” that calculates and returns the file size of an image.
  • The function takes width, length and bit depth and DPI as parameters.
  • Formula to calculate file size in bits - Formula: Height x Width x DPI x DPI x Bit Depth
  • In the main program, ask the user for width, length, bit depth and DPI and use them as arguments.

Paste your code below:

Created by Mr Suffar

301 of 385

523. Create a function called “game” that takes “playerlevel “ as a parameter. The game adjusts player level to make it fair for all players in a player vs player match. The maximum level a player can be in this match is 60.

Your function must:

  • Take player level as a parameter.
  • If a player level is 50 or above, then it sets their level to 60.
  • If a player level is below 50, then it adds 10 levels to the original player level.
  • Return the new “playerlevel”.
  • Test your program by trying different numbers in the argument.

Paste your code below:

Created by Mr Suffar

302 of 385

524.

Create a function called “game” that takes a number as a parameter.

The function must:

  • Return over 9000 if the number is above 9000.
  • Return it’s 9000 if the number is 9000.
  • Return less than 9000 if the number is less than 9000.
  • Test your program by trying different numbers in the argument.

Paste your code on the below:

Created by Mr Suffar

303 of 385

525. A buffet restaurant wants to create an algorithm to calculate the price of group ticket. The restaurant charges £20 per adult and £12 per child between 8 (8 am) and 15 (2.59 pm). The price increases by 50% between 15 (3pm) and 20 (8pm). The restaurant is closed between 8pm to 8am.

Create a function called “price” that takes number of adults and number of children as parameters.

Your function must:

  • Ask the user for the current time in hours followed by minutes, example: 16.30 which is 4.30pm.
  • If the time entered is not between 8 and 20, then display restaurant is currently closed and ask the question again until the user enters a valid number.
  • Calculate and return the total price taking into account the number of adults, number of children and entrance time.
  • In the main program, ask the user for the number of adults and children and use them as arguments.

Paste your code on the below:

Created by Mr Suffar

304 of 385

526. Copy the code below, run it and test it, then explain the purpose of the program/what the program does.

Explain the purpose of the code below:

length = 200

width = 100

def area():

shapeArea = length * width

print("Area = ",shapeArea)

def perimeter():

shapePerimeter = length*2 + width*2

print ("Perimeter = ", shapePerimeter)

while response not in ("a","p"):

response = input("Do you want to calculate area or perimeter? Enter a or p" )

if response == "a" or "A":

area()

elif response == "p" or "P":

perimeter()

Answer:

Created by Mr Suffar

305 of 385

527. Create a function called regularcuboid() that calculates the volume of a regular cuboid.

In the main program you must ask the user for length, width and height. Pass these as argument to the function.

Inside the function calculate and return the volume of the regular cuboid.

Volume = length * width * height

Paste your code on the below:

Created by Mr Suffar

306 of 385

528. Create a function called “over100” that takes in the total as a parameter. The first value of the total is 0.

The function will repeatedly ask the user for a number, and adds it to the total until the total is above 100.

The function returns the total once the total is above 100.

Paste your code on the below:

Created by Mr Suffar

307 of 385

529. Create a function called “total” that takes in 4 numbers as parameter. The function calculates and returns the total of the 4 numbers.

In the main program, create a variable called answer and store the total that is being returned by the function, use 3 , 2, 6, 8 as arguments. Calculate the average of the 4 numbers in the main program and display the answer.

Paste your code on the below:

Created by Mr Suffar

308 of 385

530. Eatallyouwant restaurant charges an entry fee of £10 for children and £20 for adults.

Create a function called “buffet” that takes in the number of adult and number of children as parameters.

The function will then return the total price that needs to be paid.

Paste your code on the below:

Created by Mr Suffar

309 of 385

531. Create a function called totalling that takes a total which starts at 0 as parameter. The function asks for 10 numbers, add it to the total parameter then once all 10 numbers have been entered, it then return the total.

Test your program by outputting the totalling(0) function.

Paste your code on the below:

Created by Mr Suffar

310 of 385

Task 532

?

?

?

?

?

Created by Mr Suffar

311 of 385

Task 533

Answer:

?

?

?

Created by Mr Suffar

312 of 385

Task 534

Answer:

Answer:

Created by Mr Suffar

313 of 385

Task 535

Answer:

Created by Mr Suffar

314 of 385

Task 536

Answer:

Created by Mr Suffar

315 of 385

537. Create a function called “encryptstring” that takes a sentence as a parameter.

The function will replace the letters a,b and c with “#” and store it in a variable called newsentence and then return newsentence once all appropriate letters have been replaced.

In the main program, ask the user for a sentence and pass it as an argument. Print your function call to test your program.

Paste your code on the below:

Created by Mr Suffar

316 of 385

538. Create a function called ATM that takes a pincode which contains 4 characters as parameter.

  • The function must return True if the pin code contains 4 characters, otherwise it should return false.
  • In the main program, ask the user for a pin code and call your function ATM and pass pin code as an argument.

Paste your code on the below:

Created by Mr Suffar

317 of 385

539. Circuit power can be calculated using the following formula: Power= Voltage * Current.

Create a function that takes voltage and current as parameter, calculates and returns the circuit power.

Test your program by outputting the function with voltage as 1.5 and current as 600.

Paste your code on the below:

Created by Mr Suffar

318 of 385

540. Create a function called repeatstring that takes a string and a number n as parameters and returns the repeated string n number of times.

For example, if we call the function with print(repeatstring("Tom",3)) it should display: “TomTomTom”

Test the program by printing the function call using the following arguments: “Suffar”,3

Paste your code on the below:

Created by Mr Suffar

319 of 385

541. Create a function called makeTen that takes two numbers as parameters. Return true if one of them is 10 or if their sum is 10. Otherwise return false.

Example: makeTen(9,10) returns True

makeTen(1,9) returns True

Paste your code on the below:

Created by Mr Suffar

320 of 385

542. Create a function called “shortest” that takes 2 names as parameters and return the shortest name, if both names are equal to each other in length then join the 2 names together using concatenation and return the new name which is both named joined together.

  • For example the following function call: "print(shortest("bob","tom"))" should display “bobtom”

Paste your code on the below:

Created by Mr Suffar

321 of 385

Task 543

Paste your code below:

Created by Mr Suffar

322 of 385

Task 544

?

?

?

?

Created by Mr Suffar

323 of 385

Task 545

?

?

Created by Mr Suffar

324 of 385

Task 546

Created by Mr Suffar

325 of 385

Task 547

Created by Mr Suffar

326 of 385

Task 548

Created by Mr Suffar

327 of 385

Task 549

Answer:

Answer:

Created by Mr Suffar

328 of 385

Task 550

Created by Mr Suffar

329 of 385

Task 551

Answer:

Created by Mr Suffar

330 of 385

Task 552

?

?

?

Created by Mr Suffar

331 of 385

year

3

return

Task 553

Answer:

Created by Mr Suffar

332 of 385

Task 554

Answer:

Created by Mr Suffar

333 of 385

Task 555

Answer:

Answer:

Answer:

Created by Mr Suffar

334 of 385

Task 556

Answer:

Created by Mr Suffar

335 of 385

Task 557

Answer:

Created by Mr Suffar

336 of 385

Task 558

Answer:

Created by Mr Suffar

337 of 385

Task 559

Answer:

Created by Mr Suffar

338 of 385

Task 560

Answer:

Created by Mr Suffar

339 of 385

Task 561

Answer:

Created by Mr Suffar

340 of 385

Task 562

Answer:

Created by Mr Suffar

341 of 385

Homework

Created by Mr Suffar

342 of 385

Revisit phase

1- Describe the differences between local and global variables

  • Local variables are declared in subroutines.
  • Global variables are used throughout the entire program.

2- Explain why it is better to use local variables?

  • Local variables are used when they are not needed throughout the entire program.
  • It uses memory only when needed.
  • It is harder to find errors in global as they can be accessed throughout the entire program.

Created by Mr Suffar

343 of 385

  • Explain the purpose of authentication & verification.
  • Explain the purpose and types of input validation.
  • Demonstrate coding programs with input validation.

Validation, authentication & verification

Lesson 25

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

344 of 385

Theory

Created by Mr Suffar

345 of 385

Authentication

Authentication: Used to confirm the identity of a user before they can access a program.

Example: Checking both the username and password are correct.

Created by Mr Suffar

346 of 385

Verification

Verification: Used to double-check that the data has been typed in correctly. This is done by checking the input matches an input that has already been supplied.

Example: Double entry of password.

Created by Mr Suffar

347 of 385

Validation

Validation: Checking data entered is reasonable and meets a certain criteria.

Reasons:

  • Reduce errors.
  • Stop programs from crashing.

Types of validation:

  1. Range check
  2. Length check
  3. Presence check
  4. Type check
  5. Format check

Created by Mr Suffar

348 of 385

Validation – Range check

Range check: Checks if the data is within certain range.

Example: Number between 1 and 100

Created by Mr Suffar

349 of 385

Validation – Length check

Length check: Checks the length of the string is valid (acceptable).

Example: Password with at least 8 characters.

Created by Mr Suffar

350 of 385

Validation – Presence check

Presence check: Checks that data has actually been entered.

Example: Checks if the username has been entered.

Created by Mr Suffar

351 of 385

Validation – Type check

Type check: Checks that the data entered is of valid (acceptable) data type.

Example: We can use “DIV 1” to find out if a number is a whole number (Integer)

Created by Mr Suffar

352 of 385

Validation – format check

Format check: Checks that the data entered is of the correct format.

Example: Email must have an @ symbol. DOB should be xx/xx/xxxx.

Created by Mr Suffar

353 of 385

Tasks

Complete tasks

Created by Mr Suffar

354 of 385

563. Range check validation program:

A football stadium makes discounts for group tickets. Carmen wants to purchase a group ticket. Minimum number of tickets must be 5 and a maximum of 20 for a group ticket.

Create a program that:

  • Asks the user to enter number of tickets.
  • Validates that the number entered is between 5 and 20. If not repeat the question until a valid number is entered.
  • When a valid number is entered, display “See you soon!”

Paste your code below:

Created by Mr Suffar

355 of 385

564. Length check validation program:

A website require users to have usernames between 8 and 15 characters.

Create a program that:

  • Asks the user to enter a username.
  • Repeatedly ask the user to enter a username until the user enters a username with the correct number of characters. (between 8 and 15)
  • When a valid number is entered, display “Username accepted”

Paste your code below:

Created by Mr Suffar

356 of 385

565. Presence check validation program:

A website require users to enter a name when making an order. The website owner wants an algorithm that checks if the user has entered something when asked for a name.

Create a program that:

  • Asks the user to enter a name.
  • Checks if the user has entered something, if they haven't, then repeat the same question again until they enter a name.
  • When the user enters a name, display “Order received”.

Paste your code below:

Created by Mr Suffar

357 of 385

566. Type check: Ask the user for age and set the data type to float. If the user enters a decimal number, display “Age can not contain a decimal number”. If the user enters a whole number, display “Valid data type entered”.

Paste your code on the below:

Created by Mr Suffar

358 of 385

567. Format check: Ask the user for date of birth. Then ensure the DOB entered is of the correct format. Ensure that it contains 2 numbers followed by / followed by 2 numbers followed by / followed by 4 numbers.

Example: 04/05/1993

Paste your code on the below:

Created by Mr Suffar

359 of 385

568. Verification program:

Create a program that:

  • Asks the user to enter a username and store it in a variable called “username1”
  • Asks the user to enter the user again and store it in a variable called “username2”
  • If both usernames are the same, display “username accepted”. Otherwise repeat the process above until both usernames are the same.

Paste your code below:

Created by Mr Suffar

360 of 385

569. Authentication program:

Create a program that:

  • Asks the user for a name and age.
  • If the name entered is “Sam” and age entered is “15”, display “Verified”. Otherwise repeatedly the user to enter a name and age until they enter the correct details for both the name and age.

Paste your code below:

Created by Mr Suffar

361 of 385

Task 570

Answer:

Created by Mr Suffar

362 of 385

Extension

Complete tasks

Created by Mr Suffar

363 of 385

try / except

This is a very powerful piece of Python code – it basically tells Python not to crash, but to run a different block of code if it comes across an error.

This is how it works :

try:

code goes here

more code here

except :

if the above code crashes then

this code will be run instead

Created by Mr Suffar

364 of 385

571. Type check validation program:

Create a program that:

  • Asks the user for the number of goals scored in a match.
  • If the user enters a letter or a symbol or a decimal number, display “You must enter a whole number” and repeat the question.
  • When the user enters a whole number, display “Score accepted”.
  • Use the code below of a similar example to help you:

Created by Mr Suffar

365 of 385

Homework

  • Revise for end of unit assessment

Created by Mr Suffar

366 of 385

End of unit test

NOW:

Complete end of unit assessment.

MS Form assessment - test link: https://forms.office.com/Pages/ResponsePage.aspx?id=NRrmRxWbmk-P3e1XFrwgvUKZUnHi_FpMtvQIsO11-sxUNFk4NVE1TkhDQVU4RkU4MUIzUThWRDY1Ti4u

THEN:

Complete any unfinished tasks from previous lessons.

Lesson 27

Created by Mr Suffar

367 of 385

  • Complete the grade 9 level questions.

Grade 9 level questions

Lesson 28

Monday, July 17, 2023

Lesson objectives…

Created by Mr Suffar

368 of 385

572. Ask user for 10 numbers between 1 and 100 and store them in the array called numbers. Validate that only numbers between 1 and 100 are added to the array. Once all 10 numbers are in the array, display the highest and lowest number in the array and the total of the numbers in the array. Write the total, lowest and highest to a text file called "numbers.txt“

numbers = ["","","","","","","","","",""]

Paste your code below:

Created by Mr Suffar

369 of 385

Task 573

Paste your code below:

Created by Mr Suffar

370 of 385

Task 574

Paste your code below:

Created by Mr Suffar

371 of 385

Task 575

Paste your code below:

Created by Mr Suffar

372 of 385

Task 576

Paste your code below:

Created by Mr Suffar

373 of 385

577.

Mr Suffar is developing an adding game. Write an algorithm to play this game. The rules for the game:

  • The game must have 5 players. (LOOP 5 TIMES).
  • For each player, the game asks the user to enter their name.
  • The player is then asked 8 addition questions for example: 5 + 6 , 7+7 , 8+10 (hint: another for loop is needed)
  • Each question asks the player to add together two random whole numbers between 1 and 10 inclusive.
  • If the user answer any question correctly, display “Correct” then add 1 to a score variable that starts with 0.
  • If the answer is incorrect display “Incorrect”
  • When each player finishes all 8 questions, their name is displayed on the screen and the number of correct answers is displayed in an appropriate format: for example: “Jones answered 8 questions correctly out of 8. Then add the name and the score to a 2D array called “players”. Which will be outputted once all players completed the game.
  • Store the name of each player and their score in a text file called “gamestats.txt”.

players= [ ["",""],["",""],["",""],["",""],["",""]]

Paste your code below:

Example of the array at the end of the program

Created by Mr Suffar

374 of 385

578- A company wants to identify the length of time in seconds that sensor were activated in a day. Data for 2 of the days are shown in the table & array.

Using the array below, create a program that:

  • Asks the user for a date
  • If the date is in not in the array, it displays “error” and then repeats. If the date is in the array then it will do the following:
  • Calculates the total time the sensors were activated on that day
  • Store the total time for that day in a text file called “sensorstime.txt” and then outputs total time in an appropriate message including the date.

Example: Sensors were activated for 15 seconds on 15/03/2023

Use the array below to test your program.

sensors = [ ["15/10/2023",6],["15/10/2023",9],["16/10/2023",7],["16/10/2023",9] ]

Paste your code below:

Date

timeinseconds

15/10/2023

6

15/10/2023

9

16/10/2023

7

16/10/2023

9

Created by Mr Suffar

375 of 385

579.

  • An alarm has an algorithm that decides whether to sound the alarm by checking the data that is stored in the following three variables.
  • SystemArmed - example data: True
  • DoorSensorActive – example data: True
  • WindowSensorActive – example data: -True
  • The alarm will only sound when the SystemAlarm has been activated and one or both of the door and window sensors are activated. When the system needs to sound the alarm it calls the pre-written procedure SoundAlarm()
  • Write a program that asks the user the user to input True or False for each of the above variables (3 separate inputs needed) to check whether each is set to True or False depending on whether its active or not.
  • The program should check the data in the variables and calls SoundAlarm() when appropriate or displays “Alarm currently off”.
  • You must first create the SoundAlarm() procedure. The procedure must display “Warning!!” 5 times over 5 seconds. {Hint: Use import time and time.sleep(1) }

Paste your code below:

Created by Mr Suffar

376 of 385

Task 580

Paste your code below:

Created by Mr Suffar

377 of 385

Task 581

Paste your code below:

Created by Mr Suffar

378 of 385

Task 582

Paste your code below:

Created by Mr Suffar

379 of 385

Task 583

Paste your code below:

Task 584

Paste your code below:

Created by Mr Suffar

380 of 385

585. Coin flip game: In this program, you will create a flip the coin game where the user has to bet a specific amount, flip the coin and then win/lose the amount they bet depending if they get it right/wrong.

  • Give the user 1000 coins ($) by setting a variable to 1000.
  • Ask the user if they want to play the game, repeat the process using a while loop until the user enters NO.
  • Print the number of coins that they have.
  • Generate a random number between 1 and 2 and store it in a variable called coinroll.
  • Set the coin roll to heads if the coinroll is = 1 and to tails if the coin roll is = 2.
  • Ask the user how much they want to bet. Then use a while loop to repeat the question if they enter a bet that is higher than the number of coins ($) that they have.
  • Ask them if they want to pick heads or tails.
  • If they get it correct, give them the amount of coins they bet.
  • If they get it wrong, take away the amount of points they bet from the total coins they have that starts with 1000.
  • Ask the user if they want to play the game again. If they don’t say NO, then get them to play again unless they have 0 coins left.

Paste your code below:

Created by Mr Suffar

381 of 385

Task 586

Paste your code below:

Created by Mr Suffar

382 of 385

Task 587

Paste your code below:

Created by Mr Suffar

383 of 385

Task 588

Paste your code below:

Created by Mr Suffar

384 of 385

Task 589

Paste your code below:

Created by Mr Suffar

385 of 385

590. Create a program that loops through the 2d array/list called marks and displays the name of the students in alphabetical order and then calculates the total marks, highest mark, lowest mark and average mark of all students in the array/list.

marks = [ ["Max",70],["Bilal",87],["Ruth",67],["Shea",57],["Ali",88]]

Paste your code on the below:

Max

Bilal

Ruth

Shea

Ali

70

87

67

57

88

Created by Mr Suffar