Python
Learning Intentions – Strand 2 – S2: Algorithms
2.5) Use pseudo code to outline the functionality of an
algorithm
2.6) Construct algorithms using appropriate sequences,
selections/conditionals, loops and operators to solve a
range of problems, to fulfil a specific requirement
2.7) Implement algorithms using a programming language
to solve a range of problems
2.16) Use data types that are common to procedural high-
level languages
*
Pseudocode
• Pseudocode is a kind of structured English for describing
algorithms.
• An algorithm is a sequence of steps designed to
accomplish a specific task. Algorithms are translated into
programs, or code, to provide instructions for computing
devices
*
Pseudocode Example 1
HOW TO MAKE A CUP OF TEA?
1. Get kettle, water, cup, milk, tea bag, spoon, bin
2. Put water in kettle
3. Place tea bag in cup
4. Switch on kettle
5. Wait until water boiled
6. Pour water from kettle into cup
7. Wait 10 seconds
8. Remove tea bag from cup with spoon
9. Put tea bag in bin
10.Pour milk into cup
11.Stir milk into tea with spoon
12.Remove spoon from cup
13.Drink tea
*
Pseudocode - Template
• Using a template helps to make the
algorithm creation process easier:
• Inputs
• Processing
• Outputs
• IPO Model
*
Template:
o Inputs
o Processing
o Output
*
Pseudocode Example 2
HOW TO MEASURE THE AREA OF A ROOM, USE IPO
• Inputs
Length
Width
• Processing
Multiply Length by Width
• Output
Area
Programming Languages
1st generation
• Machine level
• E.g. microcode - 0 and 1s
2nd generation
Programming • Assembly languages
Language • E.g. Assembler
3rd generation
• Higher level of abstraction from
machine’s physical parts
• E.g. Fortan, Cobol, C, C++, C#, Java
4th generation
•More use of pre-written libraries
•Closer to human language
•Beginner friendly
•E.g. Powerbuilder, SAS, RPG, Perl, PHP,
Python, Ruby
5th generation
•Computers have a brain and can
think for themselves
•Artificial intelligence
•E.g. Prolog
What is
Python?
• Named after Monty Python (A
comedy group)
• Scripting Language
• Leader in Data Analytics, Machine
Learning & AI
• Runs very fast
• Large libraries that we can use, all for
free
• Can be used on different types of
computers
• High level, looks like English
• Open source, meaning its free and
you can distribute any Python
program for free without having to
pay a licence
*
• Python is a general-purpose programming language, this
means that it is suitable for writing software to solve many
different kinds of problem
How does Python work?
Versions of Python
• There are two versions of Python:
• Version 2
• Version 3
• Version 2 is no longer used but you sometimes see it online,
we will be using Version 3.
• Version 2 code does not work with Version 3 and vice
versa!
• This course if based on Python 3.6
Installing Python (already done in school)
1. Install Python 3.6 onto your machine
2. We need 3.6 rather than the latest because
some libraries have not been updated yet to
the newest version of Python
3. Found at: http://www.python.org/download
*
Installing an IDE (already done in school)
• An IDE stands for Integrated Development
Environment
• While there are loads of IDEs for Python (e.g.
Pycharm) we must use Thonny for the
Leaving Certificate
• Found at: https://thonny.org/
Once both are installed:
• We now have two options of how to run
python:
• Python command line
• Use Thonny
• Lets look at both…
*
Why use an IDE?
• Rather than running scripts directly, let's say we
wanted to create a script that was 1000 lines
long.
• It would be far more difficult using the console.
• An IDE is like a text editor, like word. It allows us to
create and edit before we run the script.
• We can also save the code, so we can re-use it
later.
*
Our first program – Hello World! (Script 1)
• Python Code:
• Output:
• The print function displays text onscreen, in the
shell/terminal/console
• Why do you think the parenthesis either side are not
displayed?
*
• Python files are called scripts and have file extension .py
Errors
• One vital skill required by Computer Scientists is to be able
to read, understand and respond to errors.
• Look at this error:
• Thonny tells us what line the program crashes at (not
necessarily where the error is) and tells us why the program
crashed (in this case because of an unexpected EOL (end
of line)
*
Errors
• Two types:
• Syntax errors
• When coding, it is essential to use the correct syntax, i.e.
the spelling, punctuation and capitalisation of letters,
otherwise the code cannot be run.
• It is a language so rules must be followed
• Logic errors
• Even if the syntax is correct and the program does run
we might get some bugs.
• Here the program will run with no errors but might not
work all the time or give strange and unexpected results.
• These can be hard to track down and so we need to test
our programs carefully.
Printing
• Computers are stupid
• Unless we are specific with computers our programs will
crash.
• Look at this code again:
• Notice how we have letters inside quotation marks.
• When we place something inside quotation marks in
Python we call it a string (more on strings later)
*
Strings
• In Python you can use single quotations or double
quotations, but correct syntax is to use double
• If we did not use quotations, we would get an error
*
Printing (Script 2)
• What will the output be of the following:
*
Printing (Script 2)
• Notice how they are on separate lines.
• This is because Python automatically adds a new line at
the end of each print statement.
• We can however override this behaviour
• We do this using arguments
Special Characters
• When python adds a new line at the end of a print it is
using a special character called \n
• There are some others that you need to know:
• \n new line
• \t tab
*
Special Characters (Script 4)
• Output
Script 5
• We can use these special characters to format outputs.
• What will be printed by this?
Task 1 (Script 6)
• Try and print the following shapes using stars and special
characters
Printing Numbers
• Python can print numbers without the need for quotation
marks
• Output
*
Comments
• In the real world you are usually working as part of
a team on a software product, or you might leave
a piece of code and come back to it later.
• Therefore, it is vital that you add comments to your
code explaining what each section does.
• Comments contain explanations to help others to
understand what a piece of code is supposed to
do and serve as useful reminders to the
programmer as well.
• We use the # symbol for comments in python
• Python has two types of comments:
#Single line comments indicated by a hash symbol
“””
Multiple line comments indicated by three quotation
marks
“””
Comments (Script 8)
• Output
• Notice how comments are ignored when the program is
ran
Variables
*
Variables
• In Coding, variables are used to record
and store information
• Variables are temporary and only exist
when the program is running. When the
program stops the variables are
removed.
• You can think of
a variable as a
box with a label.
• We can write
(nearly) anything
on the label to
help us
remember what
the box is for
and we can put
stuff into the box
*
Steps to creating a variable 1 2 3
1 2 3
Pick a good Add the Add the
name (more assignment data
on the next operator: =
slide)
This is not a maths class!!!
*
Assigning a value to a variable
• The item of information stored in the variable is
called its value
• Instructing the computer to use a variable to store
a value is called assigning a value to a variable.
• This type of instruction is called an assignment
statement.
*
Naming Variables
• Large programs can have hundreds of variables so its
important that we give variables a good name.
• Do not call variables variable1, variable2, a, b, c etc.
• There are some rules for naming variables
• Must use camel case (more on that in the next slide)
• Must not start with a number (but can contain one)
• Must not have a space
• Must not have a special character (such as @)
• Must not be a keyword
Camel Case
• Camel case is when we start with the first word
being all lowercase and then capitalize the
second (and third etc.) word without a space in
between
• Used for naming variables
• E.G.
• firstName
• accountNumber
• nameOfSchool
Naming Variables
•Correct naming •Incorrect naming
examples: examples:
• i_am_a_variable • I am a variable
• item_27 • 27_item
• class_7 • class class is a keyword!
• more_at • more@
We cannot use Keywords as variables
False class finally is return
None continuefor lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
Keywords are already used in Python to carry out
specific tasks so cannot be used as variable names
• Up to now we have been manually setting
the data that the program will use but this is
bad practice.
• Manually assigning data like this is called
hardcoding.
*
Variable Data Types
• Data type is the type of data stored in the variable
• Python has 4 main data types:
How to cast in
Type Explanation
Python
1. Integer int Whole numbers
Floating point
2. Float float
numbers (decimal)
Sentences, collection
3. String str
of characters
4. Boolean bool True or False
2021 OL
2022 HL
2023 HL
2023 OL
*
Printing Variables (Script 9)
• We can print variables by saying the variable name in our
print statement, rather than writing in the string
• Output
*
Printing Variables (Script 9a)
• Remember a variable only stores one piece of information
at a time:
• Output
*
Variable Types in Python (Script 10)
• Most languages require you to specify the variable type at
the start and cannot be changed mid-way through a
program.
• Python however:
• Will assign the type automatically.
• Change the type during execution if required.
• In this snippet, four variables are declared
and python automatically assigns data
types to them
*
Script 10
• We can also print out the variables type using a Python
built in function, this is very useful for debugging our
programs
• Outputs
*
Arguments
• Adding additional instructions inside the brackets,
separated by commas, is called adding arguments.
• You might see arguments being called parameters as well
• We will be using this a lot in Python.
*
Using variables as arguments (Script 11)
• As we have seen we can use variables in our print
statements.
• Using arguments we can make our outputs more useful.
Operating using Variables *
• Python uses symbols for carrying out calculations on
numbers (just like in maths)
• The symbols we use are called operators
Operator Symbol Example Result is
Add + answer = number1+number2
Subtract - answer = number1-number2
Multiply * Answer = number1*number2
Divide / answer = number1/number2 Always a float
Floor Divide // answer = number1//number2 The number before the
decimal point after division.
Always an integer.
To the ** answer = number1**number2 number1 to the power of
power of number2
Modulus % answer = number1%number2 The remainder in whole
numbers after division.
Arithmetic Operators and
Expressions
Function Operator Expressions Answer
Addition + 10+3 13
Subtraction - 10-3 7
Multiplication * 10*3 30
Floor Division (rounds // 10//3 3
down to a whole 20//9 2
number)
Division (floats) / 10.0/3.0 3.333333333…
Modulus (gives the % 10%3 1
remainder of a division
as a whole number)
Exponent (to the power ** 10**3 1000
of)
*
Modulus explained
• Lets look at an example
*
Operator example (Script 12)
Output
Order of Operations
• The order of operations we know from maths holds true for
Python.
• Brackets
• Indices
• Multiplication
• Division
• Additional
• Subtraction
Breaking maths with computer science
• What do you think the output will be here?
• Output
Task 2 (Script 14)
• Assume pi is equal 3.14 and radius is equal to 7
• Find the volume of the sphere
4
• The formula to find the volume of a sphere is 𝜋𝑟 3
3
• Hint: Try use variables to store data when you
can
2022 OL
User Experience (UX)
User Experience
• User experience UX refers to the experience of the
users when they use your software product.
• The software should behave as the user expects it
to, for good or bad.
• We will not be delving too deeply into UX in this
chapter but just keep in mind how the customer
would expect your product to behave as we
develop our programs
• Lets look at the answer to Task 2 again
• We would like to clean up the answer to reduce the
number of decimal places.
• Python can do this using a new function, round
*
Rounding values (Script 15)
• Outputs
• The round function takes 2 arguments, the thing to be
rounded and the number of decimal places
String Methods (String 16)
• There are five string methods to look at
• String Replication
• String to upper case
• String to lower case
• String capitalization
• String length
• Output
*
Strings in Details
• String indexing
*
Finding a letter of a string (Script 21)
• We can find any letter within a string in Python
• Output
*
Script 22
• We can easily find the last letter, or second last etc.
• Output
*
Substringing (Script 23)
• We can pull out a section of the text, note that it is one
less than the second number
Output:
*
Checking for a substring (Script 24)
• We can check if a string contains a particular character
(or range of values)
• Output
Two underscores!
*
Finding a substring
• The .index() function finds a given item in a
string and returns its index number.
• If the same item occurs more than once, the
.index() function returns the first index number
*
Example (Script 25)
• Output
Inputs
• Up until now we have only been looking at
outputting information from our programs
• We often want to send information into the
computer as well, have it process the data
and display an output
• Remember IPO
*
Inputs
• We can input data into python using the input() function
• Input does not require an argument but it is better UX to
provide one.
• Output
*
• Here we are prompting the user to enter their
name and using the input() function waiting
until they press “enter”.
• Then the data is stored in a variable called
firstName
• Finally we print out a string of text and using
an argument add on the variable data
Inputs
• When we are asking the user to enter data
we must make sure and make it obvious
what we are looking for.
• For example if asking for height tell them
what units to use
• We can also check for valid input but we will
cover that later on
*
Warning
• Inputs are always taken into Python as a string
Script 27
• Lets look at this program
• Output
• All inputs are strings!
*
Casting (Script 28)
• We can overcome this by casting, or forcing the data
type of the data stored in the variable on input
• In fact we can cast any data type
Output
*
Script 29
• When asking the user to enter a number we need to cast
the data to by an int or a float depending on the
situation. We can do this by wrapping the input() function
in an int()
• Output
Performing calculations using inputs
(Script 30)
• This program asks the user for the cost of an
item in euro and the percentage VAT
charged. The program will then calculate
and display:
• The final cost of the item after VAT
• The total amount of VAT charged (useful for
business customers)
• Output
Task 4 (Script 31)
• Create a program that asks the user to input the name of
their favourite artist. Assign this value to a variable. No
hardcoding!
• Create another variable containing a compliment (e.g.,
“is brilliant”). Concatenate (combine) the two string
variables and display the result.
Task 5 (Script 32)
• Assuming that a person only has a first name and
surname, separated by a single space, write a python
script to
• Take in from the user their full name.
• Separate their name into two variables, fName and sName
• Print the fName and sName individually.
Conditional
Statements
• George Boole was an
English mathematician who
worked in Cork in the 19th
century. He developed a
branch of mathematics
known as Boolean logic
which while not very useful
back then, is now vital for
getting computers to make
logical decisions.
*
Comparative Operators
• We often need a computer program to compare one
item with another and record the result. Comparative
operators are used for this
Comparative operator Symbol
Is equal to ==
Is not equal to !=
Is less than <
Is greater than >
Is less than or equal to <=
Is greater than or equal to >=
*
• Notice that the symbol used for “is equal to”
is ==, and not =
• This is not a maths class!!!
• Remember that = is assignment and so we could not use it
for comparison!
*
Selections/Conditionals
• Computers are stupid but we can start to make them
smarter by getting them to make decisions based on the
current state of the program.
• To do this we use If statements
• Lets say we want to build a program that checks if
someone can apply for a driving licence or not.
• In Ireland you are eligible to apply for a driving licence if
you are 17 years old or more and not eligible if you are
under 17.
• Lets think about the IPO needed for this program
Decisions
diamonds
*
YES
Age <17? Not Eligible to apply for
Age a driving licence
*
In code (Script 33)
• Output
*
Structure of an If Statement
• The If statement
• The statement to check
• Ending an if statement with a :
• What we want to execute if the if statement returns True,
notice the indent!
*
Script 34 – Another example
• In this example we are at a self checkout in a shop and
we want the computer to ask the customer if they have a
loyalty card, if they do we want them to scan it.
• Output
Improving our program with an else
• While our program is now useful in that in can execute or
ignore certain sections of our code depending on input
from the user, it could be better.
• Lets look at a decision diamond again for the licence
example.
• We want the computer to display something else if the
user is over 17
*
YES
Age <17? Not Eligible to apply for
Age a driving licence
NO
Eligible to apply for a
driving licence
*
Script 35
• Output
Task 6 (Script 36)
• Write a program for a self checkout machine.
• Ask the user for their total and if they have a clubcard
• If they have a clubcard give them 10% off
• If the customer answers that they don’t have a clubcard
the system will remind them to sign up
• Display total
*
Elifs
• We can make more complex programs by branching the
code using an elif.
• Here the code will check another condition rather than just
ending with an else
• Must appear below an if statement and above another elif or
else
• This is what the decision diamond would look like for a
modified self checkout.
• Here we will ask the user how they would like to pay and adjust
the output as required.
*
paymentType
YES
paymentType == “cash” Please insert your cash
NO
YES
paymentType == “card” Please insert your card
NO
Please go to customer
service
*
In code (Script 37)
• Output
Task 7 (Script 38)
• Write a program that asks the user to type in two numbers.
• If the first number divides evenly into the second number
print a message.
• If the first number does not divide evenly into the second
number, display a different message.
• Hint, use Modulus
Task 8 (Script 39)
• In Rogerson’s Robotics factory, purchasing policy depends on
the cost of the item to be ordered.
• If the item is greater than €10,000 display a message to say
“the purchaser must go to tender”
• If an item to be purchased costs between €500 and €10,000
inclusive, display a message to say “the purchaser must get
quotes from three different suppliers” otherwise say “go ahead
with the order”
• The user should input the cost of the item and the program
should tell them what policy to use
Test Data
Hours Rate Results
Task 9 (Script 40) 30 5.00
Expected (Pay)
150.00
40 5.00 200.00
45 10.00 250
• You have been asked to write a program
for a simple payroll application:
• Employees are paid on the basis of an hourly rate.
• However, if they work hours in excess of 40 hours per week,
they are paid an extra bonus of double the hourly rate for
the extra hours worked.
• The program must be able to check the hours worked and
execute the bonus instructions only if the hours are greater
than 40.
Task 10 (Script 41)
• A program is required to compute gross and net pay
• Gross pay is hourly rate * hours worked
• A standard tax amount of €25 is deducted if the
employee earns more than €100. We then have the net
pay.
Iteration
*
Iterations
• Iteration occurs when we instruct the computer to carry
out a task over and over again by repeating a section of
code.
• This piece of code is called a loop
• There are two types of loop, a while loop and a for loop
• We will start with while loops
*
While loops
• A while loop keeps repeating while a certain condition is
true.
• It stops when the condition is false.
• While loops will always return a Boolean after checking
the condition
*
While loop can be summarised in 4 steps
1 2 3 4
Initialization Condition of Body of loop Make Progress
execution • change the loop
• Initialize the • the statement(s)
• structure the control variable so
variable that which will be that at some point
condition to allow
controls the loop or reject entry into
executed on the program may
the loop each iteration exit from the loop.
*
1. Initialisation
• Here counter is the loop control variable (in this case starting at 0)
• This step is only done once, before the loop is entered
*
2. Condition of execution
• While statement with condition (iterate while the number is less than
10)
*
3. Body of Loop
• The statement(s) which will be executed on each iteration
(lines 4 & 5)
*
4. Make Progress
• Increments the loop control variable, in this case number by 1
*
Note on incrementing in python
• Look at line 5.
• This code will take what ever number is currently in the
variable number, add one to it and then store it back in
the variable called number
*
Structure of a while loop
• The while statement
• The statement to check
• Ending a while loop with a :
• What we want to execute if the while loop returns True,
notice the indent!
*
Script 42
• Output
While Loop Step
Through
• Iteration 0 1) counter = 0
2) while counter < 10:
3) print(counter)
4) counter += 1
5) print("Loop finished...")
Counter
Line of execution variable
Value
1) Counter is set to 0 0
2) Is counter less than 10, True, enter loop 0
3) Print out counter 0
4) Add one to counter 1
While Loop Step
Through
• Iteration 1 1) counter = 0
2) while counter < 10:
3) print(counter)
4) counter += 1
5) print("Loop finished...")
Counter
Line of execution variable
Value
2) Is counter less than 10, True, enter loop 1
3) Print out counter 1
4) Add one to counter 2
While Loop Step
Through
• Iteration 2 1) counter = 0
2) while counter < 10:
3) print(counter)
4) counter += 1
5) print("Loop finished...")
Counter
Line of execution variable
Value
2) Is counter less than 10, True, enter loop 2
3) Print out counter 2
4) Add one to counter 3
While Loop Step
Through
• Iteration 3 to 8
1) counter = 0
2) while counter < 10:
3) print(counter)
4) counter += 1
5) print("Loop finished...")
While Loop Step
Through
• Iteration 9 1) counter = 0
2) while counter < 10:
3) print(counter)
4) counter += 1
5) print("Loop finished...")
Counter
Line of execution variable
Value
2) Is counter less than 10, True, enter loop 9
3) Print out counter 9
4) Add one to counter 10
While Loop Step
Through
• Iteration 10 1) counter = 0
2) while counter < 10:
3) print(counter)
4) counter += 1
5) print("Loop finished...")
Counter
Line of execution variable
Value
2) Is counter less than 10, False, exit loop 10
5) Print “Loop finished…” 10
*
• Make sure that you increment the variable otherwise you
will get stuck in an infinite loop!
• Maybe we want this to happen (e.g. a running program)
Task 11 (Script 43)
• Create a loop that will print the values 1 to 100 to the
screen inclusive.
Task 12 (Script 44)
• Create a loop that will print every even number between
1 to 1000 to the screen.
• Hint use modulus
2021 OL
*
Better uses of while loops
• In Python for loops are more suited to counting
• While loops are still useful however:
• e.g. checking a user password until it is correct
• e.g. data entry within a permissible range
• e.g. the number of entries depends on the condition to
be tested.
*
Example (Script 45)
• A user enters a radius to work out the area of a circle
• The radius they enter must be greater than zero
• Create a loop that continually prompts the user for the
radius until it is greater than zero.
*
• Output
*
Sentinel Control
• In a sentinel controlled loop a special value is input to
indicate that the loop should terminate.
*
Example (Script 46)
• The user enters list of numbers which are to be added
together, when the user enters 0, the sentinel value, the
loop terminates.
*
Example (Script 47)
• A menu system which re-displays a menu with 3 options,
the last option being an exit option.
Task 13 (Script
48)
• Lucy has started her own
sewing business. She plans to
make three kinds of products
for her customers: curtains,
cushion covers and quilts.
• Write a program to display a
menu offering the user these 3
options plus an exit option.
• Display a relevant message to
the user, after each option is
chosen. Use * to create a
visually appealing user
interface
• If the user enters 0 exit the
program
For Loops
• While loops are very useful for sentinel controlled loops
however they are not as suited when it comes to counting. Lets
look at an example
• What will the output be?
For Loops (Script 48)
• If we wanted to have a while loop print out the count
twice we would need to reset the counter in between
loops.
• A better solution would be to use for loops
• Lets examine the same code but using a for loop
• Notice how the last number printed is 10 not
11.
• For loops will go up to 1 less than the second
argument, in a similar way to how
substringing worked
*
Structure of a for loop
• A for loop always consists of:
• The word for
• The loop control variable or counter
• The word in
• A way of setting the number of times that the
loop must repeat
• A colon
• An indented block of code
*
Structure of a for loop
• The for statement
• A variable name
• The word in
• The method used to control how many times the loop runs
• What we want to execute in the for loop
*
Types of for loops
• For loops can be used to iterate (loop
through):
• A range of values
• For a string
• For a list (more on these later)
*
Script 49
• Imagine you were asked to list all house addresses in an
estate to send them a letter, it might look like this:
• Output
*
Script 50
• What if we only wanted every second houses?
• We can add another argument to the in range() function
• Output
*
Summary of options (Script 51)
range() Example and explanation
One argument for number in range(5):
print(number)
Lists the integers from 0 up to but not
including 5. Range starts at 0
Two arguments for number in range(5, 10):
print(number)
Lists the integers from 5 up to but not
including 10. Range starts at the first
argument (in this example 5)
Three arguments for number in range(5, 10, 2):
print(number)
Lists the integers from 5 up to but not
including 10 going up in steps of 2.
Going backwards for number in range(5, 0, -1):
print(number)
Lists the integers from 5 to 1 in steps of -1.
*
For loop and string (Script 52)
• We can use a for loop to iterate through a string and pull
out each individual letter
• Output
*
• This is called looping though an enumerate
variable
• An enumerate variable is a variable that contains
more than one item.
*
Example (Script 53)
• Lets go back to the previous question of counting the
words and spaces in a sentence but using a for loop
• Output
Task 14 (Script 54)
• Using a for loop with only two arguments, write a program
that inputs a value from a user. The program counts from 1
to that value and prints out every odd number
2023 HL
2023 HL
2023 OL
Lists
*
Lists
• In Python there is a data type called a list.
• A list can used to store a collection of data items and to
keep them in order if needed.
• Another name for a list is an array
• To set up a list we create a variable and use square, [ ],
brackets
• Items within a list are separated using commas.
*
• In python lists can contain more than one data
type, which a lot of programming languages
cannot do.
• What this means is we can have a list that contains
Strings, Ints, Floats or Bools or mixed together.
• We can even have lists within other lists
• We call the data points inside a list items.
*
• We can make a list increase or decrease in
size as the program executes
• We can remove, insert or edit items within lists
• This means lists are mutable i.e. we can
change them
• Think on lists as filing cabinets.
• Each drawer contains a different piece of data
• Remember python starts counting at 0 so
the top drawer is 0 and the drawer that
is open in this picture is 1.
*
Lists in code (Script 55)
• Output
*
Indexing Lists (Script 56)
• We can pull data our of lists as follows
• Output
*
Script 57
• Or like this
• Output
*
Using in and not in operators (Script 58)
• We can use these operators to check if something is in a
list or not in a list
• Output
Task 15 (Script 59)
• Tobin’s Garage sells 4 makes of cars, Renault, Ford,
VW and BMW.
• Create a list to store these car types.
• Allow a customer search for a car brand (e.g. Ford,
Tesla) and have the program report back if Tobins’
stocks that car make or not
*
Modifying lists
• We can append or add to the end of a list using the
.append() function and supplying an argument of what to
append
• We can insert an item into a list using .insert() where we
first give an argument for location and then an argument
for the data
• We can remove an item from a list using .remove() and
supplying the index of the item to be removed
*
Lets see it in action (Script 60)
• Output
*
Locating items in a list (Script 61)
• If we need to locate the index of an item in a list we loop
through the list using a for loop
• Careful of your indents!
• NB for ALT 2
• Output
• Also important for ALT 2 is pre-processing.
• We will not be covering this in this chapter
• We will not that when working with data sometimes
having a value of less than – will not give us accurate
results and so we need to change the value to something
else (usually 0)
*
Modifying values (Script 62)
• Output
Task 16 (Script 63)
• Write a Python program to take in 5
numbers and store them in a list.
Separately, go through the list and add
one to each item. Print out the list to test
that each item has been incremented
by 1.
Task 17 (Script 64)
• Create an empty list called petList
• Ask the user how many pets they own
• Using a for loop, loop for how ever many pets they own,
asking them each time what their pet name is and
appending it to the end of the petList
• Print out the petList at the end
• Make sure you have a condition for if they say that they
have no pets (display a message)
*
Python Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result.
• You use functions in programming to bundle a set of
instructions that you want to use repeatedly.
• Alternatively, a function may have many complex steps, so it
is better for it to be contained in a sub-program and
only called when needed.
• We will learn more on functions when we return to Python.
2021 HL
2021 HL
2021 HL
2022 HL
2022 HL
2022 HL
2022 HL
2023 OL
2023 OL
2024 OL
2024 OL
2024 OL
2024 OL
2024 OL Q13 Continued
2024 HL
2024 HL