< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180025031194137176049106218111004226051068061019249000137

Answers to Selected Exercises

Chapter 2

Q:

Loops and numbers. Create some loops using both while and for.

A:

5. loops and numbers

a)

								
i = 0
while i < 11:
    i = i + 1

							
b)
								
for i in range(11):
     pass

							

Q:

Conditionals. Detect whether a number is positive, negative, or zero. Try using fixed values at first, then update your program to accept numeric input from the user

A:

6. conditionals

								
n = int(raw_input('enter a number: '))
if n < 0:
    print 'negative'
elif n > 0:
    print 'positive'
else:
    print 'zero'

							

Q:

Loops and strings. Take a user input string and display string, one character at a time. As in your above solution, perform this task with a while loop first, then with a for loop

A:

7.

s = raw_input('enter a string: ')

for eachChar in s:
    print eachChar

for i in range(len(s)):
    print s[i]

							

Q:

Loops and operators. Create a fixed list or tuple of 5 numbers and output their sum. Then update your program so that this set of numbers comes from user input. As with the problems above, implement your solution twice, once using while and again with for.

A:

8.

								
subtot = 0
for i in range(5):
    subtot = subtot + int(raw_input('enter a number: '))
print subtot

Chapter 3

Q:

Identifiers. Which of the following are valid Python identifiers? If not, why not? Of the invalid ones, which are keywords?

A:

7. identifiers

40XL   number
$saving$ symbol
print   kw
0x40L   number
big-daddy symbol
2hot2touch number
thisIsn'tAVar symbol
if   kw
counter-1 symbol

Chapter 4

Q:

Object Equality. What do you think is the difference between the expressions type(a) == type(b) and type(a) is type(b)?

A:

6. difference between type(a) == type(b) and type(a) is type(b):

type(a) == type(b) whether the value of type(a) is the same as the value of type(b)… == is a value compare

type(a) is type(b) whether the type objects returned by type(a) and type(b) are the same object

Chapter 5

Q:

Geometry. Calculate the area and volume of

A:

8.

import math

def sqcube():
     s= float(raw_input('enter length of one side: '))
     print 'the area is:', s ** 2., '(units squared)'
     print 'the volume is:', s ** 3., '(cubic units)'

def cirsph():
     r = float(raw_input('enter length of radius: '))
     print 'the area is:', math.pi * (r ** 2.), 
     '(units squared)'
     print 'the volume is:', (4. / 3.) * math.pi * (r **
3.), '(cubic units)'

sqcube()
cirsph()

							

Q:

Modulus. (a) Using loops and numeric operators, output all even numbers from 0 to 20

A:

11.

a.

								
for i in range(0, 22, 2):      # range(0, 21, 2) okay too
    print i

							
OR

								
for i in range(22):            # range(21) okay too
    if i % 2 == 0: print i

							
b.

								
for i in range(1, 20, 2):      # range(1, 21, 2) okay too
    print i

							
OR

								
for i in range(20):            # range(21) okay too
    if i % 2 != 0: print i

							
c.

when i % 2 is 0, it's even (divisible by 2), otherwise it's odd

Chapter 6

1:

Strings. Are there any string methods or functions in the string module that will help me determine if a string is part of a larger string

A:

1.

find(), rfind(), index(), rindex()

							

2:

String Identifiers. Modify the idcheck.py script in Example 6-1 such that it will determine the validity of identifiers of length 1 as well as be able to detect if an identifier is a keyword. For the latter part of the exercise, you may use the keyword module (specifically the keyword.kwlist list) to aid in your cause

A:

2.

import string

alphas = string.letters + '_'
alnums = alphas + string.digits

iden = raw_input('Identifier to check? ')

if len(iden) > 0:
     if iden[0] not in alphas:
         print "invalid: first char must be alphabetic"
     else:
     if len(iden) > 1:
         for eachChar in iden[1:]:
              if eachChar not in alnums:
                  print invalid: other chars must be alphanumeric
              break
         else:
          import keyword
          if iden not in keyword.kwlist:
              print 'ok'
          else:
             print 'invalid: keyword name'

else:
    print 'no identifier entered'

							

Chapter 7

Q:

Creating Dictionaries. Given a pair of identically-sized lists, say, [1, 2, 3, …], and ['abc', 'def', 'ghi', …], process all that list data into a single dictionary that looks like: {1: 'abc', 2: 'def', 3: 'ghi', …}.

A:

4.

# assumes both list1 and list2 are of the same length
dict = {}
for i in range(len(list1)):
    dict[list1[i]] = list2[i]

							
There is a more clever solution using the map() built-in function.

Q:

Inverting Dictionaries. Take a dictionary as input and return one as output, but the values are now the keys and vice versa

A:

7.

list1 = oldDict.values()
list2 = oldDict.keys()
(See solution to problem 4 for the remainder of this solution.)

Chapter 8

Q:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

A:

3a.

								
range(10)

							

Q:

Prime Numbers. We presented some code in this chapter to determine a number's largest factor or if it is prime. Turn this code into a Boolean function called isprime() such that the input is a single value, and the result returned is 1 if the number is prime and 0 otherwise

A:

4.

def isprime(num):
    count = num / 2
    while count > 1:
        if num % count == 0: return 0
        count = count - 1
    return 1

							

Chapter 9

1:

File Access. Prompt for a number N and file F, and display the first N lines of F

A:

2.

file = open(raw_input('enter file: '))
allLines = file.readlines()
file.close()
num = input('enter number of lines: ')
i = 0
while i < num:
    print allLines[i],
    i = i + 1

							
(HINT: 1., 2., 3. can be inspired with outfile.py on p. 38 and p. 245)

2:

Logging Results. Convert your calculator program (Exercise 5-6) to take input from the command-line, i.e.

A:

14b.

								
import sys

print "# of args", len(sys.argv)
print "args:", sys.argv

							

3:

Searching Files. Obtain a byte value (0-255) and a file name. Display the number of times that byte appears in the file

A:

18.

part of this comes from creatext.py on p.247

Chapter 10

1:

Raising Exceptions. Which of the following can RAISE exceptions during program execution? Note that this question does not ask what may CAUSE exceptions

A:

1.

e)

2:

Raising Exceptions. Referring to the list in the problem above, which could raise exceptions while running within the interactive interpreter?

A:

2.

try-except monitors the try clause for exceptions and execution jumps to the matching except clause. However, the finally clause of a try-finally will be executed regardless of whether or not an exception occurred.

Chapter 11

Q:

Default arguments. Update the sales tax script you created in Exercise 5-7 such that a sales tax rate is no longer required as input to the function. Create a default argument using your local tax rate if one is not passed in on invocation

A:

5.

def printf(string, *args):
     print string % args

Chapter 13

Q:

Functions vs. Methods. What are the differences between functions and methods?

A:

2.

Methods are basically functions, but are tied to a specific class object type. They are defined as part of a class and are executed as part of an instance of that class.

Q:

Delegation. In our final comments regarding the capOpen class of Example 13.4 where we proved that our class wrote out the data successfully, we noted that we could use either capOpen() or open() to read the file text. Why? Would anything change if we used one or the other?

A:

15.

It makes no difference whether we use open() or capOpen() to read our file because in capOpen.py, we delegated all of the reading functionality to the Python system defaults, meaning that no special action is ever taken on reads, meaning the same code would be executed, i.e., none of read(), readline(), or readlines() was overridden with any special functionality.

Chapter 14

1:

Callable Objects. Name Python's callable objects

A:

1.

functions, methods, classes, callable class instances

2:

input vs. raw.input(). What is the difference between the built-in functions input() and raw_input()

A:

3.

raw_input() returns user input as a string; input() returns the evaluation of the user input as a Python expression.

Chapter 15

1:

Recognize the following strings: bat, bit, but, hat, hit, or hut.

A:

1.

bat, hat, bit, etc.

								
[bh] [aiu] t

							

2:

Match any pair of words separated by a single space, i.e., first and last names

A:

2.

first name last

								
[A-Za-z-]+ [A-Za-z-]+

							
(any pair of words separated by a single space, e.g., first and last names, hyphens allowed)

3:

Match any word and single letter separated by a comma and single space, as in last name, first initial

A:

3.

last name, first

								
[A-Za-z-]+, [A-Za-z]

							
(any word and single letter separated by a comma and single space, e.g., last name, first initial)

								
[A-Za-z-]+, [A-Za-z-]+

							
(any pair of words separated by a comma and single space, e.g., last, first names, hyphens allowed)

4:

Match the set of the string representations of all Python longs

A:

8.

Python longs

								
\d+[lL]

							
(decimal [base 10] integers only)

5:

Match the set of the string representations of all Python floats

A:

9.

Python floats

								
[0–9]+(\.[0–9]*)?

							
(describes a simple floating point number, that is, any number of digits followed optionally by a single decimal point and zero or more numeric digits, as in "0.004," "2," "75.," etc.)

Chapter 16

1:

A:

3.

TCP

2:

A:

5.

>>> import socket
>>> socket.getservbyname('daytime', 'udp')
13


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.