Homework 7 (Python 2) -- solutions

17 Dec 2011

1

Write a program that, given a filename on the command line, prints each line of the file preceded by the line number.

Solution:

import sys

filename = sys.argv[1]
file = open(filename)

line_number = 0
for line in file:
    line_number = line_number + 1
    # Use end='' to tell the print function not to go to the next line
    # (because line already ends with a newline)
    print(line_number, line, end='')

This pattern is common enough that Python has a built-in function, enumerate, that takes a file (or any iterable object) as input, and returns another object that you can iterate through using a for-loop, which provides a count of the item you're currently on (starting from 0), as well as the original items. Here's the program using that function, as well as a fancier string formatting method:

import sys

filename = sys.argv[1]
file = open(filename)

for num, line in enumerate(file):
    print('{0} {1}'.format(num + 1, line), end='')

2

Write a "guess the number" program that chooses a random number in the range from 1 to 100, and then has you guess a number until you find the chosen value. After each guess it should tell you if you're too high or too low.

One way to write the program involves a new kind of loop, a while loop, that repeats the body until some condition fails. Using this loop, an outline of your program would look like:

   import random

   target = random.randint(1, 100)
   guess = -1  # initialize to something wrong

   while guess != target:  # this repeats the body until you guess right
       guess = ... (read the guessed number and convert to an int)
       if ... (test to see if it's too high or too low)

   # if you make it past the loop, you've guessed right.
   print('Good guess!')

Solution:

import random

target = random.randint(1, 100)
guess = -1  # initialize to something wrong

while guess != target:  # this repeats the body until you guess right
    guess = int(input('Guess: '))
    if guess > target:
       print('Too high!')
    if guess < target:
       print('Too low!')

# if you make it past the loop, you've guessed right.
print('Good guess!')

Here's another version that makes sure that you actually type a number. This uses exception handling, for which Python provides a special statement (a try block). If an error occurs in the try block, other blocks can try to handle the error.

import random

target = random.randint(1, 100)
guess = -1  # initialize to something wrong

while guess != target:  # this repeats the body until you guess right
    try:
        guess = int(input('Guess: '))
    except ValueError:
        print("I didn't understand your guess.")
    else:
        if guess > target:
           print('Too high!')
        if guess < target:
           print('Too low!')

# if you make it past the loop, you've guessed right.
print('Good guess!')