Please enable JavaScript.
Coggle requires JavaScript to display documents.
COMP16321: Introduction to Programming I - Coggle Diagram
COMP16321: Introduction to Programming I
Introduction
A program - a set of instructions which perform a specific task
Programming - the process of designing and building a program
Basic instructions
Selection - if this condition is true, perform this action; otherwise do that action
Iteration - Do this action a number of times or Keep doing that until this condition is met
Key steps in programming
Define the output and data flows
Develop the logic to get that output
Write the program
State and Types
5 programming fundamentals
Input
Output
Arithmetic
Conditional
Repetition
States
A simple binary state is a 1 or 0, on or off
Variables
Numbers
Strings
Lists
Dictionaries
Sets
Boolean
Casting is the process of converting one type of variable to another type.
Programming
Assignment ==
Equals =
Core concepts
Selection e.g. crossing the road at a green light
Loops e.g. hammering a nail until it is in the wall
Sequences e.g. morning routines
From concept to program
You have ideas and requirements
Create a flowchart to display the idea
Pseudocode to create a structure
Actual code to build the program
This is algorithmic designs
Flowcharts
Represents an:
algorithm
workflow
process
Used for:
analysing
designing
documenting
Symbols include
terminus
input/output
processing
decision
connectors
flow lines
Iteration
A process wherein a set of instructions or structures are repeated in a sequence of specified number of times or until a condition is met.
Iteration
Infinite loop - repeated forever
Count controlled loops - repeat # times
Condition controlled loops - repeat until condition met
While/For loops
break - causes an immediate exit
continue - jumps to the top of a loop
pass - an empty place holder
else - runs if and only if the loop exists normally
Selection
A selection is a question - an if statement
Statements execute one after the other until you say otherwise
Block and statement boundaries are detected automatically
Blank lines, spaces and comments are usually ignored
Block delimiter: indentation rules
Each set of indentations create a new block of code to be executed
Truth tests
AND, OR and NOT
To Debug
Print
Start with code that already works
Read error messages
Comment out code
Take a break
Error Handling
Syntax errors
A grammatical error such as misspelling, missing punctuation, improperly matching parentheses, incorrect loop and selection format
Semantic errors
Occurs when a computer is asked to do something that it is unable to reliably do
Using a non-initialised variable, errors in expressions, array index out of bounds
Logic errors
A design flaw in the program
Compile Time errors
violates the rules of the language syntax
fixed before the code can be compiled
missing parentheses, printing an undeclared value, missing semicolon
Runtime errors
Occurs during execution
Can be hard to find as the compiler doesn't always point to the error
Pseudocode
A simple version of a programming language written in plain English
This happens before we implement it in a specIfic language -NOT CODE
Capitalise key commands
Write one statement per line
Use indentations
Keep it simple
Be specific
File Handling
Dictionaries vs, Lists
Dictionaries are unordered, fetched by key
Lists are ordered, fetched by positions
Python dictionaries
Accessed by a key
Unordered collection of arbitrary objects
Variable length, heterogeneous and arbitrarily nestable
"mutable mapping" - cannot rely on index
General Operations
create, read, write, delete
Opening a file
"r" Read
default, opens for reading, error if the file doesn;t exist
"w" write
opens a file for writing, creates the file if it doesn't exist
"a" append
opens a file for appending, creates a new file if it doesn't exist
"x" create
creates the specified file, returns error if file exists
Opening a file continued
You can specify if the file should be handles in text or binary mode
text "t"
default value
binary "b"
binary mode e.g. images
Basic Syntax
Writing to a file
f.write("Now the file has more content")
a adds text to the bottom of the file while w overwrites the text in the file
Reading a file
print(file.read())
To open a file it is enough to specify the name:
r and t are default values
file = open("demoFile.txt")
Deleting a file
import OS
os.remove(demofile.txt)
Trace Tables
A technique used to test algorithms, in order to make sure that no logical errors occur while the algorithm is being processed
Commenting
Good code is self-documenting
Documentation comments
for those who want to consume your work but not read through all of it
Clarification comments
for those who maintain, refactor or add to your code
avoid these by simplifying your code
avoid redundant comments
sometimes clarification is still needed, even though the code it good
be helpful to others
Functions
Functions
A block of organized code that is used to perform a single related action
Python gives you many built-in functions
You can create your own functions
Function arguments
4 types
Required
Keyword
Default
Variable-length
Required Arguments
Arguments must be passed in correct, positional order. The number of arguments should match exactly
Keyword Arguments
The caller identifies the arguments by the parameter name
This allows you to skip arguments or place them out of order
Default Arguments
An argument that assumes a default value if a value is not provided
Anonymous functions
They are not declared in the standard manner using the def keywords, but the lambda keyword
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions
It cannot be a direct call to print as it requires an expression
They have their own local namespace and cannot access variables other tan those in their parameter list in global namespace
Appears like a one-line version of a function, not equivalent to inline statements in C or C++
The statement return[expression] exists a function optionally passing back an expression to the caller
Global and Local Variables
Global Variables
accessible from anywhere in the python code
Local Variables
accessible within the function that is initialised for
You can put global in front of a variable to make it more accessible
Lambda Functions
test = lambda a: a+2
print(test(3)) #prints 5
def my_function(num):
return lambda a: a* num
doubles = my_function(2)
print(doubles(20)) #prints 40
Packages and Modules
Python modules
External python files allow for code reuse
Modules should have short, all lowercase names
underscores can be used
must have a .py extension
import keyword incorporates them
Docstring conventions
Documented by using docstring conventions
First statement in a module function, class or method definition
One liners are for very obvious cases
Multiline docstrings consist of a summary line
Docstring processing frameworks generate help information for modules
""" A bunch of functions to validate user input """
help(module_name)
Gives you information on the functionality of the module, but you do not need to know how the function was implemented
Namespaces and dir()
The module is imported into its own namespace when using import
Separate namespaces are food as the avoid name clashes
Uses dot notation
The dir function returns all the names in a given namespace
The import method will import everything, so takes a lot of space
To access the namespace using dot notation
an_int = validate_module.is_integer(user_input)
Modules can be imported using aliases
import validate_module as check
Default items in the namespace are
['
builtins
', '
cached
', '
doc
', '
file
', '
loader
', '
name
', '
package
', '
spec
']
The Global Namespace
We import into the global namespace using from validate_module impiort * instead of import validate_module as check
You should not use import *
It makes code more difficult to read and is likely to cause main conflicts
It bloats the code and slows program performance
It is better to specify what we want to import from the module
Python and the Standard Library
The standard library is very extensive and includes may packages and modules
A package can be thought of as a collection of modules that share a common namespace
Some very powerful non-standard packages also exist and need to be installed using Python's Package Manager
pip install -U scikit-learn
Pass Operation
When executed, nothing happens but it is used as a placeholder for when a statement is required to be syntactically correct but we don't need anything to be executed
tKinter
Graphics and User interaction
Standard GUI library for python
import tkinter
create a main window
add widgets
enter a main event loop to manage triggers
Graphics and animation
The Tk class
The Tk class is used to create a top level window
It is this object that interfaces with the Tk
The Canvas Widget
This allows us to create shapes and text to be placed on the canvas
Two types of coordinate systems
window coordinate system with (0, 0) being the top left
canvas coordinate system which specifies where items are drawn
The General Structure
We import the things we want to use from tkinter
We create a new instance of the Tk() method
We create a canvas
We use the pack geometry manager
The Canvas
On the canvas we can configure
background colour
scroll region
confined scroll region
cursor
height and width
highlight colour
etc.
border
We must provide the bounding box (rectangle coordinates)
canvas.config vs canvas.itemconfig
The configuration of the canvas can be changed using the config method
The items created on the canvas can be configured using the item.config method
To delete an item from the canvas, you can use the canvas.delete method
The coords method
Two purposes
Get the current coordinates of an object
Update the current coordinates of an object
We can change the position of the canvas objects but not directly as they do not have methods, but options which are controlled by the canvas class
Coordinates
Most shapes have 4 associated coordinates
More complex shapes like polygons must have at least 3 vertices
Other objects might use the windows coordinate system i.e.text
The coordinates are stored in a list [x0, y0, x1, y1] (left, top, right, bottom)
To move an object we continually increment the coords value
Moving on the x, y plane is common so there is a canvas.move(object, x, y) method
The sleep method is used to control the speed i.e. sleep(0.02). To increase the speed you can decrease the sleep time
Simple collision detection
We can check if the coordinates overlap
if pos[1] or pos[3] > 400: y = -y #changes direction upon collision
Secure Coding
Regular Expression
RegEx is a sequence of characters that forms a search pattern
It is used to check a string contains the specifies search pattern
RegEx makes validation of input or other text easy
Supported by C++, Java/script, PHP and HTML via import re
Usage
get the sting you want to check, define the conditions and check the string - returning true or false- and perform an action depending on the result
Start of strings
^ is used if we want a string to start with a specific pattern e.g. "^COMP"
Digits
\d is checking for digits
{} allows us to specify the number of occurrences
End of strings
$ used if we want a string to end with a specific pattern
Regular Expression
Building in More Validation
[] can be used to specify a set of characters e.g. [1-4]\d{3}[0-2] or [1234][0-9]{3}[012]
Capture and group with OR (0|1|2)
We can use + to specify one or more of the previous and use * to specify zero or more
\ is used to signal a special sequence
. signifies any character
^ signals that is starts with
$ signals that it ends with
{} signals the specified number of occurences
| shows either or
() signals capture and group
Validating a License Plate
\d returns a match where the string contains digits
\ is an escape character and escapes the d, meaning the d is to be treated as a special sequence
\A returns a match if the specified characters are at the beginning of the string
\b returns a match where the specified characters are at the beginning or at the end of a word
\B returns a match where the specifies characters are present, but NOT at the beginning or end of the word
\D returns a match where the string DOES NOT contain digits
\s returns a match where the string contains a white space integer
\S returns a match where the string DOES NOT contain a white space character
\w returns a match where the string contains any word characters (letter, digit and underscore)
\W returns a match where the string DOES NOT contain any word characters
\Z returns a match if the specified characters are at the end of the string
Other Uses for RegEx
checking vowels and consonants
vowels = re.findall(v_text, ex_text) #returns the number
v_text = "a|e|i|o|u"
not_vowels = "[^aeiou]" #^ is not in this case
position of matches
x = re.search("lazy". "the lazy dog")
x.start is the start position and x.end is the ending
y = re.sub("lazy", "fast", "the lazy dog")
y has the text repeated with the first word replaced by the second
More Validation
You can validate integers without converting to int using regex = "\A\d+\Z" as the validation string
To validate a number within a range CHECK THIS AGAIN
At least number of characters can be done using ^.{8,}$. This is at least 8.
At most number of characters can be done using {,57}, which is a minimum of 1
Between two numbers is {5, 60}
Other secure coding techniques
RegEx is very powerful
Makes validating easy
Catching bad input is one of the goals for ensuring your application is secure
Another requirement of secure coding is readability and consistency of code
Object Oriented Programming
Classes and Methods
Class
Can be thought of as a template
Can be used to create many instances of objects
Variables can be thought of as attributes
Functions are known as methods
Attributes vs Variables
Attributes created within a class are member attributes (normal)
Attributes created outside a class are instance attributes e.g. student_one.name = "Alice"
The Init method
Allows you to set attributes of a class
Known as a constructor method and is automatically calle
Allows you to set the attributes of a class when you create the instance rather than modify later
Other methods
We can access instant attributes directly, but this is discouraged
We should create an interface for the user of our class called getters
Class method call
student.change_surname("Badger")
We can also explicitly call the method using the class name
This time we have to pass the instance as well as the new surname
Student.change_surname(student, "Badger")
Encapsulation
Using a method to change an instance variable
the method approach allows us to validate input if desired
Privatising attributes
self. __variable makes an attribute private
Encapsulation
prevents attributes being accessed directly
methods must be used to change the attributes: setters and getters
allows us to hide the data, attributes and methods
Class attributes
attributes are shared amongst all instances of the class
we can change the variable for all classes e.g. to keep count of the number of instances
Namespaces
When we create an instance of a class, each instance will have its own namespace for the instance variables
The class also has a namespace which contains the class attributes
The instances inherit from the class namespaces
Instance attributes
You can create new instance variables for a specific instance
student.number_of_students = student.number_of_students * 2
Other methods
Class Methods vs Regular Methods
Regular methods within a class automatically take in the instance as the first argument
class methods are not bound to an instance
class methods work with classes an can be used to update attributes
In regular methods, the first parameter is the object, in class methods the first parameter is the actual class
Class methods as constructors
To create a new instance of the student class we use student_one = student("Alice", "Aardvark")
If we wanted to allow "Alice Aardvark" we could use a class method
Static Methods
Like regular functions, included when they have some logical connection with the class
Can't access class or instance variables
Also adds functionality that is related to the class
Inheritance
Inheritance and subclasses
Inheritance allows us to create a new subclass which is everything plus more than the inherited class
This also allows us to override some features of the inherited (super) class
A simple example
class International_student(Student): pass
This shows that this new class is inheriting everything from the student class
You cannot access private attributes from one class to another