Computer Programming Quarter 1
systematic steps to writing a program:
1. problem analysis: studying the problem to be solved 2. program specification: deciding exactly what the program will do. 3. design: writing an algorithm in pseudocode 4. implementation: translating the design into a programming language 5.testing/debugging: finding and fixing errors in the program. 6. maintenance: keeping the program up to date with evolving needs.
basic assignment statement form
<variable> = <expr>
prompt
>>> indicates the interpreter is ready to accept a command
defining
>>> def example(): this tells Python we are defining a new function and naming it example.
aliasing
A circumstance where two or more variables refer to the same object.
bit
A contraction of "Binary Digit". A bit is the single unit of information in a computer, typically represented as a 0 or 1.
source code
A program in a high-level language before being compiled
portability
A property of a program written in a high level language that makes it able to run on more than one kind of computer as long as there is a suitable compiler or interpreter.
mixed type expression
An expression that contains operands of different data types, like float and int. in these cases, Python automatically converts the int to a float.
byte code
An intermediate language between source code and object code. Many modern languages first compile source code from the module file into byte code and then interpret the byte code with a program called a virtual machine.
Class
An object is built based upon a class. You might think of a class as a general idea of a thing. For example, you can think of the idea of a car without thinking of any specific car. Every actual existing car is an object, but the general idea of a car is a class.
true or false. A Python int is a fixed size.
False, Python ints expand to accommodate whatever value it holds with its only limit being how much memory the computer has on it.
data types
Format of data in a field, such as text, number, or date. the data type of an object determines what values it can have and what operations can be performed on it.
HDD/SDD
HDD: hard disk drive. stores information as magnetic patterns on a spinning disk. SDD: solid state drive. employs electronic circuits known as flash memory.
Property
In our analogy of a computer statement to a grammatical sentence, we might call properties the adjectives in the sentence. For example, consider the sentence "My family's big red house is on the corner." The subject is the house, but almost everything else in the sentence refers to properties of the object. Within that one sentence we know the size, color, location, and owner.
object-oriented (OO) development
Object orientation is not easily defined. It encompasses a number of principles for designing and implementing software. The idea is to view a complex system as the interaction of simpler objects.
Object
Objects are a fundamental concept in modern programming. Most modern programming languages are what is called "object oriented". You are used to dealing with objects in your daily life. Anything you can see or hold or pick up-such as a book, a car, your dog-is an object. In general, anything that is a noun is also an object. So this would include even theoretical concepts such as happiness or sadness.
message
Objects interact by sending each other messages. Messages are simply requests for an object to perform one of its operations.
garbage collection
Releases memory that was used for a variable's value once the variable is no longer to be used by a program.
Point
The simplest object in the graphics module. a point is located by a reference to a coordinate system. Our Point can represent a location in a GraphWin. We define a point by supplying x and y coordinates. The x value represents the horizontal location of the point, and the y the vertical. Traditionally, graphics programmers locate the point (0,0) in the upper left corner of the window. In the default 200x200 GraphWin, the lower right corner has the coordinates (199, 199). drawing a point sets the color of the corresponding pixel in the GraphWin. The default color for drawing is black.
USB memory sticks/DVDs
USB memory stick: a removable, portable form of flash memory DVD: digital versatile discs, which store information as optical patterns that are read and written by a laser
assignment statement
Uses the equal sign to give the object property on the left of the equal sign the value on the right of the equal sign. example: x = 3.9 * x * (1 - x)
comments
Using descriptive text to explain portions of code. Comments do not change the way the program behaves, but are important for the programmer to remember what the code does. they start with a pound (#) sign at the top of the code.
object
You can think of an OO object as a sort of active data type that combines both data and operations. To put it simply, objects know stuff (they contain data), and they can do stuff (they have operations).
statement
a complete command in programming languages
Mantissa and exponent
a computer stores floating-point numbers as a pair of fixed-length (binary) integers. the first represents the string of digits in the value and the second keeps track of where the whole part ends and the fractional part begins (where the "binary point" goes).
loop
a device that tells Python to do the same thing over and over again. the lines underneath the loop heading are the statements that are repeated. this is called the body of the loop.
flowcharts
a diagram that uses boxes to represent different parts of a program and arrows between the boxes to show the sequence of events when the program is running.
invoked (or called)
a function is invoked by typing its name followed by parentheses >>> example()
setCoords
a function within the window object which translates the actual point coordinates into "relative coordinates" based upon the size of the window. By doing this, it allows the "scaling" (making something larger or smaller) of graphics to the window size without having to re-calculate all the numbers. Once you use setCoords for a window, all subsequent graphics drawing is done according to the coordinate system.
library
a module that contains some useful definitions
interpreter
a program that simulates a computer that understands a high-level language. it analyzes and executes source code instruction by instruction as necessary.
machine code
a program the computer can directly execute
module or script
a separate file that programs are usually created by typing definitions into. this file is saved in secondary memory so that it can be used over and over again.
function
a sequence of statements that create a brand new command
algorithm
a step-by-step procedure for solving a problem
variable
a variable is used to give a name to a value so that we can refer to it at other points in the program.
machine language
a very low level language comprised of binary notation, the only thing computer hardware can understand
abs()
absolute value
concatenation
adding two strings of text. >>> "Bat" + "man" 'Batman'
shell
an interactive mode that allows you to type Python commands and then displays the result of executing them.
unsolvable problems
cannot be solved by any algorithm
CPU
central processing unit, the brain of the machine . where all basic operations of the computer are carried out.
parameters (also called arguments)
changeable parts of commands that are placed within parentheses. >>> def greet(person): ... print("Hello", person) which can now be used like this: >>> greet("John") Hello John >>> greet("Emily") Hello Emily >>>
the difference between compiling and interpreting:
compiling is a one-shot translation. once a program is compiled, it can be run over and over again without further need for the compiler or source code. in the interpreted case, the interpreter and the source are needed every time the program runs. compiled programs tend to be faster, but interpreted languages lend themselves to a more flexible programming environment as programs can be developed and run interactively.
compiler
complex computer program that takes another program written in a high level language and translates it into an equivalent program in the machine language of some computer.
constructors
creates a brand new object. general form: <class-name>(<param1>, <param2>, ...)
computer scientists use these techniques of investigation to figure out what can be computed
design, analysis, and experimentation
why is eval dangerous?
eval is dangerous because a user of your program could inject malicious code into it (in what is called a code injection attack) and steal personal information or delete files etc.
you must _____ the _____ when you want a number rather than raw text (a string).
eval, input
instance
every object is an instance of some class
/
float division >>> 10 / 3 3.3333333333333335
Python general form of a for loop
for <var> in <sequence>: <body> the variable after the keyword -for- is called the loop index. it takes on each successive value in the sequence, and the statements in the body are executed once for each value. often the sequence portion consists of a list of values. you can create a list by placing a sequence of expressions in square brackets. >>> for i in [0, 1 , 2, 3]: print(i) 0 1 2 3 >>> for odd in [1, 3, 5, 7, 9]: print(odd * odd) 1 9 25 49 81
when you want to do something in your program a certain number of times, use a for loop with a suitable range. this is a recurring Python idiom you must memorize:
for <variable> in range(<expr>): the value of the expression determines how many times the loop executes. programmers often use i or j as the loop index variable for counted loops.
coordinate transformation
in graphical programming, the mathematics of changing a point or set of points from one coordinate system to a related one. there is a setCoords option for this
string literal
indicated by enclosing the characters in double quotation marks (""). these literals produce strings containing the quoted characters. note that the quotes themselves are not part of the string, they just tell python to create a string.
secure alternative to eval for getting numeric data from users:
int and float. like this: x = int(input("example: ")) any illegal (non-int) inputs will cause the program to crash with an error message, preventing a code injection attack.
//
integer division >>> 10 // 3 3
RAM
main memory in the computer, random access memory. main memory is fast, but volatile. when the power is turned off, it is wiped.
Accesors
methods getX and getY return the x and y values of a point, methods like theseallow us to access information from the instance variables of an object
mutators
methods that change the state of an object
operators
more complex and interesting expressions can be constructed by combining simpler expressions with operators. these are operators: (+, -, * , /, and ** ).
move(dx,dy)
moves the object dx units in the x direction and dy units in the y direction. to move the point p to the right 10 units, we could use this statement: p.move(10,0) this changes the x instance variable of p by adding ten units.
programming languages
notations for expressing computations in an exact and unambiguous way
floating point values (float)
numbers that can have fractional parts
explicit type conversion
performing a type conversion yourself. you can convert, but you can also use the built-in round function since conversion simply discards the fractional part of floats. here is an example for if you want to round to a specific decimal point. >>> pi = 3.14159265358979 >>> round(pi, 2) 3.14 >>> round(pi, 3) 3.142
syntax
precise form
semantics
precise meaning
High level computer languages
precise, but designed to be used and understood by humans
simple template notations showing two forms of the print statement
print(<expr>, <expr>, . . ., <expr>) print() the angle bracket notation is used to indicate slots that are filled in by other fragments of Python code. the name inside the brackets indicate what is missing; expr stands for expression. the ellipses denotes an indefinite series of expressions. the second version of the statement shows that its legal to type a print statement without any expressions to print.
a template for the print statement including the keyword parameter to specify the ending text looks like this:
print(<expr>, <expr>, . . ., <expr>, end="\n") one common use of the end parameter in print statements is to allow multiple prints to build up a single line of output. for example: print("The answer is", end=" ") print(3 + 4) the answer is 7
software
programs
Graphical User Interface (GUI)
provides visual elements like windows, icons, buttons, and menus. Python comes with its own standard GUI model called Tkinter.
%
remainder
strings
sequence of printed characters
method
set of messages an object responds to. If an object is a noun, then a method is a verb. Methods specify what objects can do. For example, if your dog is the object, then methods would be such things as bark, eat, and walk.
meta-languages
sophisticated notations for describing programming languages
control structures
statements like the for loop are called control structures because they control the execution of other parts of the program.
type function
tells us the data type/class of any value
intractable problems
the algorithms that solve these problems take too long or require too much memory to be of practical value
expressions
the fragments of program code that produce or calculate new data values.
data
the information that is stored and manipulated by computer programs
hardware
the physical machine
evaluation
the process of turning an expression into an underlying data type. when you type an expression into a python shell, the shell evaluates the expression and prints out a textual representation of the result. >>> 32 32 >>> "32" '32' in the latter case, Python is actually just storing the characters 3 and 2, not representing the number 32.
Fetch-Execute Cycle
the process the CPU follows. the first instruction is retrieved from memory, decoded to figure out what it represents, and then the appropriate action is carried out. the cycle continues with every other process. fetch, decode, execute.
event driven programming
the program draws a set of interface elements (often called widgets) on the screen and waits for the user to do something. when the user clicks a button, moves a mouse, or presses a key, this generates an event. an event is an object that encapsulates data about what just happened. the event object is then sent to a part of the program to be processed. a press of a button would cause a button event and then the event is sent to the button-handling part of the code which would perform the appropriate action corresponding to that button.
applications programming interface (API)
the set of objects and functions that are provided by a module
a literal
the simplest kind of expression. it is used to indicate a specific value. they represent themselves, ex: 32 represents the number 32.
definite loop
the simplest kind of loop. this kind of loop will execute a definite number of times. that is, at the beginning of the program, Python knows how many times to go around (or iterate) the body of the loop. for example, here is a loop from the chaos program that always executes exactly ten times: for i in range(10): x = 3.9 * x * (1 - x) print(x) this particular loop pattern is called a counted loop, and it is built using a Python -for- statement.
state
the value of an objects instance variables
simultaneous assignment
this is an alternate form of the assignment statement that allows us to calculate several values all at the same time. looks like this: <var1>, <var2>, ..., <varn> = <expr1>, <expr2>, ..., <exprn> this type of assignment statement tells Python to evaluate all the expressions on the right hand side and then assign these values to the corresponding variables named on the left hand side. heres an example. sum, diff = x+y, x-y
pixels
tiny points that make up an image. short for pixel elements
integer data type (int)
values of int type can be positive or negative whole numbers.
clone
variable2 = variable1.clone() you can then move the object around as you wish
how are an objects attributes accessed?
via dot notation.
identifiers
we give names to modules and to the functions within modules. variables give names to values. all these names are called identifiers. every identifier must begin with a letter or underscore which may be followed by any sequence of letters, digits, or underscores. a single identifier cannot contain any spaces. they're also case sensitive.
fundamental question computer science:
what can be computed?
reserved words/keywords
word symbols in a programming language that cannot be redefined in any program. its technically legal to re-define them, but its usually a VERY bad idea.