ENGG1810 Recap

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

Boolean – True/False options

*Use the type() function to get the type or class name of an object

Append Items: append()


• To add an item to the end of the list, use the append() method. list_name.append(‘item_name’)
Insert Items: insert()
• To insert a list item at a specified index, use the insert() method.
list_name.insert(specific_index,‘item_name’)
Remove Items: remove() • The remove() method removes the specified item.
list_name.remove(‘item_name’)
Remove Specific Items: pop()• The pop() method removes the specified item with index.
list_name.pop(specific_index)
To change the value of a specific item, refer to the index number
list_name[specific_index]=‘value_to_update’

Since tuples are also indexed, tuples can have items with the same value. (Allow Duplicate)
We can do the similar thing for accessing tuples like what we did with lists:
 Length using len()
 Access a tuple item using tuple_name[specific_index]
 Slicing using a range of indexes tuple_name[start_index(included),end_index(NOT
included)]
Technically you cannot update it, but there are some tricks!
1) Convert the tuple to a listà2) Do append() or remove()à3) Convert it back into a tuple
A Set is a collection which is unordered, unindexed, mutable, and does NOT allow duplicate values.
Sets are written with curly brackets. {}
A dictionary is a collection which is ordered*, changeable and does not allow duplicates.

Dictionaries are written with curly brackets. {}


Dictionaries are used to store data values in key: value pairs.
It can be referred to by using the key name, and it CANNOT have two items with the same key.

while <condition to iterate>: do something 1 (action1) do something 2 (action2)

break
• With the break statement we can stop the loop even if the while condition is true.
continue
• With the continue statement we can stop the current iteration, and continue with the next

for <variable> in <collection>: do something 1 (action1)


do something 2 (action2)

Dictionaries are used to store data values in key: value pairs.


range(start_num(included), end_num(NOT included), increment_num(default is 1))
 Keyword import to load contents from module sys
 Variable sys.argv to access information provided from terminal • sys.argv[0] – first
argument, name of the program file

Lists or Tuples
items = ['Weekly', 'LabTest1', 'LabTest2', 'FinalExam'] btsv = [18, 8, 16, 45]
emma = [20, 8, 16, 42]
sponge = [10, 4, 14, 35]
Dictionaries
bts_v = {
“Weekly”: 18,
“LabTest1”: 8,
“LabTest2”: 16,
“FinalExam”: 45
}
emma = {
“Weekly”: 20,
“LabTest1”: 8,
“LabTest2”: 16,
“FinalExam”: 42
}
sponge = {
“Weekly”: 10,
“LabTest1”: 4,
“LabTest2”: 14,
“FinalExam”: 35
open(file, mode)
In order to open a file - file filename
- mode mode
There are mainly four mode:
 "r" - Read - Default value. Opens a file for reading, error if the file does not exist
 "a" - Append - Opens a file for appending, creates the file if it does not exist
 "w" - Write - Opens a file for writing, creates the file if it does not exist
 "x" - Create - Creates the specified file, returns an error if the file exists

open(file, mode)
In order to open a file
- file filename - mode mode
read(size)
for reading the content of the file
- size specified size of characters
Can we remove those punctuations? I want to clean it!
Yes, we can use Python RegEx!
 A RegEx (Regular Expression) is a sequence of characters that forms a search pattern.
 RegEx can be used to check if a string contains the specified search pattern.
 Start with Import re
The sub() function replaces the The split() function returns a list where matches with the
text of your choice: the string has been split at each match:

The upper() method returns a string where all characters are in upper case. Symbols and Numbers
are ignored. (You can also try lower() method )
Print(uppercase.split(‘\n’))
The split() function returns a list where the string has been split at each match.
Hence, it returns a list where the object uppercase has been split at each match of ‘\n’

list + list: combine those two lists together

The join()method returns a string by joining all the elements of an iterable (list, string, tuple),
separated by a string separator.
Syntax check in detail!

def <function_name> (<argument-list>): statement 1


statement 2
def is used to create (define) a function
<function_name> is the name you want to call the function.
 􏰨 be lowercase with words separated by underscores
 􏰨 Reflect what the function does e.g. calc_sum, times_table
<argument-list> is the information needed to execute function. Function call must match
function signature

Parameters or Arguments?
The terms parameter and argument can be used for the same thing: information that are passed into
a function.
From a function's perspective:
 􏰨 A parameter is the variable listed inside the parentheses in the function definition.
 􏰨 An argument is the value that is sent to the function when it is called.
Variables that are created outside of a function (so far we learned in the course) are known as global
variables. Global variables can be used by everyone, both inside of functions and outside.
Variables declared inside the function (local variables) can only be used within the function, it is not
accessible outside the function
func (animate): The function to call at each frame.
 􏰨 init_func: A function used to draw a clear frame
 􏰨 frames: iterable, int, generator function
 􏰨 Interval: Delay between frames in milliseconds.
 􏰨 fps: Movie frame rate (per second).
 􏰨 init_func: A function used to draw a clear frame
 􏰨 extra_args: Extra command-line arguments passed to the underlying movie encoder
try:
<statements we intend to do> except <ExceptionName>:
<statements for handling errors>

What is Syntax Error?


Syntax is a set of rules that govern a language.
􏰽􏰞􏰗􏰝􏰐􏰖 􏰤􏰢􏰖􏰖􏰐􏰗 􏰔􏰖􏰗􏰕􏰑􏰘􏰑􏰕􏰗 􏰗􏰝􏰕 􏰔􏰖􏰥􏰗􏰑􏰙􏰤􏰗􏰔􏰐􏰖 􏰔􏰏 􏰗􏰝􏰕 􏰑􏰙􏰜􏰕􏰥 􏰢􏰑􏰕􏰖􏰟􏰗 􏰏􏰐􏰜􏰜􏰐􏰠􏰕􏰓􏱒
01 Syntax Error, 02 Runtime Error, 03 Logical Error
Common Python syntax errors include:
 􏰨 putting a keyword in the wrong place
 􏰨 leaving out a symbol (e.g. colon, comma or brackets)
 􏰨 misspelling a keyword
 􏰨 incorrect indentation
 􏰨 empty block
What is Runtime Error?
If a program is syntactically correct (free of syntax errors), it will be run by the Python interpreter.
The program may exit unexpectedly (a.k.a. it has crashed) during execution if it encounters a
runtime error: a problem which was not detected when the program was parsed, but is only revealed
when a particular line is executed.
Some examples of Python runtime errors:
 􏰨 division by zero
 􏰨 performing an operation on incompatible types
 􏰨 using an identifier which has not been defined
 􏰨 accessing a list element, dictionary value or object attribute
􏰠􏰝􏰔􏰤􏰝 􏰓􏰐􏰕􏰥􏰖􏰟􏰗 􏰕􏱓􏰔􏰥􏰗
 􏰨 􏰗􏰑􏰞􏰔􏰖􏱌 􏰗􏰐 􏰢􏰤􏰤􏰕􏰥􏰥 􏰢 􏰏􏰔􏰜􏰕 􏰠􏰝􏰔􏰤􏰝 􏰓􏰐􏰕􏰥􏰖􏰟􏰗 􏰕􏱓􏰔􏰥􏰗 􏱔􏰤􏰐􏱕􏰕􏰑􏰕􏰓 􏰔􏰖 􏰧􏰕􏰤􏰗􏰙􏰑􏰕 􏱖􏱗

What is Logical Error? (The most difficult to fix)


Logical error occurs when the program runs without crashing, but produces an incorrect result (not
the output that you expect).
The error is caused by a mistake in the 􏰘􏰑􏰐􏱌􏰑􏰢􏰡􏰟􏰥 􏰜􏰐􏱌􏰔􏰤􏱒 􏱘􏰐􏰙 􏰠􏰐􏰖􏰟􏰗 􏱌􏰕􏰗 􏰢􏰖 􏰕􏰑􏰑􏰐􏰑 message,
because no syntax or runtime error has occurred.
Some examples of Python logical errors:
 􏰨 using the wrong variable name
 􏰨 indenting a block to the wrong level
 􏰨 using integer division instead of floating-point division
 􏰨 getting operator precedence wrong
 􏰨 making a mistake in a Boolean expression
 􏰨 off-by-one, and other numerical errors

try:
<statements we intend to do> except <ExceptionName>:
<statements for handling errors> finally:
<statements executed regardless if
the try block raises an error or not>

raise Exception(‘’)

- SyntaxError
- ZeroDivisionError:
- NameError:
- TypeError:
- ValueError:
- RuntimeError
-

import matplotlib.pyplot as plt


Approach 1
Import everything from module_name module
but everything we want must be prefixed with module_name
Use keyword as to replace prefixed module_name with own identifier
from <module_name> import <attribute> as <identifier>

min/max
Find the lowest or highest in an iterable:
abs
Returns the absolute (positive) value of the specified number
round
Round number to ndigits beyond the decimal point.
pow

sum
adds the items of an iterable and returns the sum.
int/float
returns a integer or floating point number from a number or a string.

import math

The math.ceil() rounds a number upwards to its nearest integer


The math.floor() rounds a number downwards to its nearest integer 3
The math.pi

The + operator on NumPy arrays perform an element-wise addition,


while the same operation on Python lists results in a list concatenation.

Numpy data structures perform better in:


 􏰨 Size - Numpy data structures take up less space.
 􏰨 Performance - have a need for speed and are faster than lists
 􏰨 Functionality - have optimized functions such as linear algebra operations built in.
A user-defined prototype for an object that defines a set of attributes that characterize any object
of the class
An individual object of a certain class. An object that belongs to a class Singer, for example, is an
instance of the class Singer.

The built-in __init__() Function


__init__() is always executed when the class is being initiated (so called constructor).
It is for assigning values to instance/object properties, or other operations that are necessary to do
when the instance/object is being created.
The self parameter is a reference to the current instance of the class, and is used to access variables
that belongs to the class.
If the python interpreter is running that module (the source file) as the main program, it sets the
special __name__ variable
to have a ‘_main_’
If this file is being imported from another module, __name__ will be set to the modules name as
value to __name__ global variable.

Series
A Pandas Series is like a column in a table.
It is a one-dimensional array holding data of any type.
DataFrames
A Pandas DataFrame is a 2 dimensional data structure,
like a 2 dimensional array, or a table with rows and columns.
loc attribute to return the specified row(s).

Interpolation is a method for estimating an unknown value between known values.


There are two common interpolation methods:
Linear Interpolation Cubic spline interpolation
import scipy
plot(x, y, z, any options): You can plot 2D or 3D data
 􏰨 x = 1D array-like; x coordinates of vertices.
 􏰨 y = 1D array-like; y coordinates of vertices.
 􏰨 z = float or 1D array-like; z coordinates of vertices; either one for
all points or one for each point.
Test Runner:
This is a command line entry point.
It means that if you execute the script alone by running Python unittest_ex1.py at the command line,
it will call unittest.main(). This executes the test runner by discovering all classes in this file that
inherit from unittest.TestCase.
1. Read the temperature data from csv (Completed)
2. Use moving average as prediction
3. Apply this to predict tomorrow weather!
Note: There are lots of different ways to predict the time-series data. However, the moving average
model is naïve and easy-to-use for predictions and used in a walk-forward manner.
As new observations are made available (e.g. daily), the model can be updated and a prediction
made for the next day.

Calculating a moving average involves creating a new series where the values are comprised of the
average of raw observations in the original time series.
A moving average requires that you specify a window size called the window width. This defines the
number of raw observations used to calculate the moving average value.
The “moving” part in the moving average refers to the fact that the window defined by the window
width is slid along the time series to calculate the average values in the new series.
The most commonly used moving average is ‘Trailing Moving Average’ The value at time(t) is
calculated as the average of the raw observations at and before the time (t)
The most commonly used moving average is ‘Trailing Moving Average’ The moving average value at
time(t) is calculated as the average of the raw observations at and before the time (t)

You might also like