Web Developer

MIT Python Programming #3

Lesson 3: Common code patterns: iterative programs

Massachusetts Institute of Technology: Introduction to Computer Science and Programming

View the complete course at: http://ocw.mit.edu/6-00F08

Introduction to Computer Science & Programming Class Notes

Data Operations Commands
Numbers + – * / Assignment (Bind a name to a value)
Strings   input/output (Print)
Booleans and, or Conditionals (Branches)
    Loop Mechanisms (While)

Good Programming Style: Use comments. Type discipline (check
types of operands to properly apply correct operations). Descriptive use of good
variable names as a way of documenting code. Testing all possible branches
through a piece of code.

Iterative Programs
How to tackle a program in an iteravie manor?
– Choose a variable thats goint to “count”.
– Initialize outside of loop
– Set up correct end test (includes variable)
– construct block of code properly. (Variable must change or an infinte loop or error will result).
– What to do when I am done? What is the program to do next?

Figure 1.1 Flowchart – Finding a square root of a perfect square.

Python Code Defined

  1. x = 16    (An assignment statement giving the
    value of 16 to X. Value of X could also be defined by user input.)
  2. ans = 0 (Assignment: ans is given a value of 0.)
  3. while ans * ans < = x:    (Loop:  While
    ans * ans is less then or equal to x)
  4. ans = ans + 1     (Conditional:
    redefine ans as being ans + 1)
  5. print ans    (Output: Prints the
    appropriate answer, as the answer to the above Boolean was False.

Note that this program found the square root of 16 to be 5. This is incorrect
unless you are considering the current state of America's economy into the

The following code resolves this problem:

  1. x = 16
  2. ans = 0
  3. while ans * ans < x:   This line has been
    changed to "While ans * ans is less then x)
  4. ans = ans + 1
  5. print ans

This is the correct way to write the code to find the root of a perfect
ans = 0
if x >= 0:
while ans*ans < x:
ans = ans + 1
print 'ans =', ans
if ans*ans != x:
print x, 'is not a perfect square'
else: print ans
else: print x, 'is a negative number'

Simulate code by hand. This ensures it terminates correctly and gives back a
reasonable answer.

Defensive Programming: Make sure all possible paths are in
code, and that useful information is being returned for each branch of code.
Make sure path through code does not loop or result in error.

Two things to consider in defensive programming:

  1. Write the program under the assumption the user will not necessarily
    give the input program requested.
  2. Write the program under the assumption that not only might the user make
    a mistake but that other parts of the program might make a mistake.

Best to use alot of tests to catch something gone wrong then for something to
go wrong and not know.

Exhaustive Enumeration: Walking through all possible values
or factors within equation, testing everything with the very last line being the
only remaining choice, and the correct answer(anticipated result).

For Loop:
for <variable> in <some collection>
Block of Code(instructions)

For Loop Examples:

Without For Loop:

x = 10

i = 1


if x%i == 0:

print 'divisor ',i

i = i+1      —- This states add 1, with no limits
to constructs.

With For Loop

x = 10

for i in range(1, x):    —- This example
defines the exact contents of the constructs.

if x%i == 0:

print 'divisor ',i

Tuple – Ordered sequence of elements.(Instructions)
-immutable (cannot change it)

Example in Phython:
test = (1,2,3,4,5)

Computers start counting at 0.

test [0]        – Returns the number 1 as
the first entry was the number 1.

test [2]        – Returns the number 3

test [10]      – Returns an error, as there are not
11 variables defined within the tuple.

test [-1]       – Returns the number 5 as the
last element is defined as -1


test [1:3]      – Returns 2,3,4          
Select 1 (up to but not including) 3

test [:3]        – Returns 1,2,3           
Select all up to but not including 3

test [2:]        – Returns 3,4,5          
Select 2 up to (not defined so select all)

The above is my personal notes in regards to this class to help me in the learning process.

Note that during the process I “accidentilly(ha ha)” crashed Phython. It seems Python can only handle a infinte loop for so long that increases the square root of x so many times. X was defined initially as 256, then redefined as x * x, (print x), redefined as x * x (print x). That’s what I call bad programming style! : ). Even after I redefined x = 0, it still crashed each time a call for the value of x was requested. It seems that previous assignments of x were kept in cache. Either I am stupid or Phython is stupid, maybe a little of both? (Ha Ha)

  Related Posts