Unit 8
Programming concepts
Programming languages and IDE
IDLE is Python Integrated development and learning
environment
Five basic constructs in a computer program
Variables and constants
Variables and constants are used to store a single item
of data in a program. This can be accessed through the
identifier.
Variable – A named memory location that can store data
which can change whilst a program is running
Constant – A named memory location that can store
data which cannot change whilst a program is running
Identifier – A name given to a variable or a constant
Variable and constants
Not all programming languages explicitly differentiate between
constants and variables, but programmers should be clear which data
stores can be changed and which cannot be changed.
It is considered good practice to declare the constants and variables to
be used in that program. Some languages require explicit declarations,
which specifically state what type of data the variable or constant will
hold. Other languages like python require implicit declarations, where
the data type is based on the value assigned.
Declarations can be at the start of a program or just before the data is
used for the first time.
Naming of Variables
In all programming languages, variable
names should follow certain rules, such as:
Starting with a letter
Not containing spaces
Can contain letters, numbers, _ or $
Not using reserved words (like if, while, for
etc.)
Should be meaningful
Problem statement
The variables 'name' and 'age' are used to
store data in a program:
name stores the user’s name
age stores the user’s age
Write pseudocode statements to store
“Anna” in user’s name and 30 in user’s age
Convert the statements to Python
Data Types
The characteristics of a piece of data.
Data in a program can be of different types
Data Types
A data type is a classification of data into groups according to the kind of
data they represent
Computers use different data types to represent different types of data in a
program
The basic data types include:
Integer: used to represent whole numbers, either positive or negative
Examples: 10, -5, 0
Real: used to represent numbers with a fractional part, either positive or
negative
Examples: 3.14, -2.5, 0.0
Char: used to represent a single character such as a letter, digit or symbol
Examples: 'a', 'B', '5', '$'
String: used to represent a sequence of characters
Examples: "Hello World", "1234", "@#$%
Boolean: used to represent true or false values
Examples: True, False
Practice Questions
1. Write a pseudocode and python statements for the
following
- Storing “red” in a variable
- Storing 10 in a variable
- Storing real number 22.6 in a variable
- Storing True in a variable.
2. Write a pseudocode statement to assign the word
“house” to a variable named MyWord
3. Write a pseudocode statement to declare a constant
named MultiplyValue with the value 10.
Basic Data Types
Practice Question
Name and describe the most appropriate
programming data type for each of the
examples of data given. Each data type must
be different [6]
1. Data: 83
2. Data:
[email protected]3. Data: True
Marking Scheme
Data type name: Integer [1]
Data type description: The number is a whole
number [1]
Data type name: String [1]
Data type description: It is a group of characters [1]
Data type name: Boolean [1]
Data type description: The value is True (or could be
False) [1]
Variables and constants
Python does not require any separate
declarations and does not differentiate
between constants and variables.
Programmers need to keep track of and
manage these differences instead
Hint
Output Statements
Output refers to the process of displaying or saving the results of
a program to the user.
Format the output to make it readable and understandable by
the user
For a program to be useful, the user needs to know what results
are being output, so each output needs to be accompanied by a
message explaining the result.
e.g print("Volume of the cylinder is ", volume)
Pseudocode example:
OUTPUT "Hello, ", name
Python example:
print("Hello, ", name)
Input Statements
'User Input' is data or information entered by the user during
program execution.
For a program to be useful, the user needs to know what they are
expected to input, so each input needs to be accompanied by a
prompt stating the input required.
Prompt is a statement required by the user to provide designated
input.
Pseudocode example:
OUTPUT "Enter your name"
INPUT name
Python example:
name = input("Enter your name: ")
Input Output Statements practice
questions
1. Convert a string in to an integer
2. Convert a number in to string
3. Output the words “Hello World”
4. Output the number 20
5. Output the word Hello, then the contents of the variable
name
6. Output the number of balloons stored in a variable
balloon
7. Tell a user to enter a word and store it in a variable
Answers
Concatenation
1. Number= int(“123”) Means joining together. It
2. Value = string(22) joins multiple pieces of data
with a comma
3. Print (“Hello world”)
4. Print (20)
5. Print (“Hello”, name)
6. Print (“There are”, Balloon, “balloons”)
7. Print (“Enter a word”)
input word
Programming Task
3. Select appropriate variables for the items you have identified
that you are going to store
4. Write a program to ask the user to enter each of the items in
turn. Read in each value and store in an appropriate variable
5. Output a message confirming the details that the user has
entered.
Arithmetic operators
MOD
Vs
DIV
Task
Write a pseudocode to find
even or odd number from
the user’s input.
Even or Odd
If a number is evenly divisible by 2 with no remainder,
then it is even. You can calculate the remainder with
the modulo operator % like this num % 2 == 0 .
If a number divided by 2 leaves a remainder of 1, then
the number is odd. You can check for this using
num % 2 == 1 .
Programming Task
1. Find the whole number
after dividing 33 by 7
2.Find the remainder after
dividing 33 by 7
Answers
1. result= DIV(33,7)
2. Result = MOD (33,7)
MOD and DIV are the library
routines
Library routines
A library routine is a block of code (subroutine, procedure,
function etc), often designed to handle commonly
occurring problems or tasks.
Library routines are stored in a program library and given
names. This allows them to be called into immediate use
when needed, even from other programs. They are
designed to be used frequently.
Using library routines make writing programs faster and
easier as part of the work has already been done (and
debugged).
Order of calculations
Programming Task
Write pseudocode for the following
1. Sum of two numbers
2. Subtracting 10 from 20
3. Multiplication of two numbers
4. Dividing 100 by 6
Basic concepts
When writing the steps required to solve a problem,
the following concepts need to be used and
understood:
» sequence
» selection
» iteration
» counting and totalling
» string handling
» use of operators
Sequence
The ordering of the steps in an
algorithm is very important.
An incorrect order can lead to
incorrect results and/or extra steps
that are not required by the task.
Completer the
Trace Table
With test data
25,27,23,999
Trace Table
Identify mistakes and rewrite the pseudocode.
Completer the Trace Table With test data
25,27,23,999
Trace Table
Selection
Selection is a programming concept
that allows you to execute different
sets of instructions based on certain
conditions. There are two main types
of selection statements: IF statements
and CASE statements.
Logical operators
Conditions need logical operators
Each condition using a logical operator result in true
or false.
Logical operators
Boolean Operators
Boolean Operators
If Statements
IF statements allow you to execute a set of
instructions if a condition is true. They have the
following syntax:
IF condition
THEN
instructions
ENDIF
Programming task
Write a pseudocode that
takes a number from the
user and display whether
the number is positive or
negative
IF ELSE Statements
If else statements are used to execute one set of
statements if a condition is true and a different set of
statements if the condition is false. They have the
following syntax:
IF condition
THEN
Instructions
ELSE
Instructions
ENDIF
Programming Task
Write a pseudocode that takes a
number from the user and
display whether the number is
positive or negative using IF
ELSE statements
IF ELSE IF Statements
If else if statements are used to test multiple conditions and
execute different statements for each condition. They have the
following syntax:
IF condition
THEN
Instructions
ELSE IF condition
THEN
Instructions
ELSE
Instructions
ENDIF
Programming Task
Write a pseudocode that takes
a number from the user and
display whether the number is
positive or negative using IF
ELSE IF statements
Programming Task
Write an algorithm using pseudocode that:
Inputs 3 numbers
Outputs the largest of the three numbers
[3]
Answer
INPUT a, b, c
IF a > b AND a > c THEN PRINT a [1]
ELSE IF b > c THEN PRINT b [1]
ELSE PRINT c [1]
Case Statements
CASE statements allow you to execute
different sets of instructions based on the
value of a variable. They have the following
syntax:
CASE OF variable
value1: instructions
value2: instructions
...
OTHERWISE instructions
END CASE
Problem statement
Write a pseudocode using
a SELECT CASE to output a
grade for a test.
Answer
INPUT score
CASE OF Score:
80:
Print (“A”)
75:
Print (“B”)
OTHERWISE PRINT (“u”)
ENDCASE
Programming TASK
Describe what is meant by selection, identify any two
examples of selection
Write a peudocode which ask the user to input a
colour and output a different message if the user
enters the words “yellow”, “green”, “orange”. If
neither of these are entered, the program should
output a different message. Use a CASE statement.
Iteration
What is iteration?
Iteration is the process of repeating a set of instructions
until a specific condition is met. It is an important
programming concept and is used to automate repetitive
tasks.There are three main types of iteration:
» Count-controlled loops (for a set number of iterations)
» Pre-condition loops – may have no iterations
» Post-condition loops – always has at least one iteration.
Count-controlled Loops
A count-controlled loop is used when the number of
iterations is known beforehand
It is also known as a definite loop
It uses a counter variable that
is incremented or decremented after each iteration
The loop continues until the counter reaches a specific value
Example in Pseudocode:
count ← 1
FOR i <= 10
OUTPUT count
NEXT
Pre-condition Loops
A precondition loop is used when the number of iterations is not
known beforehand and is dependent on a condition being true
It is also known as an indefinite loop
The loop will continue to execute while the condition is true and
will stop once the condition becomes false
Example in Pseudocode:
INPUT temperature
WHILE temperature > 37 DO
OUTPUT "Patient has a fever"
INPUT temperature
END WHILE
Postcondition Loops
A post-condition loop is used when the loop must
execute at least once, even if the condition is false
from the start
The condition is checked at the end of the loop
Example in Pseudocode:
REPEAT
INPUT guess
UNTIL guess = 42
Totalling
Totalling involves adding up values, often in a loop
A total variable can be initialised to 0 and then
updated within a loop, such as:
Counting
Counting involves keeping track of the number of
times a particular event occurs
A count variable can be initialised to 0 and then
updated within a loop, such as:
Programming Task
Write an algorithm using
pseudocode that:
Inputs 20 numbers
Outputs how many of these
numbers are greater than 50
Answer
String Handling
Strings are a sequence of characters, such as letters,
numbers, and symbols
They are used to represent text in a computer
program
String handling refers to the various operations that
can be performed on strings
String Handling
Length
The length of a string is the number of characters it contains
In Python, the len() function is used to find the length of a string
Substring
A substring is a portion of a string
In Python, the substring can be obtained using the slicing operator [:]
Upper
The upper() method converts all characters of a string to uppercase
In Python, the upper() method is used to convert a string to uppercase
Lower
The lower() method converts all characters of a string to lowercase
In Python, the lower() method is used to convert a string to lowercase
SUBSTRING
Position of First Character
The first character of a string can be at
position zero or one, depending on the
programming language
In Python and Java, the first character
of a string is at position zero
In Pseudocode, the first character of a
string is at position one
Programming Task
The function Length(x) finds the length of a string
x. The function substring(x,y,z) finds a substring of x
starting at position y and z characters long. The first
character in x is in position 1.
Write pseudocode statements to:
Store the string “Save my exams” in x
Find the length of the string and output it
Extract the word exams from the string and output it
Answer
Cambridge Outline
CAIE outline
Nested Statements
A construct (selection or iteration) that is inside
another construct
Nested statements involve including one statement
within another statement. This can be done with both
selection (if/else) and iteration (for/while) statements
In programming languages like Python, Java, and
Visual Basic, nested statements are often indicated by
indenting the inner statement(s) relative to the outer
statement(s)
Nested Selection
Nested selection is an IF statement inside an IF
statement
If the first if statement is true, it will run the if
statement which is nested inside
Otherwise, it will skip to the "else if" or "else" which
is part of that if statement
Nested Iteration
Nested iteration is useful when we need to perform a
task for a specific range of values
It is important to keep track of the number of nested
statements
It is important to keep nested statements organized
and clear. Use consistent indentation and avoid going
too many levels deep, as this can make the code
difficult to read and understand
Programming task
Write a pseudocode that
count how many numbers
entered are greater than
10 and how many are
equal to 10
Answer
Programming task
Write a pseudocode that
output only the vowels in
a message. Take input if
the user selects option 1
1
Count)
Answers
Use of nested statements
Selection and iteration statements can be nested one
inside the other. This powerful method reduces the
amount of code that needs to be written and makes it
simpler for a programmer to test their programs.
One type of construct can be nested within another –
for example, selection can be nested within a
condition-controlled loop, or one loop can be nested
within another loop.
Programming Task (Page 319-320)
calculate and output highest, lowest, and average
marks awarded for a class of twenty students
calculate and output largest, highest, lowest, and
average marks awarded for each student
calculate and output largest, highest, lowest, and
average marks for each of the six subjects studied by
the student; each subject has five tests.
Assume that all marks input are whole numbers
between 0 and 100
Cambridge Outline
Subroutine
Subroutines
Subroutines
It is a piece of code that has
an identifier and it can be
called from anywhere in the
main program.
Benefits of subroutines
Subroutines make programs easier
to read.
They reduce the duplication of
code.
Complex problems are broken
down into smaller chunks.
Types of subroutines
Procedures
A procedure just executes commands, such
as printing something a certain number of
times.
Function
A function produces information by receiving
data from the main program and returning a
value to the main program.
PROCEDURE
EXAMPLE
DEFINING AND CALLING FUNCTIONS
EXAMPLE
Differences between procedures and
functions
A function uses parameters to
transfer data from the main
program into the function.
A function returns a value to the
main program.
Parameters
These are the variables
sent to functions and
procedures
Task 1: write the call statement
Task 2: Convert to a procedure
Past Paper Question
Marking Scheme
Practice Task
Write a pseudocode that
defines a procedure which takes
two values as firstnumber and
lastnumber and display all the
numbers from firstnumber to
lastnumber
Answer
TRACE THE OUTPUT OF
LOCAL AND GLOBAL
VARIABLES
Memory and Variables
Answers
Library routines
CAIE outline
Creating a maintainable program
Once a program is written, it may need to be
maintained or updated by another
programmer at a later date.
The programmer may have no documentation
other than a copy of the source program.
Even a programmer looking at their own
program several years later may have
forgotten exactly how all the tasks in it were
completed!
A maintainable program should:
» use meaningful identifiers for variables, functions
and procedures
» always use meaningful identifier names for: variables
– constants – arrays – procedures – functions
» be divided into modules for each task using: –
procedures – functions
» be fully commented using your programming
language’s commenting feature.
#Python uses hash to start a comment for every line
Example