Programming Fundamental Notes
Programming Fundamental Notes
Programming Fundamental Notes
In each subsequent unit of this course, we will be learning about the structure,
grammar, and vocabulary of the Python programming language. Python is an
interpreted language that is object-oriented. Python is actually a relatively recent
language in that it was first developed in 1991. Other programming languages, such
as Fortran, are much older. Fortran was developed by IBM in 1958. The BASIC
programming language was developed in 1964 and Cobol was developed in 1959.
One item that is a part of this history is origin of the concept of a computer bug. As
you will learn in this unit, a computer bug is a defect in coding of a software program
that makes the program operate incorrectly or fail. The process of eliminating
problems or errors in a program is known as ‘debugging’.
Input (Get
data)
Repetition
Output
(perform
(Display
repeated Type of data)
action)
Basic
Instructio
n
print('Hello
World!')
print
statement
Display a
result on a function
screen
Addition +
XOR,bitwise
Subtraction -
operator ^
Arithmetic
Operator
Exponentiation Multiplification
** *
Divide /
Integer
(int)
Values &
Types
Floating-
point
String (str)
number
(Default)
Natural Language
Formal Language (Differences with
Formal)
This is @ well-structured
Engli$h sentence with invalid
ful of idiom & methaphor
t*kens in it. This sentence all
( literalness)
valid tokens has, but invalid
structure with.
structure of formal laguage
Debugging
Track down
programming error
Summary:
Assignment statement = A line of code create new variables & give it value
State Diagram Example ( show what state/value each variable is in)
Assignment
Statement
Can't use
Python Refer a value
keyword as to a name
variable name
Variable
Variable
Variable
name can't
name can't
contain illegal
begin with
character,
number
i.e., @
Expression(va
lue+variable+
operator)
n+25 (val
n
+varia +
(variable)
operator)
Python Mode
Interactive Script
Mode Mode
Interact directly with
Code is save in script
Python interpreter
No need print
Interpreter run in
statement/return
script mode to
statement to display
execute the script
result
Need print
statement/return
statement to display
result
(3) M&D *
&/
Function takes argument[value inside the parantheses] & returns a result [value]
Import Python built-in Module to use the functions in it (radian, exponential, sin, cos,
log,sqrt…):
I.e
.
math log10(100)
Function or Method
module Dot. Notation
1st line is header [start with def & end with :] & the rest is body [Must be indented]
To end the function, enter an empty line at the end
Function is an object
Variable defined inside function is local variable & can’t be detected / used outside
the function. The local variable will be destroyed after program halted inside
function.
Other important topics covered in this unit include keyboard input and the integer
operators for floor division (//) and modulus (%).
Divide 2 nums % round down to an integer Divide 2 nos. and return the remainder
If x % y = 0, mean x is divisible by y
Boolean Expression (True / False)
and
Logical
Operator
not or
** Python is not strict, any non-zero number is interpreted as True when without the logical
operator and operands.
Compound statement:
Condition Execution: -Ability to check conditions & change the behaviour of program.
If x <0:
Alternative Execution:
Chained Conditionals:
For more than 2 possibilities which need more than 2 branchoes
elif statement (else if)
Nested Conditionals:
if x == y:
else:
if x < y:
else:
Recursion :
def countdown(n):
if n <= 0:
print('Blastoff!
else:
print(n)
countdown(n-1)
In-built function “input” enable program to stop & wait for user to input/type sth
before continuing
For example: name = input('What...is your name?\n')
Recursion
Condition
Nested
Exec. (if)
Unit
3
Chained Alternative
Exec. Exec. (else)
(elseif)
Summary:
This unit covers techniques for using functions with return values to deal with
complexity. Boolean functions can be used to encapsulate complex tests, where the
functions can be used in conditional statements. Composition is the technique
where a function builds up a complex return value by calling simpler functions. The
idea of composition can be applied to recursion to perform interesting
computations.
Temporary variable:
Dead Code:
Code after a return statement or any other place the flow of execution can
never reach
Absolute value:
Boolean Functions:
Leap of Faith:
When you use built-in function without knowing its flow of execution
Checking Types
Chapter 7 - Iteration
Chapter 8 - Strings
Iteration is a strategy often used in algorithms, which are general processes for
solving categories of problems. One algorithm presented in this unit, for example,
searches a string for a particular letter.
In addition to looping through strings, other string functionality covered in the unit
includes string slices, which specify parts of strings, and string methods, which are
useful functions that are associated with a string variable.
Reassignment:
Break statement:
while True:
if line == 'done':
print(line
While
Statement
Iteration
Recursion For loop
While statement
Algorithms:
To include chap 8
>>> letter
'a'
returns quantity of
characters in a string, i.e.,
len('banana') = 6
Select each character in the string and perform action till the end of the string
Unit 6 (Lists)
Chapter 10 – Lists
This unit covers Python lists, which have similarities and differences with strings. Like
strings, lists are sequences, they can be traversed with for loops, they have a slice
operator (“[]”), and they have many useful methods. Unlike strings, lists can store
more than just characters, including other lists. And lists are mutable; the elements
in a list can change.
List:
>>> numbers[1] = 5
>>> numbers
[42, 5]
1 is the index in numbers [1], meaning 2 nd element inside the list ‘numbers’, for -1
index, it means the last element inside the list, -2 is the 2 nd last element & so forth.
Traverse a list (to iterate/read through each element in the list) – Using For Loop
print (number)
Length of ['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]] is 4. [1,2,3] also
counted as 1 element as it is a nested list
List Operation:
+ operator * operator
['b', 'c']
>>> t[1:3] = ['x', 'y'] #Update 2nd to before 4th elements, assign new value on RHS to
replace
>>> t
append
List
method
sort extend
>>> t.append('d')
>>> t
>>> t1
(iii) sort – arrange elements from low to high or alphabetical (return None if you try to
modify the list)
>>> t.sort()
>>> t
None
List Operation:
Accumulator
Delete Reduce
List
Operation
Filter Map
def add_all(t):
total = 0
for x in t:
total += x
return total
** As loop runs, total add up the sum of the elements, this is called accumulator
(ii) Reduce (reduce the elements into lesser entries)
>>> t = [1, 2, 3]
>>> sum(t)
** sum function in this case is a reduce operation as it combine the no. of elements from 3
to 1
(iii) map – map a function capitalize_all onto each of the elements in a sequence
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
(iv) filter – select only some elements on the list and return a sublist
i.e. take a lists of strings and only returns a list that contains only uppercase strings
def only_upper(t):
res = []
for s in t:
res.append(s)
return res
a) del operator (completely remove value, can return back like .pop() method)
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> t
['a', 'c']
Can remove more than 1 element as well using slice index:
i. >>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> t
['a', 'f']
b) .remove() method – if you know the element but don’t know its position/index
>>> t = ['a', 'b', 'c']
>>> t.remove('b') #remove element, no need specify its location in the
list
>>> t
['a', 'c']
c) .pop method
pop modifies the list and returns the element that was removed. If you
don’t provide an index, it deletes and returns the last element.
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> t
['a', 'c']
>>> x #.pop store and return the removed value
'b'
>>> s = 'spam'
>>> t = list(s)
>>> t
>>> t
Or
>>> s = 'spam-spam-spam'
>>> t = s.split(delimiter) #if specify argument, then for this case will split at “-“ character
>>> t
>>> s = delimiter.join(t)
>>> s
String of different variable but with same character will always refer to same object
Use is operator to check whether variables are referring to the same object:
>>> a is b
True # is operator returns True, means that both string variable A & B refers to the same
object.
** We can say object ‘banana’ is aliased, as this object has more than 1 reference (variables)
connected to it, as shown in stack diagram below:
* * Avoid aliasing with mutable object like list etc. as it is error prone.
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False # List 1 and List 2 are referring to different objects although they are containing the
same element. This prove that list will always create a unique object every time a list is
created without cross-reference to other list variable available like what string variable is
doing.
List argument:
Determine whether the list is modified or a new line list is created when a list is
passed to a function
len(a)~Calc
length of
string
eval(a) -
calculate a.split('-') ~
math Delimit string
expression in between "-"
string
String
Function
a.replace("-",
"*") ~
a[5] ~Extract
Replace -
4th character
with * in
string
a.find("*") ~
Find
character "*"
in string
String slice:
String Method:
upper() – take a string & returns a new find() – find location/index of the character
string with all uppercase letters in string
>>> word = 'banana' >>> word = 'banana'
>>> new_word = word.upper() >>> index = word.find('a')
>>> new_word >>> index
'BANANA' 1
>>> name = 'bob'
>>> name.find('b', 1, 2) # 2nd argument “1”
specify where search should start & 3rd
argument “2” the index before find()
should stop
-1 (result return is -1 as character b not
found between index 1 &2 not found
in operator:
String Comparison:
All the uppercase letters come before all the lowercase letters, A common way to
address this problem is to convert strings to a standard format, such as all
lowercase, before performing the comparison
Chapter 11 – Dictionaries
Chapter 12 – Tuples
Chapter 13 - Case study: Data structure selection (Supplement)
Topics:
A dictionary is a mapping
Looping and dictionaries
Reverse lookup
Dictionaries and lists
Global variables
Tuples are immutable
Tuple assignment
Tuples as return values
Lists and tuples
Dictionaries as tuples
In this unit, you will study two powerful data structures in Python,
the dictionary and the tuple. You will learn how to use each of these types, along
with how to use them together.
Dictionaries (which are implemented as objects) provide a simple way to store data
and retrieve it using an index key. Dictionaries are based on key-value pairs.
The key identifies the data and can be used to store, retrieve, and update the data. It
must be immutable.
The value part of the pair is the actual data, and it can be any type, including a list or
even another dictionary. An example use of a dictionary might be to store the
number of days in a month and retrieve it using the name of the month. For January,
the key would be “January”, and the value would be 31.
Tuples are sequences of values, like lists. Unlike lists and dictionaries, tuples
are immutable. Thus tuples can be keys in a dictionary. Tuples are useful for
assigning multiple values at once, for iterating through multiple lists at once, and for
iterating through the key-value pairs in a dictionary.
Dictionary Intro:
Like a list but its indices are known as keys & can be any value type (indices for list
must be integers)
Contain key-value pair with {} or known as item: {'one': 'uno'} ~ {'key': 'value'}
eng2sp = dict() #making variable eng2sp become dictionary type data using dict()
fxn
similar to list, to call out the value in dict, use [index]
>>> eng2sp #define dictionary
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
>>> eng2sp['two'] #extract value of key ‘two’
'dos'
create 26 variables (A~Z) & Create a list with 26 create a dictionary with
traverse the string elements, convert each characters as keys and
character to a number (using counters as the
the built-in function ord), use corresponding values. The
the number as an index into first time you see a character,
the list, and increment the you would add an item to the
appropriate counter. dictionary. After that you
would increment the value of
an existing item.
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
>>> h = histogram('a')
>>> h
{'a': 1}
>>> h.get('a', 0)
1
Looping key & value pairs in dictionaries:
Global variable:
Variable created outside function belongs to the special frame called _ _main_ _ ,
hence called global variable.
Even if global and local variable with same name has same value, value of global
function won’t be affected. Local function will be deleted once function ends.
Tuple Introduction:
>>> t = ('A',) + t[1:] #Replace the 1st element of tuple with another tupls (‘A’), No error
>>> t
Tuple Assignment:
0a
1b
2c
List of tuples[()] , list of lists [[]] , tuples of tuples (()) , tuples of lists ([])
Comparing tuple vs list vs dictionary
Unit 8 File
Topics:
This unit introduces reading and writing text files in Python. In particular, you will
learn how to read the lines of a text file using a for loop and how to write lines one
at a time. To help with writing, the unit describes an important new use of the “%”
operator, to format text output.
You will also learn how to find files on a computer, along with how to put new files
where you want them, using functions from the os and os.path modules. These
functions navigate the directories (also known as “folders”) of the file system.
Finally, the unit covers how to handle file errors by catching exceptions. You will
learn about try blocks, which allow you to call functions that might raise exceptions
and “catch” those exceptions to deal with the problem.
method
.strip()
1. create a file object, fin associate with a text file named words.txt:
fin = open('words.txt')
2. readline() method to extract line content in words.txt file
>>> fin.readline()
3. strip () method ?? to be further explore
4. Combination of for loop + file object to read & print each word in every line of
Python:
fin = open (‘words.txt’)
for line in fin:
word = line.strip()
print (word)
For loop can be utilise as search pattern too for searching letters & etc..
def has_no_e(word):
if letter == 'e':
return False
return True
**If we find the letter “e”, we can immediately return False; otherwise we have to go to the
next letter. If we exit the loop normally, that means we didn’t find an “e”, so we return True.
-Before this we are just reading the line from text file, to get into the characters in the string.
For loop:
def is_abecedarian(word):
previous = word[0]
for c in word:
if c < previous:
return False
previous = c
return True
While statement:
def is_abecedarian(word):
i=0
return False
i = i+1
return True
Stack Diagrams
Shows value of each variable and the function each variable belongs to (Showing
relationship)
Similar to traceback function which trace the type and source of error in a program
code:
Overall Debugging
3 kinds of error to be debug
Syntax Error
structure & rule
violated
Appear Before
program run
Erro
r
Semantic Error Runtime Error
Program able to run Appear After
Result is not correct program run
How to debug?
Violate
Pre-
condition
Fragmentized
Code Error
Wrong
Violated
usage of
Post
return
condition
value
Common Debug/Avoid
Mistake Method
List is diff. frm string, it will be modified instead
t = t.sort() # WRONG! of returning a new object like string. It will
return None.
s tructs ha p e -p yM
o d ule .txt
Files:
(i) write a file using open function with mode ‘w’ write:
(ii) use write method to put data into the file, argument of write must be string type:
>>> fout.write(line1)
>>> fout.close()
Format operator – to specify the type/format of the data using %:
%d – format as integer
>>> camels = 42
'42'
>>> import os
>>> cwd
'/home/dinsdale'
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
>>> os.path.exists('memo.txt')
True
>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('/home/dinsdale')
True
>>> os.listdir(cwd)
def walk(dirname):
if os.path.isfile(path):
print(path)
else:
walk(path
try:
fin = open('bad_file')
except:
Glossary Unit 1
1. Problem Solving
Process of formulating a problem, find solution & expressing it
2. High level language:
Programming language (i.e., Python) which is easy for human to read &
understand
3. Low level language:
Programming language which is design to be easy for computer to run (machine
language/assembly language)
4. Portability
A property of a program that can run on more than one kind of computer
5. Interpreter
A program that read another program & execute it (i.e., Python 3 read code in
PyCharm IDE & execute it)
6. Prompt
Characters display by interpreter indicating it is ready to take input from user
(i.e., >>> in Python 3 command box)
7. Program
A set of instructions that specifies a computation
8. Print Statement
An instruction to display a value on screen.
9. Operator:
Special symbol for simple computation i.e., mathematical (+ - * / ** ^)
10. Value
Basic unit of data like number / string which program manipulates/use
11. Type
A category of value (int/float/string)
12. Integer
Value type representing whole number
13. Floating-point
Value type represent numbers with fractional parts/decimals
14. String
Value type represent sequence of character
15. Natural language
Language that people speak that evolve naturally (i.e., human language)
16. Formal language
Language that people design for specific purpose (i..e, programming language)
17. Token
One of the basic elements of the syntactic structure of a program, analogous to
a word in natural language
18. Syntax
Rule that govern structure of program (i.e., parentheses () to use print
statement)
19. Parse
To examine a program & analyse structure of program
20. Bug
Error in program
21. Debugging
Process of finding & correcting bugs
Glossary Unit 2
22. Variable
Name that refer to a value (i.e., Nick)
23. Assignment
Statement that assign a value to a variable (i.e., Nick = 10)
24. State diagram
Diagram showing relationship between variables and their values
25. Keyword
Word reserved by Python (i.e., print, if, def) that is used to parse a program
26. Operand
Value which an operator operates on i.e. 2 in 2+1
27. Expression
A combination of variables, operators & values that represent a single result.
28. Evaluate
Simplify an expression by performing operation to yield a single value
29. Statement
A section of code represents a command or an action.
30. Execute
To run a statement & do what It says
31. Interactive mode
Mode of typing code at prompt in Python interpreter
32. Script mode
Mode of using Python interpreter to read code from script & run it.
33. Script
A program stored in a file
34. Order of operations
Rules governing the priority / order in which expressions to be evaluated 1st
35. Concatenate
To join 2 operand end to end (i.e. A+pig = Apig)
36. Comment
Information in a program that is meant for other programmers (or anyone
reading the source code) and has no effect on the execution of the program.
37. Syntax Error:
An error in program that makes it impossible to parse (and therefore impossible
to interpret
38. Exception:
An error that is detected while program is running
39. Semantics
The meaning of a program
40. Semantic error:
An error in program to make it do something other than what the programmer
intended
41. Function:
A named sequence of statements that perform sth useful operation. It
ma/maynot take argument/input or may/may not produce a result.
42. Function definition:
A statement that creates a new function by specifying its name, parameters &
the statements
43. Function object:
The name of the function defined is a variable that refers to a function object.
44. Header:
The 1st line of a function definition
45. Body:
Sequence of statements inside a function definition
46. Parameter:
A name used inside a function to refer to value passed as an argument
47. Function call:
A statement that runs a function with argument list in function’s parentheses.
48. Argument
A value provided to function when it is called which then assigned to
corresponding parameter in the function.
49. Local variable
A variable defined inside a function and can only be used inside function.
50. Return value
The result of function / value of the expression
51. Module:
A file that contains a collection of related functions and other definitions
52. Import statement:
A statement that reads a module file and creates a module object.
53. Module object:
A value created by an import statement that provides access to the values
defined in a module.
54. Dot notation:
Syntax to call a function in another module by specifying the module name
followed by a dot then the function name.
55. Composition
Using an expression as part of a larger expression or a statement as a part of a
larger statement
56. Flow execution
The order statements run in.
57. Stack diagram
A graphical representation of a stack of functions, their variables and the values
they refer to.
58. Frame
A box in a stack diagram that represents a function call. It contains the local
variables and parameter of the function.
59. traceback
A list of the functions that are executing, printed when an exception occurs
Glossary Unit 3
60. Floor division
An operator // divides 2 numbers then round them down to an integer.
61. Modulus operator
% sign operator return the remainder after dividing two integer
62. Boolean expression
Expression with either True or False value
63. Relational operator
Operator that compare its operand with value
64. Logical operator
Operator that combines Boolean expressions (and , or , not)
65. Conditional statement:
Statement that control flow of execution to which branches depends on the
condition set.
66. Condition:
Boolean expression in conditional statement that determine which branches to
run
67. Compound statement
A statement that consists of a header and a body with its header ending with
colon “:” with indented body
68. Branch
One of the alternative sequences of statement in conditional statement
69. Chained conditional:
Conditional statement with a series of alternative branches
70. Nested conditional:
A conditional statement that appear in the body of another conditional
statement
71. Return statement
A function that cause a function to end immediately and return to the caller
72. Recursion
Process of calling the function that is currently executing
73. Base case
A conditional branch inside recursive function that does not make recursive call
74. Infinite recursion
A recursion without base case which will cause runtime error eventually.
Glossary Unit 4
75. Temporary variable
A variable used to store an intermediate value in a complex calculation
76. Dead code
Part of a program that can never run, often because it appears after a return
statement
77. Incremental development
A program development plan intended to avoid debugging by adding and testing
only a small amount of code at a time.
78. Scaffolding
Code that is used during program development but is not part of the final
version (will be removed during final stage when code is mature)
79. Guardian
A programming pattern that uses a conditional statement to check for and
handle circumstances that might cause an error
Glossary Unit 5
80. Reassignment:
Assigning new value to existing variable
81. Update
Assignment that new value of the variable depends on the old
82. Initialization
Assignment that gives an initial value to a variable that will be updated.
83. Increment
An update that increases the value of a variable (often by one)
84. Decrement
An update that decrease the value of a variable
85. Iteration
Repeated execution of a set of statements using either recursive function call or
a loop
86. Infinite loop
A loop which terminating condition is never satisfied
87. Algorithm
A general process for solving a category of problems
88. Object
Something a variable can refer to.
89. Sequence
An ordered collection of values where each value is identified by unique integer
index.
90. Item
One of the values in sequence
91. Index
An integer value used to select an item in a sequence, such as a character in a
string. In Python, indices start from 0.
92. Slice
A part of a string specified by a range of indices
93. Empty string
A string with no characters and length 0, represented by two quotation marks
94. Immutable
Property of a sequence whose items cannot be changed
95. Traverse
To iterate through the items in a sequence, performing a similar operation on
each
96. Search
A pattern of traversal that stops when it finds what it is looking for.
97. Counter
A variable used to count something, usually initialized to zero and then
incremented
98. Invocation
A statement that calls a method
99. Optional argument
A function/method argument that is not required.
Glossary Unit 6
100. List
A sequence of values
101. Element
One of the values in the list (or other sequence), also known as items
102. Nested list
A list contained in another list
103. Accumulator
A variable used in a loop to add up / accumulate a result (i.e., x +=2, accumulate
2)
104. Augmented Assignment:
A statement that update the value of a variable using an operator like +=
105. Reduce:
A processing pattern that traverses a sequence and accumulates the elements
into a single result (i.e., [1,2,3] ~ {6}
106. Map:
A processing pattern that traverses a sequence and performs an operation on
each element
107. Filter
A processing pattern that traverse a sequence and select the elements that
satisfy some criterion
108. Object
Something a variable can refer to. An object has a type (string/int/float..) and
value
109. Equivalent
Having same value
110. Reference:
Association between a variable and its value
111. Aliasing
A circumstances where two or more variables refer to the same object
112. Delimiter
A character or string used to indicate where a string should be split.
Glossary Unit 7
113. Mapping
Relationship where element of one set corresponds to an element of another
set
114. Dictionary
A mapping of key to its values
115. Key-value pair
Representation of the mapping of key to its value
116. Item
Another name for key-value pair
117. Value
An object appears in a dictionary as the second part of a key-value pair
118. Implementation
A way of performing computation
119. Hashable
A type that has hash function. Immutable type like integers, floats and strings
are hashable; mutable type like dictionary and lists are not.
120. Hash function
A function used by hashable to compute location for a key
121. Lookup
A dictionary operation that takes a key and finds the corresponding value
122. Reverse-lookup
A dictionary operation that takes a value and finds one or more keys that map to
it
123. Raise statement
A statement that raises an exception
124. Singleton
A list (or other sequence) with a single statement
125. Call graph
A diagram that shows every frame created during the execution of a program,
with an arrow from each caller to each callee
126. Memo
A computed value stored to avoid unnecessary future computation
127. Global variable
A variable defined outside a function and can be accessed from any function
128. Global statement
A statement that declares a variable name global
129. Flag
A Boolean variable used to indicate whether a condition is true
130. Declaration
A statement like global that tells the interpreter something about a variable
131. Tuple
An immutable sequence of elements
132. Tuple assignment
An assignment with a sequence on the RHS and a tuple of variables on LHS. The
RHS is evaluated and then its elements are assigned to the variables on the left.
133. Gather
The operation of assembling a variable-length argument tuple
134. Scatter
The operation of treating a sequence as a list of arguments
135. Zip object
The result of calling built-in function zip, an object that iterates through a
sequence of tuples
136. Iterator
An object can iterate through a sequence but which does not provide list
operators and methods
137. Data structure
A collection of related values, often organized in lists, dictionaries, tuples and
etc..
138. Shape error
An error caused by a value having the wrong shape, that is wrong type or size