0% found this document useful (0 votes)
15 views

Topic 1 Introduction To Programming Revision 202201

The document discusses the program development process which includes defining the problem, developing an algorithm, testing the algorithm, coding the algorithm, and running and documenting the program. It provides details on each step such as using flowcharts to illustrate algorithms and testing algorithms with sample input data before coding.

Uploaded by

Melashri Ramis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Topic 1 Introduction To Programming Revision 202201

The document discusses the program development process which includes defining the problem, developing an algorithm, testing the algorithm, coding the algorithm, and running and documenting the program. It provides details on each step such as using flowcharts to illustrate algorithms and testing algorithms with sample input data before coding.

Uploaded by

Melashri Ramis
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

COURSE LEARNING OUTCOMES

TOPIC 1  CLO1
INTRODUCTION TO PROGRAMMING  Solve programming problems by applying concepts
of problem-solving and structured programming.

 CLO2
 Develop computer programs by using various
structures with relevant algorithms and functions.

References: 2
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

CONTENTS 1.1 PROGRAM DEVELOPMENT PROCESS


 1.1 Program development process 1. Define the problem
o Structured theorem 2. Develop an algorithm (based on step 1)
 1.2 Python built-in (data) types 3. Test the algorithm (for correctness)
 1.3 Constants and variables 4. Code the algorithm (using a specific programming
 1.4 Variable naming convention language)
 1.5 Operators 5. Run the program (on the computer)
 1.6 Expressions and equations 6. Document & maintain the program

3 4

1 DEFINE THE PROBLEM 1 DEFINE THE PROBLEM (Cont’d)


 To help with the initial analysis, the problem should be  INPUT contains all input data to be processed in solving
divided into three separate components: the problem.
 the inputs
 the outputs
 The PROCESS contains all processing:
 the processing steps to produce the required outputs
 A list of actions needed to produce the required outputs.

 The OUTPUT includes all required outputs as designated


by the problem and/or the user.

5 6

1
1 DEFINE THE PROBLEM (CONT’D) 2 DEVELOP THE ALGORITHM
 Example: Shop A is offering a 20% discount for all their  The solution defined in Step 1 is expanded into an
products. Calculate the payment for each customer algorithm.
for his or her total purchase.
 Input – total_purchase  A program must be systematically and properly
 Process: designed before coding begins.
 Input total_purchase
 Calculate payment
 Display payment  This design process results in the construction of an
 Output - payment algorithm.

7 8

WHAT IS AN ALGORITHM? WHAT IS AN ALGORITHM?


 An algorithm is a set of precise steps that describe  An algorithm (instructions) must:
exactly the tasks to be performed and the order in  Be lucid, precise and unambiguous
which they are to be carried out to produce the  Give correct solutions in all cases
desired output from a given input.
 Eventually end
 Be executable one step at a time
 Be complete
 Not assume
 Not skip any steps

9 10

TOOL(S) TO BUILD ALGORITHM FLOWCHART

 Tools used to present algorithms :  A graphic illustration of an algorithm.


 Flowcharts Symbol Function Symbol Function

Start / Stop Connector

Process Flow

Pre-defined
Input / Output process

Decision Off-page
11 12
connector

2
2 DEVELOP THE ALGORITHM (Cont’d) 3 TEST THE ALGORITHM FOR CORRECTNESS
 This step is one of the most important in the
Flowchart development of a program, and yet it is the step most
Start
often forgotten.
discount_rate = 0.20
 The main purpose of desk checking (testing the
algorithm) is to identify major logic errors early, so that
INPUT total_purchase
they may be easily corrected.
payment = total_purchase *
(1 – discount_rate)  Early error identification is better because it will save
time and cost.
PRINT payment

13 14
End

4 CODE THE ALGORITHM INTO A SPECIFIC


3 TEST THE ALGORITHM FOR CORRECTNESS (Cont’d) PROGRAMMING LANGUAGE
 Algorithm testing is also known as desk checking.  Only after all design considerations have been met,
should you actually start to code the program into
 Choose two sets of input for data test cases and test them your chosen programming language (e.g. Python, C,
in the algorithm. C++ , Java, C#, Pascal, MS Visual Basic).
First data set Second data set
total_purchase 5.40 8.00

 Establish test results for each test case.


First data set Second data set
payment 4.32 6.40
15 16

5 RUN THE PROGRAM ON THE COMPUTER 5. RUN THE PROGRAM ON THE COMPUTER (Cont’d)
 This step uses a program compiler and programmer-  Logic errors
designed test data to machine test the code for syntax  These errors are related to logic of the program execution.
errors and logic errors.  Logic errors occur when the code does not run in the way it has
been intended because of the way it is written.
 Syntax errors are any violation of rules of the language  Logic errors can be easy-to-spot blatant mistakes or subtle
results in syntax error. problems that are extremely difficult to spot.
 E.g. A Python print statement for Python version 3.x  E.g. Wrong operations in a mathematical formula to calculate
✘primt “Game over” ✘ print "Game over length of hypotenuse of a right-angle triangle.
✘ Print “Game over” ✔ print ("Game over") ✘ h = math.sqrt(a*a – b*b)
✔ h = math.sqrt(a*a + b*b)
 Syntax: all programming languages have a set of rules on
what is, and is not allowed when forming a line of code. In
other words, all programming languages have a ‘grammar’.
17 18

3
6 DOCUMENT AND MAINTAIN THE PROGRAM Internal & External Documentation

 Program documentation should not be listed as the last  Internal documentation


step in the program development process, as it is really • Remarks or comments written with the instructions to
an ongoing task from the initial definition of the problem explain what is being done in the program.
• Necessary so that the program can be easily understood by
to the final test result.
another programmer.

 Documentation involves both external documentation


 External documentation
and internal documentation that may have been coded
• Manuals or help menus written about the solutions.
in the program.
• For users of the program.

19 20

STRUCTURED THEOREM STRUCTURED THEOREM (CON’T)


 The structured program theorem is a theorem in  The three ways are:
programming and computer science.  In sequence. Executing (running) one subprogram, and then
executing another subprogram.
 By selection. Executing a subprogram based on a certain
 A computer program can be split into pieces of code that
condition.
do a certain task.
 In repetition. Executing the same subprogram over and over
again.
 According to the structured program theorem, these
smaller tasks can be combined in only three ways to get any
larger task done.

21 22

1.2 PYTHON DATA MODEL 1.2 PTYHON DATA TYPES


 All data in a Python program is represented by objects.  The standard type hierarchy
Every object has an identity (you may think of it as the
object’s address in memory), type and value. Types

 Sample Code:
>>> thisnumber=15 Numbers Sequence
>>> id(thisnumber)
140716303246608 Mutable Immutable
>>> type(thisnumber)
<class 'int'>
>>> thisnumber Real
Lists Tuples
Integral Strings
15 (float)

23 Integers Booleans 24
https://docs.python.org/3/reference/datamodel.html#index-0 (int) (bool)
https://docs.python.org/3/library/stdtypes.html

4
TYPE: NUMBERS TYPE: IMMUTABLE (STRINGS)
 Numbers: Integers  Strings
 You can use an integer to represent numeric data, and  Strings are collections of alphabets, words or other
more specifically, whole numbers from negative infinity to characters. In Python, you can create strings by enclosing a
infinity, like 4, 5, or -1.
sequence of characters within a pair of single or double
quotes. For example: 'cake', "cookie", etc.
 Numbers: Boolean
 This built-in data type takes up the value of True or False
 0, [ ], { }, ( ) evaluates to False
 -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 26
such as 1.11 or 3.14.

TYPE: MUTABLE (LISTS) INDEX OPERATOR []


 List  An element in a list or string can be accessed through the
 A list is used to store a collection of heterogenous items index operator.
(same type or different). Lists are mutable (can be
changed), which means you can change their contents  E.g. :
without changing their identity.  mylist[index]
 A list has [ ] square brackets and holds elements, separated  mystring[index]
by commas.
 A Python list’s size is flexible. It can grow and shrink on  Index: a number specifying the position of an element in a
demand. list.
 A list can be empty.  List / String indexes are ranged from 0 to len(myList) – 1.
 Lists are very easy to create. These are some of the ways to
make lists :  Negative indexes identify positions relative to the end of
 emptyList = [ ] the list.
 List1 = ["one" , "two" , "three"]
 Numlist = [1, 2, 3]
 List2 = [1, "two", 3.0] 27 28

TYPE: MUTABLE (LISTS) TYPE: MUTABLE (LISTS)


INDEX OPERATOR INDEX OPERATOR (CON’T)
 Examples : mylist = [5.6, 4.5, 3.3, 13.2, 4.0]  Examples : mystring = "abcd1"
5.6 4.5 3.3 13.2 4.0 "a" "b" "c" "d" "1"
Index from mylist[0] mylist[1] mylist[2] mylist[3] mylist[4] Index mystring[0] mystring[1] mystring[2] mystring[3] mystring[4]
front (left from
to right) front
mylist[-5] mylist[-4] mylist[-3] mylist[-2] mylist[-1] (left to
Index from
right)
back (right
to left) Index mystring[-5] mystring[-4] mystring[-3] mystring[-2] mystring[-1]
from
back
(right
to left)

29 30

5
TYPE: MUTABLE (LISTS) TYPE: MUTABLE (LISTS)
SLICING LIST SLICING
 Slice is a sublist / substring from index start to index  Example:
>>> list1 = [2, 3, 5, 7, 9, 1, 33, 21]
end – 1. >>> list1[2 : 4]
 Syntax : List [start : end] [5, 7]

>>> list1[ : 4]
[2, 3, 5, 7]

>>> list1[3 : ]
[7, 9, 1, 33, 21]

>>> list1[-4 : -2]


[9, 1]

>>> list1[3 : -2]


31 [7, 9, 1] 32

1.3 CONSTANTS AND VARIABLES 1.3 CONSTANTS AND Variables (Cont’d)


 Constants  Variables
• A constant represents permanent data that never • The value of a variable may change during the
changes during the execution of a program. execution of a program.
• E.g. π is a constant. If you use it frequently, you
don’t want to keep typing 3.14159; instead you
can use a descriptive name PI for the value.

33 34

Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA: Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Course Technology/Cengage Learning Course Technology/Cengage Learning

EXAMPLE PROGRAM WITH CONSTANTS AND VARIABLES 1.4 VARIABLE NAMING CONVENTION
# Assign a value to radius  Rules to follow to create legal variable names:
radius = 20 1. A variable name must consist of only letters, digits or
underscores.
# Compute area
PI = 3.14159 # 3.14159 is a constant 2. A variable name cannot contain spaces.
area = radius * radius * PI
3. A variable name must start with a letter or an
underscore. It cannot start with a digit.
# Display results
print("The area for the circle of radius",
radius, "is", area)
35 36

Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Course Technology/Cengage Learning Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

6
1.4 VARIABLE NAMING CONVENTION (Cont’d) 1.4 VARIABLE NAMING CONVENTION (Cont’d)
4. An identifier cannot be a keyword. Keywords, also  Some standards to follow to create good variable names:
called reserved words, have special meanings in Python. 1. Choose descriptive names.
[Refer Appendix 1] - Use score instead of s as the variable name as score
is more meaningful.
5. Uppercase and lowercase characters are distinct. This
means the variable name ItemsOrdered is not the 2. Be consistent.
same as itemsordered.
- Choose either averageMark or average_Mark
and stick to one style all the way.

37 38

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

1.4 VARIABLE NAMING CONVENTION (Cont’d) 1.5.1 OPERATORS (FOR NUMBERS)


3. Keep the length in check. 1. Mathematical operators
- To reduce typo, use score instead of 2. Assignment and Augmented assignment operators
score_of_all_students_in_science_stream. 3. Comparison operators
4. Logical operators

39 40

Reference: Harbour, J. S. (2012). More Python programming for the absolute beginner. Boston, MA:
Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Course Technology/Cengage Learning

MATHEMATICAL OPERATORS MATHEMATICAL OPERATORS (Cont’d)


Operator Description Expression Evaluation  Python expressions are evaluated in the same way as
+ Addition 5 + 2 7 arithmetic expressions.
- Subtraction 5 – 2 3
 Example of how an expression is evaluated:
* Multiplication 5 * 2 10
/ Float division 5 / 2 2.5
// Integer division 5 // 2 2
** Exponentiation 5 ** 2 25
% Remainder 5 % 2 1

41 42

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

7
AUGMENTED ASSIGNMENT OPERATORS COMPARISON OPERATORS
 The operators +, -, *, /, //, % and ** can be Operator Meaning Example Condition Result
combined with the assignment operator (=) to form (radius = 5)

augmented assignment operators. == equal to radius == 0 False


!= not equal to radius != 0 True
Operator Description Example Equivalent
> greater than radius > 0 True
+= Addition assignment x += 5 x = x + 5
< less than radius < 0 False
-= Subtraction assignment x -= 5 x = x - 5
>= greater than or equal to radius >= 0 True
*= Multiplication assignment x *= 5 x = x * 5
<= less than or equal to radius <= 0 False
/= 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 44

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

OPERATOR PRECEDENCE CHART


Precedence Operator Description
LOGICAL OPERATORS ** Exponentiation
n/b: The power operator ** binds less tightly than an arithmetic or
 Also known as Boolean operators. bitwise unary operator on its right, that is, 2**-1 is 0.5 (versus -2**2 is -
4).

 The logical operators not, and, and or can be used to +x, -x, ~x Positive, negative, bitwise NOT
create a composite condition. *, /, //, % Multiplication, division, integer division, and
Operator Description remainder
not logical negation +, - Addition and subtraction
and logical conjunction <, <=, >, >=, ==, !=, is, is Comparison, identity, membership operators
not, in, not in
or logical disjunction
not x Boolean NOT
 Logical operators can be used to combine these and Boolean AND
conditions to form a compound expression. or Boolean OR
=, +=, -=, *=, /=, //=, %= Assignment
45 Associativity: What about priority within the same level? 46

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

OPERATOR NOT OPERATOR AND


p not p Example Condition p1 p2 p1 and Example Conditions
(p: gender = ‘F’) p2 (p1: age = 24, p2: gender = ‘F’)
True False not (gender == ‘F’) is False, False False False (age < 18) and (gender == ‘M’) is
because (gender == ‘F’) is True False, because (age < 18) and (gender
False True not (gender == ‘M’) is True, == ‘M’) are both False
because (gender == ‘M’) is 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

47 48

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

8
1.5.2 OPERATORS (FOR MUTABLE AND IMMUTABLE
OPERATOR OR SEQUENCES)
p1 p2 p1 or p2 Example Conditions
(p1: age = 24, p2: gender = ‘F’) The +, *, and in/not in Operators
False False False (age < 18) or (gender == ‘M’) is False,
because (age < 18) and (gender == ‘M’)
are both False
Operator Description
False True True (age < 18) or (gender == ‘F’) is True, + Concatenate two lists/string
because one of the conditions, (gender == ‘F’)
is True
* Replicate elements in a list/string
True False True (age > 18) or (gender == ‘M’) is True, in Return True if element is in a list/string
because one of the conditions, (age > 18) is
True
not in Return True if element is not in a
True True True (age > 18) or (gender == ‘F’) is True,
list/string
because (age > 18) and (gender == ‘F’)
are both True
49 50

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

THE +, *, AND IN/NOT IN OPERATORS THE +, *, AND IN/NOT IN OPERATORS


Example : Example :
>>> 10 in [1,2,10]
>>> list1 = [2, 3] True
>>> list2 = [1, 9]
>>> list3 = list1 + list2 >>> 's' in ['S','s']
>>> list3 True
[2, 3, 1, 9] >>> 'S' in ['s','n']
False
>>> list4 = 3 * list1
>>> 'S' not in ['s','n']
>>> list4
[2, 3, 2, 3, 2, 3] True
51 52

1.6 EXPRESSIONS AND EQUATIONS 1.6 EXPRESSIONS AND EQUATIONS (Cont’d)


 An expression represents a computation involving  You can use a variable in an expression.
values, variables and operators that, taken together,
evaluate to a value.  A variable can be also used on both sides of the equal sign
(=). For example, y = x + 1.
 An equation is an assignment statement, that assigns
a value to a variable. The equal sign (=) is used as the  To assign a value to a variable, the variable name must be
assignment operator. The syntax for an equation is as placed to the left of the assignment operator. Thus, the
follows: following statement is wrong:
x + 1 = y # Wrong
variable = expression
53 54

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

9
1.6 EXPRESSIONS AND EQUATIONS (Cont’d) PYTHON EXPRESSIONS
 Example assignment statements:  Example arithmetic expression:
x = 5
3 + 4𝑥 10 𝑦 − 5 𝑎 + 𝑏 + 𝑐 4 9+𝑥
y = x + 1 − + 9( + )
5 𝑥 𝑥 𝑦

• Explanation:
which can be translated into a Python expression as:
5 is assigned to x.
(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)
The result of x + 1 is assigned to y after the
statements are executed. Thus, 6 is assigned to y.

55 56

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

PYTHON ASSIGNMENT STATEMENTS PYTHON ASSIGNMENT STATEMENTS (Cont’d)


 Example assignment statement 1:  Example assignment statement 2:
F −𝑏 ± 𝑏 2 − 4𝑎𝑐
P= 𝑥=
1+r n 2𝑎

which can be translated into two separate Python assignment


which can be translated into a Python assignment
statements as:
statement as:
x1 = (-b - math.sqrt((b**2)-(4*a*c))) / (2*a)
P = F /(1.0 + r)**n
x2 = (-b + math.sqrt((b**2)-(4*a*c))) / (2*a)

Note: the statement import math has to be included in


57 order to use math.sqrt. 58

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

PYTHON ASSIGNMENT STATEMENTS (Cont’d) APPENDIX 1: PYTHON KEYWORDS


 Example assignment statement 3: Python Keywords
𝐴 = 𝜋𝑟 2 and else in return
as except is True
assert False lambda try
which can be translated into a Python assignment
break finally None while
statement as:
class for nonlocal with
A = math.pi * r**2 continue from not yield
def global or

Note: the statement import math has to be included in del if pass


elif import raise
order to use math.pi.
[Refer appendix 2]
59 60

Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson Reference: Liang, Y.D. (2013). Introduction to Programming using Python. Boston: Pearson

10
APPENDIX 2: EXAMPLE PROGRAMS
 Program 1: Calculating area of a circle.

 Output:

61

11

You might also like