Building Buttons

Buttons, of course, are standard elements of virtually every GUI these days. Modern buttons are very sophisticated, usually having a 3-dimensional look and feel. Our simple graphics package does not have the machinery to produce buttons that appear to depress as they are clicked. The best we can do is find out where Figure 10.3 Snapshot of dice roller in action. Figure 10.3 Snapshot of dice roller in action. the mouse was clicked after the click has already completed. Nevertheless, we can make...

Implementing the Model

So far, we have a pretty good picture of what the Dice class will do and a starting point for implementing the PokerApp class. We could proceed by working on either of these classes. We won't really be able to try out the PokerApp class until we have dice, so let's start with the lower-level Dice class. The Dice class implements a collection of dice, which are just changing numbers. The obvious representation is to use a list of five ints. Our constructor needs to create a list and assign some...

Simple String Processing

Now that you have an idea what string operations can do, we're ready to write some programs. Our first example is a program to compute the usernames for a computer system. Many computer systems use a username and password combination to authenticate system users. The system administrator must assign a unique username to each user. Often, usernames are derived from the user's actual name. One scheme for generating usernames is to use the user's first initial followed by up to seven letters of...

Using Graphical Objects

Some of the examples in the above interactions may look a bit strange to you. To really understand the graphics module, we need to take an object-oriented point of view. Recall, objects combine data with operations. Computation is performed by asking an object to carry out one of its operations. In order to make use of objects, you need to know how to create them and how to request operations. In the interactive examples above, we manipulated several different kinds of objects GraphWin, Point,...

What is Computer Science

You might be surprised to learn that computer science is not the study of computers. A famous computer scientist named Edsgar Dijkstra once quipped that computers are to computer science what telescopes are to astronomy. The computer is an important tool in computer science, but it is not itself the object of study. Since a computer can carry out any process that we can describe, the real question is What processes can we describe Put another way, the fundamental question of computer science is...

Definite Loops

You already know that programmers use loops to execute a sequence of statements several times in succession. The simplest kind of loop is called a definite loop. This is a loop that will execute a definite number of times. That is, at the point in the program when the loop begins, Python knows how many times to go around (or iterate) the body of the loop. For example, the Chaos program from Chapter 1 used a loop that always executed exactly ten times. This particular loop pattern is called a...

Top Down Design

Now you have the complete specification for our simulation and the necessary knowledge of random numbers to get the job done. Go ahead and take a few minutes to write up the program I'll wait. OK, seriously, this is a more complicated program than you've probably attempted so far. You may not even know where to begin. If you're going to make it through with minimal frustration, you'll need a systematic approach. One proven technique for tackling complex problems is called top-down design. The...

Example Program Word Frequency

Let's write a program that analyzes text documents and counts how many times each word appears in the document. This kind of analysis is sometimes used as a crude measure of the style similarity between two documents and is also used by automatic indexing and archiving programs (such as Internet search engines). At the highest level, this is just a multi-accumulator problem. We need a count for each word that appears in the document. We can use a loop that iterates through each word in the...

Multi Way Decisions

The newest version of the quadratic solver is certainly a big improvement, but it still has some quirks. Here is another example run. This program finds the real solutions to a quadratic Please enter the coefficients (a, b, c) 1, 2, 1 The solutions are -1.0 -1.0 This is technically correct the given coefficients produce an equation that has a double root at -1. However, the output might be confusing to some users. It looks like the program has mistakenly printed the same number twice. Perhaps...

The Halting Problem

Let's just imagine for a moment that this book has inspired you to pursue a career as a computer professional. It's now six years later, and you are a well-established software developer. One day, your boss comes to you with an important new project, and you are supposed to drop everything and get right on it. It seems that your boss has had a sudden inspiration on how your company can double its productivity. You've recently hired a number of rather inexperienced programmers, and debugging...

Developing a GUI

Now that we have a working program, let's turn our attention to a nicer graphical interface. Our first step must be to decide exactly how we want our interface to look and function. The interface will have to support the various methods found in the text-based version and will also probably have some additional helper methods. Let's start with the basic methods that must be supported and decide exactly how interaction with the user will occur. Clearly, in a graphical interface, the faces of the...

Simulation and Design

You may not realize it, but you have reached a significant milestone in the journey to becoming a computer scientist. You now have all the tools to write programs that solve interesting problems. By interesting, I mean problems that would be difficult or impossible to solve without the ability to write and implement computer algorithms. You are probably not yet ready to write the next great killer application, but you can do some nontrivial computing. One particularly powerful technique for...

Towers of Hanoi

One very elegant application of recursive problem solving is the solution to a mathematical puzzle usually called the Tower of Hanoi or Tower of Brahma. This puzzle is generally attributed to the French mathematician Edouard Lucas, who published an article about it in 1883. The legend sorrounding the puzzle goes something like this. Somewhere in a remote region of the world is a monastery of a very devout religious order. The monks have been charged with a sacred task that keeps time for the...

Graphics Module Reference

The examples in this chapter have touched on most of the elements in the graphics module. This section provides a complete reference to the objects and functions provided in the graphics library. Experienced programmers use these sorts of guides to learn about new libraries. You will probably want to refer back to this section often when you are writing your own graphical programs. A GraphWin object represents a window on the screen where graphical images may be drawn. A program may define any...

Example Program Future Value

Let's close the chapter with one more example of the programming process in action. We want to develop a program to determine the future value of an investment. Let's start with an analysis of the problem requirements . You know that money that is deposited in a bank account earns interest, and this interest accumulates as the years pass. How much will an account be worth ten years from now Obviously it depends on how much money we start with the principal and how much interest the account...

Future Value with a Function

Now that you've seen how defining functions can help solve the code duplication problem, let's return to the future value graph. Recall the problem is that bars of the graph are printed at two different places in the program. The code just before the loop looks like this. Draw bar for initial principal bar Rectangle Point 0, 0 , Point 1, principal And the code inside of the loop is as follows. bar Rectangle Point year, 0 , Point year 1, principal Let's try to combine these two into a single...

Loop and a Half

Some programmers would solve the warning problem from the previous section using a slightly different style. number input Enter a positive number if x gt 0 break Loop exit print The number you entered was not positive Here the loop exit is actually in the middle of the loop body. This is called a loop and a half. Some purists frown on exits in the midst of a loop like this, but the pattern can be quite handy. The loop and a half is an elegant way to avoid the priming read in a sentinel loop....

Suppose You Are Doing A Random Walk See Previous Problem On The Blocks Of A City Street

Draw the top levels of a structure chart for a program having the following main function. length, width getDimensions amtNeeded computeAmount length,width printReport length, width, amtNeeded 2. Write an expression using either random or randrange to calculate the following. A random int in the range 0-10 A random float in the range-0.5-0.5 A random number representing the roll of a six-sided die A random number representing the sum resulting from rolling two six-sided dice A random float...

Interactive Graphics

Graphical interfaces can be used for input as well as output. In a GUI environment, users typically interact with their applications by clicking on buttons, choosing items from menus, and typing information into on-screen text boxes. These applications use a technique called event-driven programming. Basically, the program draws a set of interface elements often called widgets on the screen, and then waits for the user to do something. When the user moves the mouse, clicks a button or types a...

Python Programming Exercises Ask User For 4 Numbers Absolute Value

Show the result of evaluating each expression. Be sure that the value is in the proper form to indicate its type int, long int, or float . If the expression is illegal, explain why. 2. Translate each of the following mathematical expressions into an equivalent Python expression. You may assume that the math library has been imported via import math . 3. Show the list of numbers that would be generated by each of the following range expressions. 4. Show the output that would be generated by...

Functions that Return Values

You have seen that parameter passing provides a mechanism for initializing the variables in a function. In a way, parameters act as inputs to a function. We can call a function many times and get different results by changing the input parameters. Sometimes we also want to get information back out of a function. This is accomplished by having functions return a value to the caller. You have already seen numerous examples of this type of function. For example, consider this call to the sqrt...

Post Test Loop

Suppose you are writing an input algorithm that is supposed to get a nonnegative number from the user. If the user types an incorrect input, the program asks for another value. It continues to reprompt until the user enters a valid value. This process is called input validation. Well-engineered programs validate inputs whenever possible. get a number from the user until number is gt 0 The idea here is that the loop keeps getting inputs until the value is acceptable. The flowchart depicting this...

Indefinite Loops

Our averaging program is certainly functional, but it doesn't have the best user interface. It begins by asking the user how many numbers there are. For a handful of numbers this is OK, but what if I have a whole page of numbers to average It might be a significant burden to go through and count them up. It would be much nicer if the computer could take care of counting the numbers for us. Unfortunately, as you no doubt recall, the for loop is a definite loop, and that means the number of...

Python Programming Chapter 9 Exercises Zelle

Given the initial statements import string s1 spam s2 ni Show the result of evaluating each of the following string expressions. a The Knights who say, s2 3 2. Given the same initial statements as in the previous problem, show a Python expression that could construct each of the following results by performing string operations on s1 and s2 . c Spam Ni Spam Ni Spam Ni 3. Show the output that would be generated by each of the following program fragments. a for ch in aardvark b for w in...