Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Topic 1 Introduction To Programming Revision 202305

Uploaded by

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

Topic 1 Introduction To Programming Revision 202305

Uploaded by

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

TOPIC 1

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

COURSE LEARNING OUTCOMES


 CLO1
 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.

1
CONTENTS
 1.1 Program development process
o Structured theorem

 1.2 Python built-in (data) types

 1.3 Constants and variables

 1.4 Variable naming convention

 1.5 Operators

 1.6 Expressions and equations

1.1 PROGRAM DEVELOPMENT PROCESS


1. Define the problem
2. Develop an algorithm (based on step 1)
3. Test the algorithm (for correctness)
4. Code the algorithm (using a specific programming
language)
5. Run the program (on the computer)
6. Document & maintain the program

2
1 DEFINE THE PROBLEM
 To help with the initial analysis, the problem should be
divided into three separate components:
 input
 process
 output

1 DEFINE THE PROBLEM (Cont’d)


 INPUT contains all input data to be processed in solving
the problem.

 PROCESS contains all processing:


 A list of actions needed to produce the required outputs.

 OUTPUT includes all required output as designated by


the problem and/or the user.

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

2 DEVELOP THE ALGORITHM


 The solution defined in Step 1 is expanded into an
algorithm.

 A program must be systematically and properly


designed before coding begins.

 This design process results in the construction of an


algorithm.

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

 Tools used to present algorithms :


 Flowcharts

11

FLOWCHART
 A graphic illustration of an algorithm.

Symbol Function Symbol Function

Start / Stop Connector

Calculation Process Flow

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

payment = total_purchase * (1 – discount_rate)

PRINT payment

13
End

3 TEST THE ALGORITHM FOR CORRECTNESS


 This step is one of the most important in the
development of a program, and yet it is the step most
often forgotten.

 The main purpose of desk checking (testing the


algorithm) is to identify major logic errors early, so that
they may be easily corrected.

 Early error identification is better because it will save


time and cost.

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

 Step 2: Establish test results for each test case.


Variable First data set Second data set
payment 4.32 6.40

15

4 CODE THE ALGORITHM INTO A SPECIFIC


PROGRAMMING LANGUAGE
 Only after all design considerations have been met,
should you actually start to code the program with
your chosen programming language.
 Examples of programming languages:
 Python
 C
 C++
 Java
 C#
 Pascal
 MS Visual Basic

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 errors are resulted from any violation of rules of


the language.
 The first three statements contain syntax errors.
✘ primt “Game over”
✘ print "Game over
✘ Print “Game over”
✔print ("Game over")

 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’.

5. RUN THE PROGRAM ON THE COMPUTER (Cont’d)


 Logic errors
 These errors are related to logic of the program execution.
 Logic errors occur when the code does not run in the way it has
been intended because of the way it is written.
 Logic errors can be easy-to-spot blatant mistakes or subtle
problems that are extremely difficult to spot.
 E.g. The first statement contains wrong operations to calculate the length of
hypotenuse of a right-angle triangle.
✘ h = math.sqrt(a*a – b*b)
✔ h = math.sqrt(a*a + b*b)

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.

 Documentation involves both external documentation


and internal documentation that may have been coded
in the program.

19

Internal & External Documentation

 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.

 A computer program can be split into pieces of code that


do a certain task.

 According to the structured program theorem, these


smaller tasks can be combined in only three ways to get any
larger task done.

21

STRUCTURED THEOREM (CON’T)


 The three ways are:
 In sequence. Executing (running) one subprogram, and then
executing another subprogram.
 By selection. Executing a subprogram based on a certain
condition.
 In repetition. Executing the same subprogram over and over
again.

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

1.2 PTYHON DATA TYPES


 The standard type hierarchy

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.

TYPE: IMMUTABLE (STRINGS)


 Strings
 Strings are collections of alphabets, words or other
characters. In Python, you can create strings by enclosing a
sequence of characters within a pair of single or double
quotes. For example: 'cake', "cookie", etc.

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.

 Negative indexes identify positions relative to the end of


the list.

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

TYPE: MUTABLE (LISTS)


INDEX OPERATOR (CON’T)
 Examples :
mystring = "abcd1”
"a" "b" "c" "d" "1"

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

TYPE: MUTABLE (LISTS)


LIST SLICING
 Example:
>>> list1 = [2, 3, 5, 7, 9, 1, 33, 21]
>>> list1[2 : 4]
[5, 7]

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

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

>>> list1[-4 : -2]


[9, 1]

>>> list1[3 : -2]


[7, 9, 1] 32

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

1.3 CONSTANTS AND Variables (Cont’d)


 Variables
• The value of a variable may change during the
execution of a program.

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

1.4 VARIABLE NAMING CONVENTION


 Rules to follow to create legal variable names:
1. A variable name must consist of only letters, digits or
underscores.

2. A variable name cannot contain spaces.

3. A variable name must start with a letter or an


underscore. It cannot start with a digit.

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]

5. Uppercase and lowercase characters are distinct. This


means the variable name ItemsOrdered is not the
same as itemsordered.

37

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

1.4 VARIABLE NAMING CONVENTION (Cont’d)


 Some standards to follow to create good variable names:
1. Choose descriptive names.
- Use score instead of s as the variable name as score
is more meaningful.

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

1.5.1 OPERATORS (FOR NUMBERS)


1. Mathematical operators
2. Assignment and Augmented assignment operators
3. Comparison operators
4. Logical operators

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

MATHEMATICAL OPERATORS (Cont’d)


 Python expressions are evaluated in the same way as
arithmetic expressions.
 Example of how an expression is evaluated:

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

 Logical operators can be used to combine these


conditions to form a compound expression.

45

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

OPERATOR PRECEDENCE CHART


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

+x, -x, ~x Positive, negative, bitwise NOT


*, /, //, % Multiplication, division, integer division, and
remainder
+, - Addition and subtraction
<, <=, >, >=, ==, !=, is, is Comparison, identity, membership operators
not, in, not in
not x Boolean NOT
and Boolean AND
or Boolean OR
=, +=, -=, *=, /=, //=, %= Assignment
Associativity: What about priority within the same level? 46

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

1.5.2 OPERATORS (FOR MUTABLE AND IMMUTABLE


SEQUENCES)

The +, *, and in/not in Operators

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 :

>>> list1 = [2, 3]


>>> list2 = [1, 9]
>>> list3 = list1 + list2
>>> list3
[2, 3, 1, 9]

>>> list4 = 3 * list1


>>> list4
[2, 3, 2, 3, 2, 3]
51

THE +, *, AND IN/NOT IN OPERATORS


Example :
>>> 10 in [1,2,10]
True
>>> 's' in ['S','s']
True
>>> 'S' in ['s','n']
False
>>> 'S' not in ['s','n']
True
52

26
1.6 EXPRESSIONS AND EQUATIONS
 An expression represents a computation involving
values, variables and operators that, taken together,
evaluate to a value.

 An equation is an assignment statement, that assigns


a value to a variable. The equal sign (=) is used as the
assignment operator. The syntax for an equation is as
follows:

variable = expression
53

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

1.6 EXPRESSIONS AND EQUATIONS (Cont’d)


 You can use a variable in an expression.

 A variable can be also used on both sides of the equal sign


(=). For example, y = x + 1.

 To assign a value to a variable, the variable name must be


placed to the left of the assignment operator. Thus, the
following statement is wrong:
x + 1 = y # Wrong

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 𝑥 𝑥 𝑦

which can be translated into a Python expression as:


(3+4*x)/5 – 10*(y-5)*(a+b+c)/x + 9*(4/x + (9+x)/y)

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

which can be translated into a Python assignment


statement as:
P = F /(1.0 + r)**n

57

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

PYTHON ASSIGNMENT STATEMENTS (Cont’d)


 Example assignment statement 2:
−𝑏 ± 𝑏 2 − 4𝑎𝑐
𝑥=
2𝑎

which can be translated into two separate Python assignment


statements as:
x1 = (-b - math.sqrt((b**2)-(4*a*c))) / (2*a)
x2 = (-b + math.sqrt((b**2)-(4*a*c))) / (2*a)

Note: the statement import math has to be included in


order to use math.sqrt. 58

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

29
PYTHON ASSIGNMENT STATEMENTS (Cont’d)
 Example assignment statement 3:
𝐴 = 𝜋𝑟 2

which can be translated into a Python assignment


statement as:
A = math.pi * r**2

Note: the statement import math has to be included in


order to use math.pi.
[Refer appendix 2]
59

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

APPENDIX 1: PYTHON KEYWORDS


Python Keywords
and else in return
as except is True
assert False lambda try
break finally None while
class for nonlocal with
continue from not yield
def global or
del if pass
elif import raise

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

You might also like