15-112 Lecture 3 (Wednesday, May 22, 2013)

File Input

Sometimes we want to read data from files or write data to files. In practice, this can become very tangled. But, fundamentally, it is simple.

Let's create a file called, "input.txt" as below:


  one
  1
  2
  two
  

And, given "input.txt", let's take a look at the example below:


#!/usr/bin/python

inputfile = open ("input.txt")

line = inputfile.readline()
print line                    # (but, nothing to see here)
line = inputfile.readline()   # (or here)
print line

line = inputfile.readline()
print line,                   # NOTICE THE COMMA HERE 
line = inputfile.readline()   # AND THE COMMA HERE
print line,

inputfile.close()
  

And, pay attention to its output:


  one

  1

  two 
  2
  

What are the take-aways?

File Output

Writing to a file is very similar to reading from a file. Notice, though, the added argument to "open", specificaly, the "w". We are now giving open the name of the file -- and asking it to allow us to write to it.

Notice also the "\n". The is called the "New line escape character". It is a way of asking the system to insert a new line, like hitting enter, at that point.


#!/usr/bin/python

outpfile = open ("outfile.txt", "w")
outfile.write("Hello world!\n")
outfile.write("Hello great, wonderful world!\n")
outfile.close()
  

The file we created is shown below. We can view it, for example, via "more outfile.txt" from the command prompt.


Hello world!
Hello great, wonderful world!
  

Decision Making

Let's consider the code below:


#!/usr/bin/python

number = int(raw_input("number> "))
if (number > 5):
  print "Number is greater than 5."
print "Done!"


number = int(raw_input("number> "))
if (number > 5):
  print "Number is greater than 5."
else:
  print "Number is less than or equal to 5."
print "Done!"


number = int(raw_input("number> "))
if (number > 5):
  print "Number is greater than 5."
elif (number < 5):
  print "Number is less 5."
else:
  print "Number is equal to 5."
print "Done!"


word = raw_input ("word> ")
if (word == "hello"):
  print "Hello, back to you."
print "Done!"

word = raw_input ("word> ")
if (word != "hello"):
  print "Um, hi?"
print "Done!"
  

What are the take-aways?

Loops

Often times we want to do something more than once, until some condition is met. This is done with a "while loop", which is much like an automatically restartign "if statement". Essentially, it is structured like an "if statement", but loops back to the beginning, until the predicate is false. Since, like an "if statement", the predicate is tested before the body, if it is initally false, the body is never executed.

It is also very important that they body of the loop (or something) leads to the predicate eventually becoming false. Otherwise the loop will never end. Sometimes we do want "infinite loops" -- but these are very rarely a good thing. Usually they are a symptom of an unintended bug.

Let's see a few examples:


#!/usr/bin/python

index = 0
while (index < 10):
  print index
  index = index + 1

print ""

index = 0
while (index <= 10):
  print index
  index = index + 2

print ""

index = 10
while (index > 0):
  print index
  index = index - 2

#
# Infinite Loop below -- Caution
# See the problem? Note the predicate, the initial value of "index", and 
# how it is being changed with each iteration.
#
#print ""

#index = 10
#while (index <= 10):
#  print index
#  index = index - 2

  

Functions and Code Reuse

We've already made use of "functions" such as "len()". Now, let's take a deeper look and learn to write our own. Funtions are a way of taking a chunk of code, giving it a name, and clearly designating what inputs the code requires and what the resulting value is.

By creating functions from complex or reused code, we can make our programs more maintainable and more readable. If we have long, complex code, it can distract from the "Big picture" logic. To combat this, we can give it a meaningful name and "factor it out" into a function. Then, the detail is tucked away in the function, and the algorithmic, big-picture part of the code is clearer. It is like putting all of the tables and reference data at the back of a book, in an appendix, rather than in-line each and every time it is used.

And, if we have code that is used in mmore than one place, using functions enables us to write it only once and to "call" it from each use. this makes our program smaller. It means we have to type less, and it means that, if we ever need to revise the code, we only need to change it in one place -- rather than go hunting.

Let's see an example:


#!/usr/bin/python

def boxvolume(height,width,depth):
  volume = (height * width * depth)
  return volume

print "The volume of a 2x6x9 inch box is ",
print boxvolume(2,6,9),
print "cubic inches"

  

What are the take-aways?

  • Functions begin with "def", short for "define"
  • Like other Python constructs with bodies, they use a ":" and reply upon careful indention
  • "Return" is used to designate the value to which the function will evaluate when called. Once the program his a return, the function ends and is evalauted to the designated value
  • Functions must be defined before they are used