Defining Your Own Modules

Section 2.1, The Big Picture, on page 17 explained that in order to save code for later use, you can put it in a file with a .py extension. You can then tell Python to run the code in that file, rather than typing commands in at the interactive prompt. What we didn't tell you then is that every Python file can be used as a module. The name of the module is the same as the name of the file, but without the .py extension. For example, the following function is taken from Section 2.6, Function...

Summary Uat

In this chapter, we learned the following A module is a collection of functions and variables grouped together in a file. To use a module, you must first import it. After it has been imported, you refer to its contents using modulename. thingname. Put docstrings at the start of modules or functions to describe their contents and use. Every thing in a Python program is an object. Objects have methods, which work just like functions but are associated with the object's type. Methods are called...

Default Parameter Values

Default parameter values are the first of these tools. Here's an example Download construct default_define.py def total values, start 0, end None '''Add up the values in a list. If none are given, the total is zero. If 'start' is not specified, start at the beginning. If 'end' is specified, go up to but not including that index otherwise, go to the end of the list. '' ' This function has three parameters a list of values and two indices that specify which part of the list to sum up. What makes...

Exercises

Here are some exercises for you to try on your own 1. For each of the following expressions, what value will the expression give Verify your answers by typing the expressions into Python. 2. Unary minus negates a number. Unary plus exists as well for example, Python understands 5. If x has the value -17, what do you think x should do Should it leave the sign of the number alone Should it act like absolute value, removing any negation Use the Python shell to find out its behavior. 3. a Create a...

Exercises Wkf

Here are some exercises for you to try on your own 1. For each of the following expressions, what value will the expression give Verify your answers by typing the expressions into Python. 2. Here is a possible definition of how and works If both operands are true, and's result is its second value. If either is false, and's result is its first value. Is this the rule that Python actually uses If not, provide a counter example. 3. You are given variables x and y. a Write an expression that...

Exercises Luw

The best way to learn how to do object-oriented programming is to go back through the examples and exercises of previous chapters and see which ones are easier or more naturally written using classes and objects. You can also create object-oriented programs that represent things in the real world. For example, what classes would you use to model the stars, planets, moons, rings, and comets that make up a solar system What methods should each class have How and where would you keep track of...

Insertion Sort

Like selection sort, insertion sort keeps a sorted section at the beginning of the list. Rather than scan all of the unsorted section for the next smallest item, though, it takes the next item from the unsorted section and inserts it where it belongs in the sorted section. Reorder the values in L from smallest to largest. Insert L i where it belongs in L 0 i 1 . i i 1 This is exactly the same code as for selection sort the difference is in the comment in the loop. How does insert work It works...

Ragged Lists

Nothing says that nested lists all have to be the same length gt gt gt info 'Isaac Newton', 1643, 1727 , 'Alan Turing', 1912, 1954, 'alan bletchley.uk' These sorts of lists are called ragged lists. Ragged lists can be tricky to process if the data is not uniform for example, trying to assemble a list of email addresses for data where some addresses are missing requires a bit of careful thought. Ragged data does arise normally. For example, if a record is made each day of the time at which a...

Exercises Hbt

Here are some exercises for you to try on your own 1. Your lab partner claims to have written a function that replaces each value in a list with twice the preceding value and the first value with 0 . For example, if the list 1, 2, 3 is passed as an argument, the function is supposed to turn it into 0, 2, 4 . Here's the code def double_preceding values if values pass do nothing to the empty list else for i in range 1, len values values i 2 temp temp values i Explain what the bug in this function...

Escape Characters

Suppose you want to put a single quote inside a string. If you write it directly, Python will complain Download strings single_in_single.cmd gt gt gt 'that's not going to work' File lt stdin gt , line 1 The problem is that when Python sees the second quote the one that you think of as being part of the string it thinks the string is over. It then doesn't know what to do with all the stuff that comes after the second quote. One simple way to fix this is to use double quotes around the string...

Mergesort

Download searchsort mergesort_header.py Sort L in increasing order. Figure 11.8 List of lists in mergesort Figure 11.8 List of lists in mergesort Mergesort uses function merge to do the bulk of the work. Here is the algorithm, which creates and keeps track of a list of lists Take list L, and make a list of one-item lists from it. As long as there are two lists left to merge, merge them, and append the new list to the list of lists. Download searchsort mergesort_make_list.py Make a list of...

The Pragmatic Bookshelf

Available in paperback and DRM-free PDF, our titles are here to help you stay on top of your game. The following are in print as of April 2009 be sure to check our website at pragprog.com for newer titles. Advanced Rails Recipes 84 New Ways to Build Stunning Rails Apps Agile Retrospectives Making Good Teams Great Agile Web Development with Rails Second Edition Agile Web Development with Rails, Third Edition Augmented Reality A Practical Guide Behind Closed Doors Secrets of Great Management Core...

The Pdb File Format Is Often Used To Store Information About Molecules. A Pdb

Here are some exercises for you to try on your own 1. Write a function called find_dups that takes a list of integers as its input argument and returns a set of those integers that occur two or more times in the list. 2. Python's set objects have a method called pop that removes and returns an arbitrary element from the set. If a set gerbils contains five cuddly little animals, for example, calling gerbils.pop five times will return those animals one by one, leaving the set empty at the end....

Computer Science Exercises

Here are some exercises for you to try on your own 1. Import module math, and use its functions to complete the following exercises a Write a single expression that rounds the value of -4.3 and then takes the absolute value of that result. b Write an expression that takes the ceiling of sine of 34.5. 2. In the following exercises, you will work with Python's calendar module a Visit the Python documentation website at http docs.python. org modindex.html, and look at the documentation on the...

Set Operations

In mathematics, set operations include union, intersection, add, and remove. In Python, these are implemented as methods for a complete list, see Figure 9.2, on the next page . Note that most operations create a new set only add, remove, and clear modify the current set. The following program shows these methods in action gt gt gt ten set range 10 gt gt gt lows set 0, 1, 2, 3, 4 gt gt gt odds set 1, 3, 5, 7, 9 gt gt gt lows.add 9 gt gt gt lows gt gt gt lows.intersection odds gt gt gt...

Strings 1

Computers may have been invented to do arithmetic, but these days, most of them spend a lot of their time processing text. From desktop chat programs to Google, computers create text, store it, search it, and move it from one place to another. In Python, a piece of text is represented as a string, which is a sequence of characters letters, numbers, and symbols . The simplest data type for storing sequences of characters is str it can store characters from the Latin alphabet found on most North...

Write A For Loop To Read The Contents Of Alkaline Metals.txt And Store It In A

Here are some exercises for you to try on your own 1. Assign a list that contains the atomic numbers of the six alkaline earth metals beryllium 4 , magnesium 12 , calcium 20 , strontium 38 , barium 56 , and radium 88 to a variable called alkaline_earth_metals. 2. Which index contains Radium's atomic number Write the answer in two ways, one using a positive index and one using a negative index. 3. Which function tells you how many items there are in alkaline_ earth_metals 4. Write code that...

Computer Science Python Exercises

Here are some exercises for you to try on your own 1. All of the file-reading functions we have seen in this chapter read forward through the file from the first character or line to the last. How would you write a function that would read backward through a file 2. The file reader we developed in Section 8.3, Positional Data, on page 174 returns a single tuple for each entire record. Modify it so that if the field format is specified like this 4, int , 2, int , 2, int , date 2, int , 2, int ,...