Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Python (2005)

.pdf
Скачиваний:
177
Добавлен:
17.08.2013
Размер:
15.78 Mб
Скачать

Integrating Java with Python

Access any database that provides a JDBC driver. The zxJDBC driver bridges from the Python DB API to the Java JDBC API.

Run Jython scripts as Java servlets by using the handy PyServlet class from your J2EE web applications.

Interactively gather information on Java classes and execute methods on those classes. This is very useful for testing.

Embed the Jython interpreter in your own Java classes, enabling you to execute Jython scripts and expressions from your Java code.

This chapter wraps up this tutorial on Python. The appendixes provide answers to the chapter exercises, links to Python resources, as well as a discussion of new features in the Python 2.4 release.

Exercises

1.If Python is so cool, why in the world would anyone ever use another programming language such as Java, C++, C#, Basic, or Perl?

2.The Jython interpreter is written in what programming language? The python command is written in what programming language?

3.When you package a Jython-based application for running on another system, what do you need to include?

4.Can you use the Python DB driver modules, such as those described in Chapter 14, in your Jython scripts?

5.Write a Jython script that creates a window with a red background using the Swing API.

571

TEAM LinG

TEAM LinG

A

Answers to Exercises

Chapter 1

Exercise 1 solution

‘Rock a by baby,\n\ton the tree top,\t\twhen the wind blows\n\t\t\t the cradle will drop.’

Because this is not being printed, the special characters (those preceded with a backslash) are not translated into a form that will be displayed differently from how you typed them.

Exercise 2 solution

Rock a by baby,

 

on the tree top,

when the wind blows

the cradle will drop.

When they are printed, “\n” and “\t” produce a newline and a tab character, respectively. When the print function is used, it will render them into special characters that don’t appear on your keyboard, and your screen will display them.

Chapter 2

Exercise 1 solution

>>> 5 * 10 50

Exercise 2 solution

>>>122/3

40

>>>122.0/3

40.666666666666664

TEAM LinG

Appendix A

Exercise 3 solution

>>>print “%o” % 6

6

>>>print “%o” % 7

7

>>>print “%o” % 8

10

>>>print “%o” % 9

11

>>>print “%o” % 10

12

>>>print “%o” % 11

13

>>>print “%o” % 12

14

>>>print “%o” % 13

15

>>>print “%o” % 14

16

Exercise 4 solution

>>>print “%x” % 9

9

>>>print “%x” % 10

a

>>>print “%x” % 11

b

>>>print “%x” % 12

c

>>>print “%x” % 13

d

>>>print “%x” % 14

e

>>>print “%x” % 15

f

>>>print “%x” % 16

10

>>>print “%x” % 17

11

>>>print “%x” % 18

12

>>>print “%x” % 19

13

Exercise 5 solution

When an unknown function is called, Python doesn’t know that the name that’s been typed in is necessarily a function at all, so it just flags a general syntax error:

>>> pintr “%x” & x

File “<input>”, line 1 pintr “%x” & x

^

SyntaxError: invalid syntax

574

TEAM LinG

Answers to Exercises

You’ll notice, however, that codeEditor will display print in bold when you type it. This is because print is a special word to Python, and codeEditor knows this. You can help yourself catch errors by paying attention to how the editor reacts to what you’ve typed.

Exercise 6 solution

>>> print “%u” % -10 -10

Python 2.4 will turn the unsigned integer into a signed integer instead of confusing you. In prior versions, it would have given you a very large number — somewhere a bit more than four billion.

Chapter 3

Exercise 1 solution

>>> dairy_section = [“milk”, “cottage cheese”, “butter”, “yogurt”]

Exercise 2 solution

>>> print “First: %s and Last %s” % (dairy_section[0], dairy_section[1]) First: milk and Last cottage cheese

Exercise 3 solution

>>> milk_expiration = (10, 10, 2005)

Exercise 4 solution

>>> print “This milk will expire on %d/%d/%d” % (milk_expiration[0], milk_expiration[1], milk_expiration[2])

This milk will expire in 10/10/2005

Exercise 5 solution

>>>milk_carton = {}

>>>milk_carton[“expiration_date”] = milk_expiration

>>>milk_carton[“fl_oz”] = 32

>>>milk_carton[“cost”] = 1.50

>>>milk_carton[“brand_name”] = “Milk”

Exercise 6 solution

>>> print “The expiration date is %d/%d/%d” % (milk_carton[“expiration_date”][0], milk_carton[“expiration_date”][1], milk_carton[“expiration_date”][2])

The expiration date is 10/10/2005

Exercise 7 solution

>>> print “The cost for 6 cartons of milk is %.02f” % (6* milk_carton[“cost”]) The cost for 6 cartons of milk is 9.00

575

TEAM LinG

Appendix A

Exercise 8 solution

>>>cheeses = [“cheddar”, “american”, “mozzarella”]

>>>dairy_section.append(cheeses)

>>>dairy_section

[‘milk’, ‘cottage cheese’, ‘butter’, ‘yogurt’, [‘cheddar’, ‘american’, ‘mozzarella’]]

>>> dairy_section.pop()

[‘cheddar’, ‘american’, ‘mozzarella’]

Exercise 9 solution

>>> len(dairy_section) 4

Exercise 10 solution

>>> print “Part of some cheese is %s” % cheeses[0][0:5] Part of some cheese is chedd

Chapter 4

At this point, the examples can become long. You should consider typing the code into codeEditor’s main window and cutting and pasting lines so that you don’t have too much to type if there is a problem. Even if you don’t choose to do this, you can use the Shift and up and down arrows to bring back lines you’ve already typed, and you can edit these lines. Try it out.

Exercise 1 solution

The key theme here is that 0 is False, and everything else is considered not False, which is the same as

True:

>>> if 0:

... print “0 is True”

...

>>> if 1:

... print “1 is True”

...

1 is True

>>> if 2:

... print “2 is True”

...

2 is True

>>> if 3:

... print “3 is True”

...

3 is True

>>> if 4:

... print “4 is True”

...

4 is True

>>> if 5:

576

TEAM LinG

Answers to Exercises

... print “5 is True”

...

5 is True

Exercise 2 solution

>>>number = 3

>>>if number >= 0 and number <= 9:

... print “The number is between 0 and 9: %d” % number

...

The number is between 0 and 9: 3

Exercise 3 solution

>>>test_tuple = (“this”, “little”, “piggie”, “went”, “to”, “market”)

>>>search_string = “toes”

>>>if test_tuple[0] == search_string:

... print “The first element matches”

... elif test_tuple[1] == search_string:

... print “the second element matches”

... else:

... print “%s wasn’t found in the first two elements” % search_string

...

toes wasn’t found in the first two elements

Exercise 4 solution

>>>fridge = {“butter”:”Dairy spread”, “peanut butter”:”non-dairy spread”, “cola”:”fizzy water”}

>>>food_sought = “chicken”

>>>for food_key in fridge.keys():

...

if food_key == food_sought:

...

print “Found what I was looking for: %s is %s” % (food_sought,

fridge[food_key])

...

break

... else:

...

print “%s wasn’t found in the fridge” % food_sought

...

 

chicken wasn’t found in the fridge

Exercise 5 solution

>>>fridge = {“butter”:”Dairy spread”, “peanut butter”:”non-dairy spread”, “cola”:”fizzy water”}

>>>fridge_list = fridge.keys()

>>>current_key = fridge_list.pop()

>>>food_sought = “cola”

>>>while len(fridge_list) > 0:

...

if current_key == food_sought:

...

print “Found what I was looking for: %s is %s” % (food_sought,

fridge[current_key])

... break

... current_key = fridge_list.pop()

577

TEAM LinG

Appendix A

... else:

... print “%s wasn’t found in the fridge” % food_sought

...

Found what I was looking for: cola is fizzy water

Exercise 6 solution

>>>fridge = {“butter”:”Dairy spread”, “peanut butter”:”non-dairy spread”, “cola”:”fizzy water”}

>>>food_sought = “chocolate milk”

>>>try:

...

fridge[food_sought]

... except KeyError:

...

print “%s wasn’t found in the fridge” % food_sought

... else:

...

print “Found what I was looking for: %s is %s” % (food_sought,

fridge[food_key])

...

chocolate milk wasn’t found in the fridge

Chapter 5

Exercise 1 solution

def do_plus(first, second): return first + second

Exercise 2 solution

def do_plus(first, second):

for param in (first, second):

if (type(param) != type(“”)) and (type(param) != type(1)):

raise TypeError, “This function needs a string or an integer” return first + second

Exercise 3 solution

#Part 1 - fridge has to go before the omelet_type. omelet_type is an

#optional parameter with a default parameter, so it has to go at the end.

#This can be used with a fridge such as:

#f = {‘eggs’:12, ‘mozzarella cheese’:6,

#‘milk’:20, ‘roast red pepper’:4, ‘mushrooms’:3}

#or other ingredients, as you like.

def make_omelet_q3(fridge, omelet_type = “mozzarella”):

“””This will make an omelet. You can either pass in a dictionary that contains all of the ingredients for your omelet, or provide a string to select a type of omelet this function already knows about

The default omelet is a mozerella omelet”””

def get_omelet_ingredients(omelet_name):

578

TEAM LinG

 

 

Answers to Exercises

“””This contains a dictionary of

omelet names that can be produced,

and their ingredients”””

 

 

# All of our omelets need eggs and milk

ingredients = {“eggs”:2, “milk”:1}

if omelet_name == “cheese”:

 

 

ingredients[“cheddar”] = 2

 

 

elif omelet_name == “western”:

 

 

ingredients[“jack_cheese”] =

2

ingredients[“ham”]

=

1

ingredients[“pepper”]

=

1

ingredients[“onion”]

=

1

elif omelet_name == “greek”:

 

 

ingredients[“feta_cheese”] =

2

ingredients[“spinach”]

=

2

# Part 5

 

 

elif omelet_name == “mozzarella”: ingredients[“mozzarella cheese”] = 2 ingredients[“roast red pepper”] = 2 ingredients[“mushrooms”] = 1

else:

print “That’s not on the menu, sorry!” return None

return ingredients

#part 2 - this version will use the fridge that is available

#to the make_omelet function.

def remove_from_fridge(needed): recipe_ingredients = {}

#First check to ensure we have enough for ingredient in needed.keys():

if needed[ingredient] > fridge[ingredient]:

raise LookupError, “not enough %s to continue” % ingredient

#Then transfer the ingredients.

for ingredient in needed.keys():

# Remove it from the fridge

fridge[ingredient] = fridge[ingredient] - needed[ingredient]

# and add it to the dictionary that will be returned recipe_ingredients[ingredient] = needed[ingredient]

# Part 3 - recipe_ingredients now has all the needed ingredients return recipe_ingredients

# Part 1, continued - check the type of the fridge if type(fridge) != type({}):

raise TypeError, “The fridge isn’t a dictionary!”

if type(omelet_type) == type({}):

print “omelet_type is a dictionary with ingredients” return make_food(omelet_type, “omelet”)

elif type(omelet_type) == type(“”):

needed_ingredients = get_omelet_ingredients(omelet_type) omelet_ingredients = remove_from_fridge(needed_ingredients) return make_food(omelet_ingredients, omelet_type)

else:

print “I don’t think I can make this kind of omelet: %s” % omelet_type

579

TEAM LinG

Appendix A

Exercise 4 solution

The get_omelet_ingredient from make_omelet_q3 could be changed to look like the following:

def get_omelet_ingredients(omelet_name):

“””This contains a dictionary of omelet names that can be produced, and their ingredients”””

# All of our omelets need eggs and milk ingredients = {“eggs”:2, “milk”:1}

if omelet_name == “cheese”: ingredients[“cheddar”] = 2

elif omelet_name == “western”: ingredients[“jack_cheese”] = 2

ingredients[“ham”]

= 1

ingredients[“pepper”]

= 1

ingredients[“onion”]

= 1

elif omelet_name == “greek”:

 

ingredients[“feta_cheese”] = 2

ingredients[“spinach”]

= 2

# Part 5

elif omelet_name == “mozerella”: ingredients[“mozerella cheese”] = 2 ingredients[“roast red pepper”] = 2 ingredients[“mushrooms”] = 1

# Question 4 - we don’ want anyone hurt in our kitchen! elif omelet_name == “salmonella”:

raise TypeError, “We run a clean kitchen, you won’t get this here” else:

print “That’s not on the menu, sorry!” return None

return ingredients

When run, the error raised by trying to get the salmonella omelet will result in the following error:

>>> make_omelet_q3({‘mozzarella cheese’:5, ‘eggs’:5, ‘milk’:4, ‘roast red pepper’:6, ‘mushrooms’:4}, “salmonella”)

Traceback (most recent call last): File “<stdin>”, line 1, in ?

File “ch5.py”, line 209, in make_omelet_q3 omelet_ingredients = get_omelet_ingredients(omelet_type)

File “ch5.py”, line 179, in get_omelet_ingredients

raise TypeError, “We run a clean kitchen, you won’t get this here” TypeError: We run a clean kitchen, you won’t get this here

>>>

You can see from this that the program was run from <stdin>, which means it was run interactively, with python -i ch5.py or by using codeEditor’s Run with Interpreter option. The function make_ omelet_q3 was called, and the function get_omelet_ingredients was called on line 209 in ch5.py. Python shows you the actual line that was run, in case you needed more information at first glance. Note that depending on the contents of your ch5.py file, the exact line numbers shown in your stack trace will be different from those shown here.

You can next see that line 179 is where get_omelet_ingredients raised the error (though it may be at a different line in your own file).

580

TEAM LinG