Sei sulla pagina 1di 12

Definition Explanation

Computational
Thinking
It is a mental process aiming at solving a problem by formulating the solution into a
procedure/method.
Algorithm It is a description of the procedure on how one can solve the problem
Programming
language
It is used as a tool to formulate algorithm into a program that a computer can run
Program It is an implementation of an algorithm in a particular language for computers to run
on
Aspects of an
Algorithm
-Provide enough detail to be implementable
-Relies on common sense and the audience
Express an
Algorithm
-Must be unambiguous
-Algorithms is sequential(step by step)
-Branching is making a selection
-Looping is repeating a operation
-Must terminate
Technique to
express
algorithm
-Flowcharts
-Nassi-Schneiderman diagrams
-Pseudo-code
Use of Python -Web Development
-Games
-Scripting in Graphics/Rendering
Characteristic of
python
-simple yet powerful
-readability
-Rapid prototyping
-Interpreted and interactive
-object-oriented python
-High productivity
-build-in resources
-Cross-platform
Interpreted Translates each line of Python instruction into machine code
Interactive Type in Python instruction in a shell which interactively run
Shortcuts in IDLE <ctrl>+<space> Auto complete
<alt>+<p> Recall previous command
<alt>+<n> Back to next command
Machine
Language
-low level language(in bits and byte not human readable)
-machine dependent(created on windows cannot use on Mac)
Complier
approach
Translate is done before execution of the program. The execution is usually faster
for large coding because there no need to do code translation after compiling.
Machine code can be optimized
Interpreter
approach
Translation is done with the execution. Can be interactive better for experiment.
Execution is slower for larger coding purposes. Program can be executed cross
platform.
semantics Meaning of your program
Syntax Specifying algorithm using a programming language
Statement Each line of code in python is a statement. Python interprets and runs statement
one by one. Sensitive to end of line, to continue a statement with the next line.

Comments Comment is indicated with pound sign #. Anything after # is ignored for
interpretation. Helps to improve code readability.
Guidelines:
-Do not repeat the code or explains it. Clarify the intention and explain higher level
concepts
-Use comments to explain noteworthy solution
Keywords Words reserved for specific purpose in the programming language itself. Cannot use
these word to define own stuff
Modules It is a python file containing elements to help working on certain problems. Modules
are resources provided by Python
User Input Input is a built-in function. Prints the message on the screen until a user input and
end with enter. Returns a string whatever is given.
Computation Takes variables and computes an operation and assign the computed value into a
variable
Print Results Print is a built-in function to display related message or data on shell screen
Whitespace To separate words in a statement. Makes the code more readable
Types of white space: Space, tab, return, etc..
Indentation Leading whitespace at a beginning.
Used for grouping flow control, branching, etc.
Make code more readable
Tokens Special elements in a programming language where the interpreter or complier will
identify them when parsing in the program to allow the interpreter or complier to
understand the meaning of your statement
Types of Tokens: Keywords, Operators, Punctuators and Delimiters, Literals
Operators Special character that imply certain operations

Punctuators and
Delimiters
Punctuators aka delimiters that separates different types of elements in Python
statement and expressions
Literals Fixed/plain values in a computer program
Expressions Anything that produces/returns a value. Ignores whitespaces.
Interpreter
Errors
When the interpreter translates Python code into machine language. The first stage
is to determine whether its syntax is valid or not. Syntax error cannot translate the
code
Variable Uses names to make program more readable. Variable are kept in pair of info:

A variable is created when a value is assign for the first time. It associates a name
with a value. We can call this name reference value.
Once a variable is created we can store, retrieve or modify the value associated with
the variable name
Namespace It is a table that contains the association of names with values

Naming
conventions
Dos
-Must begin with a letter or _.
-May contain letters, digits and underscores
-Can be of any length
-Case sensitive
Donts
-start with a digit
Hungarian Notations


Assignment
Operator
Variable = expression
-Evaluate the expression
-Take the resulting value and assign it to a variable in the namespaces

Chained
assignment
a=b=c=d= 0
Swapping two
values
or

Data Type The internal structure of a variable where to the kind of operation can be
performed.
Data Types type: Integers, Floating points, Complex Numbers, Booleans, strings, etc.

Integers/int A value without fractional or decimal components. Unlimited precision.

Float Real number with decimal points. Do not have exact precisions due to the limited
number of bits to store the data in a special format. To check the max or min
representable finite float:

Therefore, computation results with float may not be exact

Complex
Numbers
z=a+bj
The j is to deduce the imaginary part. There is no space before the j.
z.real extract the real part
z.imag extract the imaginary part

Boolean/bool Either True or False. Use for logical operations


String/str It is a collection type. Collection type contains multiple objects organized as a single
object type. String is a sequence delimited by () or () or (.). Strings are
immutable.

Duck-typing Based on the given assigned variable Python will determine the data type based on
the input. Do not need to declare variables. Re-assigning another value can changes
the type of a variable.
Type() Know the type of variable

Data Conversion Converting a value to other type and returning a new value of that type. Must be
compatible and reasonable. Eg. Cannot convert abc to integer.
Conversion operation: int(), float(), str()
Issues of
Arithmetic
Operators
Issue 1: Binary Operators take two values of the same type and return a value of
the same type. Except for division.
Issue 2: Division in Python given 2 integer value the outcome will be a floating
point rather than an integer value. Run time error occurs when an expression try
division by zero (1/0).
Issue 3: Mixed Operations 8/3.0 is mixed operation. Python wil automatically
convert the data into the most detailed result, thus, float (more details but maybe
less precise). Data are implicitly converted
Issue 4: Order of Calculation-

Issue 5: Augmented Assignment- operation shortcut, making the code easier to read

Relational
Operators
Compare two variables and return a boolean (True or False)

Logical Operators Connects the Boolean value and expressions and return a Boolean value

Short-Circuit

Chained
Comparisons

is operator Checks if two variables have the same reference/id number while == compares
values only


Random

Computations are deterministic. Therefore, computer cannot generate TRUE
random but near. This is called Pseudo random
Built-in function These are subroutines, procedures or methods that are built into Python itself. Each
provides a specific functionality.

Comparing
floating point

Computing
Square Root

Branching Selection a computer program dynamically chooses which instruction to be
executed next based on certain conditions. Different instruction can be selected to
run at different time but the program is the same.
Form 1: IF statement
Form 2: IF-ELSE
Form 3: IF-ELIF-ELSE
Form 4: Nested IF Statement(if within an if)
NOTE:
-Colon marks the beginning of a block
-Indentation to define the scope of a block
-Number of whitespaces is flexible but should be consistent for the same level

Important:
-Understand: be able to trace the code in the control flow
-Analysis: Given a problem, analyze the different possibilities and the logic
-Apply: transform the logic into the branch form
-Test: use sufficient test data to evaluate the program with different consequences
Looping Looping can dynamically choose how many times it repeats certain instructions.
Structure of a loop:
-Initialize: loop control variable
-Test: continue the loop?
-Loop body: main computation being repeated
-Update: modify the value of the loop control variable to prevent infinite loop
Types of loop:
-Counter-controlled loop (for loop)- the repetition is known before execution of the
loop body
-Sentinel-Controlled loop (while loop)-the repetition is not known before the
execution of the loop body
While

While loop can be useful to repeatedly ask user for an input until the input fulfills
our requirement
For

Summing a series of data

Nested loop

Keywords


Flow Control Control which instructions to be executed next.

ASCII vs Unicode ASCII stores everything in 8bits while Unicode is an extension of ACSII. It contains
the similar 8bits code of ASCII with addition of another 8bits for other character.

Character
comparison
Comparing index to index and the first difference determines the results

Composite Type A data type which is constructed using primitive or composite type

Primitive Type A data type that are basic building blocks of a program

Data structure Methods of storing data to ease certain operation
Type of data structure: Built-in or User defined

list A sequence of items. Able to contain a mixture of any type. Lists are mutable.





Tuple Immutable list give a data structure with some integrity and permanency. No
accidental changes everything in a tuples works the same as a list except the
declaration method and the modifying of the tuple


Dictionary Used for associative array or associative list. Using a list of pairs of key to a value. It
is a collection but not in sequence. Key is immutable while value is mutable.

Sets It is a collection of object with no two elements the same. There is no order. A set
with no elements are empty sets

functions Functions encapsulate the performance of particular operation so it can be used by
others.
Reason for using function:
Reusable can use again
Sharing others can use
Security- more secure for reuse
Simplify code- more readable

How to write a function
-Does one thing
-Readable
-Reusable
-Complete
-Not too long
Function return Return is a statement indicating the value that is returned by the function. This
statement is optional and a no returned function is called a procedure.
Functions are able to return multiple values as well.

Function
comment
A triple quoted string after the def is called a docstring. Docstring is used to tell what
the function is designed for.
Function
procedure
Procedures are used to perform some duty instead of returning a value
Eg. print output, store data, etc.
Scope It is a set of program statements over which a variable exist. It is about what its
associated value is. Scope means the context, the part of the code, where we can
make a reference to a variable or function.
Multiple scope there are multiple scopes are used for determining a reference
Namespace Namespace is an association of name and object. It looks like a dictionary where we
can call the namespace.
Scope and namespace what namespace we might be using is part of identifying
the scope of the variables and functions.
Type of namespace:
Unqualified function, assignments
Follows LEGB rules
-Local inside the function which is defined
-Enclosing enclosing/encompassing
-Global check global namespace
-Built-in- lastly check the built-in scope
-Else- Error
Qualified namespace : for modules and classes
Local If a variable is assigned in a function then that variable is only available within that
function. Changes to a local variable affect only the local context. Even if the
parameter is mutable. If the variable is assigned locally it cannot be reference before
the assignment.
Global Can cheat using a global keyword in a function to make the variable global
Passing
argument
The passing means the argument and the parameter named in two different
namespaces share an association with the same object. Sharing except for list
When the parameter is assigned to a new value then a new association is created. It
does not affect the object it was previously associated to.
Function
recursion
A function to call itself. Ackermann function is a recursive function which is not
primitive recursive. Primitive recursive is a function that can be implemented using
only do-loops
Stack Stack is a data structure like list or dictionary. It is a sequence which only allows
access to one end of the data and it is the top of the stack.

If a function calls another function the new function is pushed onto the calling stack
and the previous function waits. The top is always the active function. When a pop
occur (end of a function), the function below becomes active.
Modules Modules are files containing collection of code(function ,class)

User defined modules are code which user creates which is useful across many
program.
How to create a user defined module
-moduleName.py
-import moduleName
Modules as script
The code in the module wil be executed as if you imported it.

The code in the if statement will only execute if the file is run as a script
Module path
When importing a module python will search its directory containing in the input
script and then in the list of directories by the environment variable PYTHONPATH. It
is operating system dependent.

File Management A file is a collection of data that is stored on a secondary storage like a disk or a
thumbdrive. Accessing a file means establishing a connection between the file and
the program and moving data between the two.
Types of file
-Text file need to translate. Contain control characters where is generally human
readable. Inefficient storage.
-Binary file do not need to translate. Not readable by human. More efficient
storage.
File object or stream
When opening a file it creates a file object or file stream which is a connection
between the file information and the program. The stream is called a buffer of
information from the file and provides the information to the program

Buffering Reading from a disk is very slow tsk the data from the file object is buffered. Storing
the information of the file in a cache

Current file
positioning
Every file maintains a current file position. It is the current position in the file that
indicates what file will be read next. It is set by the mode table
Os Os module is an interface between the operating system and python language

Exceptions Way to deal with exceptional situation. Try to capture certain situation/failures and
deal with them. Especially bad inputs from users
What is an exception
-Error- display error message
-Events no an error but informative
-Ending condition before closing the program what must be done
-Weird stuff- rare events
Steps of exception:
-Watch
-raise/throw
-handle
-found

Methods to deal with exceptions:
-LBYL Look before you leap
+Cautious
+Check all aspect before executing
+longer length of code
+Not readable
+using if-else statement to handle error
-EAFP-Easier to ask forgiveness than permission
+Run anything
+be ready to clean up errors
+reflects on using try and except
Other try except suite

Potrebbero piacerti anche