Topic 1 Introduction To Programming Revision 202305
Topic 1 Introduction To Programming Revision 202305
INTRODUCTION TO PROGRAMMING
References:
1. Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA: Course
Technology/Cengage Learning
2. Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
CLO2
Develop computer programs by using various
structures with relevant algorithms and functions.
1
CONTENTS
1.1 Program development process
o Structured theorem
1.5 Operators
2
1 DEFINE THE PROBLEM
To help with the initial analysis, the problem should be
divided into three separate components:
input
process
output
3
1 DEFINE THE PROBLEM (CONT’D)
Example: Shop A is offering a 20% discount for all their
products. Calculate the payment for each customer
for his or her total purchase.
Input: total_purchase
Process:
Input total_purchase
Calculate payment
Display payment
Output: payment
4
WHAT IS AN ALGORITHM?
An algorithm is a set of precise steps that describe
exactly the tasks to be performed and the order in
which they are to be carried out to produce the
desired output from given input.
WHAT IS AN ALGORITHM?
An algorithm (instructions) must:
Be lucid, precise and unambiguous
Give correct solutions in all cases
Eventually end
Be executable one step at a time
Be complete
Not assume
Not skip any steps
10
5
TOOL(S) TO BUILD ALGORITHM
11
FLOWCHART
A graphic illustration of an algorithm.
Pre-defined
Input / Output
process
Off-page
Decision
connector 12
6
2 DEVELOP THE ALGORITHM (Cont’d)
Flowchart
Start
discount_rate = 0.20
INPUT total_purchase
PRINT payment
13
End
14
7
3 TEST THE ALGORITHM FOR CORRECTNESS (Cont’d)
Algorithm testing, also known as desk checking, can be
done as follows:
Step 1: Choose two sets of input for data test cases and test them
in the algorithm.
Variable First data set Second data set
total_purchase 5.40 8.00
15
16
8
5 RUN THE PROGRAM ON THE COMPUTER
This step uses a program compiler and programmer-
designed test data to machine test the code for syntax
errors and logic errors.
Syntax are a set of rules on what is, and is not allowed when
forming a line of code. In other words, all programming 17
languages have a ‘grammar’.
18
9
6 DOCUMENT AND MAINTAIN THE PROGRAM
Program documentation should not be listed as the last
step in the program development process, as it is really
an ongoing task from the initial definition of the problem
to the final test result.
19
Internal documentation
• Remarks or comments written with the instructions to
explain what is being done in the program.
• Necessary so that the program can be easily understood by
another programmer.
External documentation
• Manuals or help menus written about the solutions.
• For users of the program.
20
10
STRUCTURED THEOREM
The structured program theorem is a theorem in
programming and computer science.
21
22
11
1.2 PYTHON DATA MODEL
All data in a Python program is represented by objects.
Every object has an identity (you may think of it as the
object’s address in memory), type and value.
Sample Code:
>>> thisnumber=15
>>> id(thisnumber)
140716303246608
>>> type(thisnumber)
<class 'int'>
>>> thisnumber
15
23
https://docs.python.org/3/reference/datamodel.html#index-0
https://docs.python.org/3/library/stdtypes.html
Types
Numbers Sequence
changeable
Mutable Immutable unchangeable
Real
Integral Lists Tuples Strings
(float)
Integers Booleans 24
(int) (bool)
True and false
12
TYPE: NUMBERS
Number: Integer
You can use an integer to represent numeric data, and
more specifically, whole numbers from negative infinity to
infinity, like 4, 5, or -1.
Number: Boolean
This built-in data type takes up the value of True or False
0, [ ], { }, ( ) evaluates to False. () dictionary [ ] List
-1, 1, 50, 50.1, [1,2] evaluates to True.
Float
"Float" stands for 'floating point number'. You can use it
for rational numbers, usually ending with a decimal figure, 25
such as 1.11 or 3.14.
26
13
TYPE: MUTABLE (LISTS)
List
A list is used to store a collection of heterogenous items
(same type or different). Lists are mutable (can be
changed), which means you can change their contents
without changing their identities.
A list has [ ] square brackets and holds elements, separated
by commas.
A Python list’s size is flexible. It can grow and shrink on
demand.
A list can be empty.
Lists are very easy to create. These are some of the ways to
make lists:
emptyList = [ ]
List1 = ["one" , "two" , "three"]
Numlist = [1, 2, 3]
List2 = [1, "two", 3.0] 27
INDEX OPERATOR []
An element in a list or string can be accessed through the
index operator.
E.g. :
mylist[index]
mystring[index]
Index: a number specifying the position of an element in a
list.
List / String indexes are ranged from 0 to len(myList) – 1.
28
14
TYPE: MUTABLE (LISTS)
INDEX OPERATOR
Examples :
mylist = [5.6, 4.5, 3.3, 13.2, 4.0]
5.6 4.5 3.3 13.2 4.0
Index from
front (left mylist[0] mylist[1] mylist[2] mylist[3] mylist[4]
to right)
Index from
back (right mylist[-5] mylist[-4] mylist[-3] mylist[-2] mylist[-1]
to left)
29
Index
from
front
mystring[0] mystring[1] mystring[2] mystring[3] mystring[4]
(left
to
right)
Index
from
back mystring[-5] mystring[-4] mystring[-3] mystring[-2] mystring[-1]
(right 30
to left)
15
TYPE: MUTABLE (LISTS)
SLICING
Slice is a sublist / substring from index start to index
end – 1.
Syntax : List [start : end]
31
>>> list1[ : 4]
[2, 3, 5, 7]
>>> list1[3 : ]
[7, 9, 1, 33, 21]
16
1.3 CONSTANTS AND VARIABLES
Constants
• A constant represents permanent data that never
changes during the execution of a program.
• E.g. π is a constant. If you use it frequently, you do
not want to keep typing 3.14159; instead you can
use a descriptive name PI for the value.
33
Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Course Technology/Cengage Learning
34
Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Course Technology/Cengage Learning
17
EXAMPLE PROGRAM WITH CONSTANTS AND VARIABLES
Line No Program Code
1 # A program to calculate the area of a circle
2
3 # Input radius
4 radius = float(input("Enter radius : ")) # radius is a variable
5
6 PI = 3.14159 # PI is a symbolic constant
7
8 # Calculate area
9 area = radius * radius * PI # area is a variable
10
11 # Display output
12 print("The area for the circle of radius", radius, "is", area)
35
Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Course Technology/Cengage Learning
36
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
18
1.4 VARIABLE NAMING CONVENTION (Cont’d)
4. An identifier cannot be a keyword. Keywords, also
called reserved words, have special meanings in Python.
[Refer Appendix 1]
37
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
2. Be consistent.
- Choose either averageMark or average_Mark
and stick to one style all the way.
38
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
19
1.4 VARIABLE NAMING CONVENTION (Cont’d)
3. Keep the length in check.
- To reduce typo, use score instead of
score_of_all_students_in_science_stream.
39
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
40
Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Course Technology/Cengage Learning
20
MATHEMATICAL OPERATORS
Operator Description Expression Evaluation
+ Addition 5 + 2 7
- Subtraction 5 – 2 3
* Multiplication 5 * 2 10
/ Float division 5 / 2 2.5
Floor division // Integer division 5 // 2 2
power ** Exponentiation 5 ** 2 25
% Remainder 5 % 2 1
41
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
42
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
21
AUGMENTED ASSIGNMENT OPERATORS
The operators +, -, *, /, //, % and ** can be
combined with the assignment operator (=) to form
augmented assignment operators.
Operator Description Example Equivalent
+= Addition assignment x += 5 x = x + 5
-= Subtraction assignment x -= 5 x = x - 5
*= Multiplication assignment x *= 5 x = x * 5
/= Float division assignment x /= 5 x = x / 5
//= Integer division assignment x //= 5 x = x // 5
**= Exponent assignment x **= 5 x = x ** 5
%= Remainder assignment x %= 5 x = x % 5
43
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
COMPARISON OPERATORS
Operator Meaning Example Condition Result
(radius = 5)
= assignment operator
== equal to radius == 0 False
==comparison operator != not equal to radius != 0 True
> greater than radius > 0 True
< less than radius < 0 False
>= greater than or equal to radius >= 0 True
<= less than or equal to radius <= 0 False
44
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
22
LOGICAL OPERATORS
Also known as Boolean operators.
The logical operators not, and, and or can be used to
create a composite condition.
Operator Description
not logical negation
and logical conjunction
or logical disjunction
45
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
https://docs.python.org/2/reference/expressions.html#id25
23
OPERATOR NOT
p not p Example Condition
(p: gender = ‘F’)
True False not (gender == ‘F’) is False,
because (gender == ‘F’) is True
False True not (gender == ‘M’) is True,
because (gender == ‘M’) is False
47
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
OPERATOR AND
p1 p2 p1 and Example Conditions
p2 (p1: age = 24, p2: gender = ‘F’)
False False False (age < 18) and (gender == ‘M’) is
False, because (age < 18) and (gender
== ‘M’) are both False
False True False (age < 18) and (gender == ‘F’) is
False, because (age < 18) is False
True False False (age > 18) and (gender == ‘M’) is
False, because (gender == ‘M’) is False
True True True (age > 18) and (gender == ‘F’) is
True, because (age > 18) and (gender ==
‘F’) are both True
48
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
24
OPERATOR OR
p1 p2 p1 or p2 Example Conditions
(p1: age = 24, p2: gender = ‘F’)
False False False (age < 18) or (gender == ‘M’) is False,
because (age < 18) and (gender == ‘M’)
are both False
False True True (age < 18) or (gender == ‘F’) is True,
because one of the conditions, (gender == ‘F’)
is True
True False True (age > 18) or (gender == ‘M’) is True,
because one of the conditions, (age > 18) is
True
True True True (age > 18) or (gender == ‘F’) is True,
because (age > 18) and (gender == ‘F’)
are both True
49
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
Operator Description
+ Concatenate two lists/string
* Replicate elements in a list/string
in Return True if element is in a list/string
not in Return True if element is not in a
list/string
50
25
THE +, *, AND IN/NOT IN OPERATORS
Example :
26
1.6 EXPRESSIONS AND EQUATIONS
An expression represents a computation involving
values, variables and operators that, taken together,
evaluate to a value.
variable = expression
53
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
54
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
27
1.6 EXPRESSIONS AND EQUATIONS (Cont’d)
Example assignment statements:
x = 5
y = x + 1
• Explanation:
5 is assigned to x.
The result of x + 1 is assigned to y after the
statements are executed. Thus, 6 is assigned to y.
55
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
PYTHON EXPRESSIONS
Example arithmetic expression:
3 + 4𝑥 10 𝑦 − 5 𝑎 + 𝑏 + 𝑐 4 9+𝑥
− + 9( + )
5 𝑥 𝑥 𝑦
56
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
28
PYTHON ASSIGNMENT STATEMENTS
Example assignment statement 1:
F
P=
1+r n
57
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
29
PYTHON ASSIGNMENT STATEMENTS (Cont’d)
Example assignment statement 3:
𝐴 = 𝜋𝑟 2
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
60
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson
30
APPENDIX 2: EXAMPLE PROGRAMS
Program 1: Calculating area of a circle.
Output:
61
31