Week 14 agenda and readings -- Python conditionals and files
30 Nov 2011Review questions
Look at the following function:
def f(x): x = 2 * x return x
What are the values of
x
andy
after running the following lines?x = 5 y = f(x)
Write a function that takes a string and a number
n
as input, and prints the stringn
times.Write a function that doubles every entry in a list of numbers.
Use it like the following lines:numbers = [2,3,4] double(numbers) # numbers is now [4,6,8]
Why can you modify the variable within the function like this?
Conditionals
To execute a line only if a condition is met, Python provides an
if
statement. For example, if we have a variable called hour
that contains the current hour of the day, we can say "good morning"
if necessary:
if hour < 12:
print('Good morning!')
We can add an else
statement to print a message for the other
cases:
if hour < 12:
print('Good morning!')
else:
print('Good not-morning!')
If we have a whole sequence of decisions to make, we can
fill in the middle with elif
statements:
if hour > 5 and hour < 12:
print('Good morning!')
elif hour < 18:
print('Good afternoon!')
elif hour < 23:
print('Good evening!')
else:
print('Good night!')
Some common uses for conditionals include:
- Keeping track of the largest or smallest element in a for loop. Try to define functions to find the min or max number in a list.
- Defining piecewise functions. Try to define the
absolute value function using an
if-else
statement.
Files
The open
command opens a file for reading or writing. It returns an object
that represents the file; you can call its methods to get the file contents (or
write to the file if you've opened it for writing).
Here are some examples, assuming you've got Huck Finn saved in your working directory.
huck = open('pg76.txt')
contents = huck.read()
print('The file contains', len(contents), 'characters')
huck.close()
output = open('output.txt', 'w') # creates or overwrites file output.txt
print('This message goes in the file', file=output)
output.close()
Files are automatically closed when your program ends, but it's good practice to use some method to make sure they're closed as soon as possible (so that other programs can use them).
One of the most useful ways to deal with files is to iterate through them line-by-line using a for-loop. File objects work just like lists in this context (they provide the same iterable interface).
There are two special file objects available in all programs through the
sys
module. stdin
is the file object that provides input from the
keyboard (or from a file if input redirection is used on the command line).
stdout
is the file object that is used to write output (this is where
output from the print
function goes by default).
Command line arguments
When we used command line programs earlier in the semester, we typed
a command followed by a number of arguments. We can do the same
with our Python programs. The sys
module has a special variable
called argv
that contains those values. Try running the following
program:
import sys
print(sys.argv)
argv
is just a list of the strings that you typed on the command line.
Exercises
Using Huck Finn again, let's re-create some of the programs we used before:
Create a program that counts the number of lines in the file specified on the command line. So if you type:
linecount FILENAME
, it will print the number of lines inFILENAME
. Create an alternate version that counts the lines fromstdin
if noFILENAME
is specified.Create a program that counts the number of lines containing a particular word. So if you type
wordlines WORD FILENAME
, it will print the number of lines that containWORD
in the fileFILENAME
. Create an alternate version that prints all those lines instead of counting them. Try using this version in a pipeline with yourlinecount
program.Create a program that finds the longest word in a file. Hints:
words = line.split()
will take a line and split it into a list of words.- Break the program up into small functions. Define a function that finds the longest word in a list of words. Then define a function that finds the longest word in the entire file, using the first function.
- For finding the longest word, think about how you defined the
max
function to find the max number in a list. You can find the longest word in almost the same way -- you just need to transform the input in some way.
Readings
Read chapters 5 and 6 in How to Think Like a Computer Scientist: Learning with Python. As usual, do as many exercises as you can.