Another Python Program Adding Integers

Our next program inputs two integers (whole numbers, like -22, 7 and 1024) typed by a user at the keyboard, computes the sum of the values and displays the result. This program invokes Python functions raw_input and int to obtain the two integers. Again, the program uses the print statement to display the sum of the integers. Figure 2.7 contains the program and its output. Lines 1-2 contain comments that state the figure number, file name and the purpose of the program. Line 5 calls Python's...

Case Study A Single List Class

We now present an example of a class that wraps (contains) a list to illustrate how to define several special methods to create a class that behaves like a sequence. The list allows clients to insert only new (unique) values in the list and allows the list to be displayed in tabular form. This example will sharpen your appreciation of data abstraction. You will probably want to suggest enhancements to this example. Class development is an interesting, creative and intellectually challenging...

Case Study Point Circle Cylinder

Consider a more substantial example using a point, circle, cylinder structural-inheritance hierarchy. First we develop and use class Point (Fig. 9.6). Then we present an example in which we derive class Circle from class Point (Fig. 9.7). Finally, we present an example in which we derive class Cylinder from class Circle (Fig. 9.8). Figure 9.6 shows class Point. The constructor (lines 7-11) takes two arguments that correspond to the x- and -coordinates of the point. Method_str_(lines 13-16)...

Composition Object References as Members of Classes

Until now, we have defined classes whose objects have attributes of basic types. Sometimes, a programmer needs objects whose attributes are themselves references to objects of other classes. For example, an object of class AlarmClock needs to know when it is supposed to sound its alarm, so why not include an object of class Time as a member of the object of class AlarmClock Such a capability is called composition.

Creating Base Classes and Derived Classes

This section creates an inheritance hierarchy and instantiates objects from the classes in that hierarchy. Python provides two built-in functions issubclass and isinstance that enable us to determine whether one class is derived from another class and whether a value is an object of a particular class or of a subclass of that class. We discuss these functions in Fig. 9.4 that demonstrates how to derive one class from another class and that underscores the fact that a derived-class object is a...

Customizing Attribute Access

In the previous chapter, we discussed two techniques for a client to access an object's attributes. The client can access the attributes directly (through the dot access operator), or the class author can give the attributes special names to signify that a client should access the attributes through access methods. In this section, we discuss another technique defining special methods that customize the behavior of direct attribute access. Python provides three special methods (Fig. 8.2) that a...

Decision Making Equality and Relational Operators

This section introduces a simple version of Python's if structure that allows a program to make a decision based on the truth or falsity of some condition. If the condition is met, (i.e., the condition is true), the statement in the body of the if structure is executed. If the condition is not met (i.e., the condition is false), the body statement does not execute. We will see an example shortly. Conditions in if structures can be formed with the equality operators and relational operators...

Entry Component

Entry components are areas in which users can enter text or programmers can display a line of text. This section demonstrates entry components in a program. When the user types text into an Entry component and presses the Enter key, a < Return> event occurs. If an event handler is bound to that event for the Entry component, the event is processed. In our example, the < Return> event signals that the user has finished entering text in the Entry. Figure 10.6 defines class EntryDemo,...

First Program in Python Printing a Line of Text

We begin by considering a simple program that prints a line of text. Figure 2.1 illustrates the program and its screen output. 2 Printing a line of text in Python. 4 print Welcome to Python 1. The resources for this book, including step-by-step instructions for installing Python on Windows and Unix Linux platforms, are posted at www.deitel. com. 36 Introduction to Python Programming This program illustrates several important features of the Python language. Let us consider each line of the...

Good Programming Practice

Place spaces on either side of a binary operator or symbol. This helps the operator or symbol stand out, making the program more readable. Line 13 displays the string Sum is followed by the numerical value of variable sum. Items we want to output are separated by commas (,). Note that this print statement outputs values of different types, namely a string and an integer. Calculations also can be performed in output statements. We could have combined the statements in lines 11 and 13 into the...

Graphical User Interface Components Part

To understand the design principles of graphical user interfaces. To use the Tkinter module to build graphical user interfaces. To create and manipulate labels, text fields, buttons, check boxes and radio buttons. To learn to use mouse events and keyboard events. To understand and use layout managers. the wisest prophets make sure of the event first. Horace Walpole Do you think I can listen all day to such stuff Lewis Carroll SSpeak the affirmative emphasize your choice by utter ignoring of...

Implementing a Time Abstract Data Type with a Class

Classes enable programmers to model objects that have data (represented as attributes) and behaviors or operations (represented as methods). Methods are invoked in response to messages sent to objects. A message corresponds to a method call sent from one object to another. Classes simplify programming because the clients (or users of the class) need to be concerned only with the operations encapsulated or embedded in the object the object interface. Such operations usually are designed to be...

Keyboard Event Handling

This section presents binding event handlers to keyboard events. These events are generated when keyboard keys are pressed and released. Figure 10.13 presents all available formats for keyboard events. Figure 10.14 demonstrates binding methods to keyboard events. For clarity, we do not use the shorthand notations of < KeyPress> and < KeyPress-key> events. Event format Description of Event < KeyPress> Any key has been selected. < KeyRelease> Any key has been released. <...

List and Dictionary Methods

We have seen how sequences and dictionaries enable programmers to accomplish high-level data manipulation, such as storing and retrieving data. We now introduce a new programming concept, the method, to extend data-manipulation capabilities. As discussed in Chapter 2, Introduction to Python Programming, all Python data types contain at least three properties a value, a type and a location. Some Python data types (e.g., strings, lists and dictionaries) also contain methods. A method is a...

Lists Tuples and Dictionaries

These values might be represented as integers, each integer has its own meaning, and the full representation of the time is obtained only by taking all three values together. The length of the tuple (i.e., its number of data items) is predetermined and cannot change during a program's execution. By convention, each data item in the tuple represents a unique portion of the overall data. Therefore, a program usually does not iterate over a tuple, but accesses the parts of the tuple the program...

Logical Operators

So far, we have studied simple conditions, such as counter < 10, total > 1000 and number sentinelValue. We have expressed these conditions in terms of the relational operators > , < , > and < and the equality operators and . Each decision tested precisely one condition. To test multiple conditions while making a decision, we performed these tests in separate statements or in nested if or if else structures. Python provides logical operators that are used to form more complex...

Lookand Feel Observation

Having more than one Button with the same label results in ambiguity. Provide a unique label for each button. Figure 10.7 creates two Buttons and demonstrates that Buttons, like Labels, can display both images and text. from Tkinter import * from tkMessageBox import * Create one plain and one fancy button Create two buttons, pack them and bind events Frame._init_( self ) self.pack( expand YES , fill BOTH ) self.master.title( Buttons ) create button with text self.plainButton Button( self, text...

Mouse Event Handling

This section demonstrates how programs handle mouse events events that occur as a result of user interaction with a mouse. Figure 10.10 summarizes several common mouse event formats and Fig. 10.11 demonstrates how a GUI program can handle them. All Tkinter events are described by strings following the pattern < modifier-type-detail> . The type (for instance, Button and Return) specifies the kind of event. The prefix Double is an example of a modifier while the specific mouse button is a...

Operator Overloading

Operators provide programmers with a concise notation for expressing manipulations of objects of built-in types. Programmers can also use operators with objects of a class. Although Python does not allow new operators to be created, it does allow most existing operators to be overloaded such that, when these operators are used with objects of a programmer-defined type, the operators have meaning appropriate to the new types. Software Engineering Observation 8.3 Operator overloading contributes...

Simple CGI Script

Two types of scripting are used in Web-based applications server-side and client-side. CGI scripts are an example of server-side scripts because they run on the server. Programmers have greater control over Web page content when using server-side scripts, because serverside scripts can manipulate databases and other server resources. An example of client-side scripting is JavaScript. Client-side scripts can access the browser's features, manipulate browser documents, validate user input and...

Simple Tkinter Example Label Component

Labels display text or images that provide instructions or other information in graphical user interfaces. Figure 10.4 demonstrates class Label the Tkinter class that represents a label component. class LabelDemo( Frame ) Demonstrate Labels Create three Labels and pack them Frame._init_( self ) initializes Frame object frame fills all available space self.pack( expand YE , fill BOTH ) self.master.title( Labels ) self.Label1 Label( self, text Label with text ) resize frame to accommodate Label...

Software Engineering Observation

A suite can be placed anywhere in a program that a single statement can be placed. The if selection structure can contain several statements in its body (suite), and all these statements must be indented. The following example includes a suite in the else part of an if else structure that contains two statements. A suite that contains more than one statement is sometimes called a compound statement. print You must take this course again. In this case, if grade is less than 60, the program...

String Formatting

Now that we have investigated numeric values, let us turn our attention to strings. Unlike some other popular programming languages, Python provides strings as a built-in data type, thereby enabling Python programs to perform powerful text-based operations easily. We have already learned how to create a string by placing text inside double quotes (). Python strings can be created in a variety of other ways, as Fig. 2.18 demonstrates. Line 4 creates a string with the familiar double-quote...

Using cgiField Storage to Read Input

Figure 6.10 reimplements the example from Fig. 6.9 to take advantage of a high-level data abstraction provided by module cgi. Line 28 creates an object of class cgi.FieldStorage. Wote Classes are discussed in Chapter 7, Object-Based Programming. In our example, the high-level data type (or class) is called cgi. FieldStorage and resembles the dictionary returned by the parsing function. Demonstrates use of cgi.FieldStorage an with XHTML form. import cgi < xml version 1.0 encoding UTF-8 > <...

Using the for Repetition Structure

The following examples show techniques for varying the control variable (loop counter) in a for structure. In each case, we write the appropriate for header. Note the change in the third argument to range for loops that decrement the control variable. a) Vary the control variable from 1 to 100 in increments of 1. b) Vary the control variable from 100 to 1 in increments of -1 (decrements of 1). Fig. 3.21 for repetition structure flowchart. Fig. 3.21 for repetition structure flowchart....

Using Xhtml Forms to Send Input and Using Module cgi to Retrieve Form Data

If Web page users had to type all the information that the page required into the page's URL every time the user wanted to access the page, Web surfing would be quite a laborious task. XHTML provides forms on Web pages that provide a more intuitive way for users to input information to CGI scripts. The < form> and < form> tags surround an XHTML form. The < form> tag typically takes two attributes. The first attribute is action, which specifies the operation to perform when the user...

Using Default Arguments With Constructors

Thus far, the client has supplied all the values that the constructor for class Time needed to initialize a new object. However, constructors can define default arguments that specify initial values for an object's attributes, if the client does not specify an argument at construction time. Constructors also can define keyword arguments that enable the client to specify values for only certain, named arguments. Figure 7.13 Time3.py defines a modified version of class Time that redefines the...

Example Interactive Portal

Figure 6.11 and Fig. 6.12 show the implementation of a simple interactive portal login page for the fictional Bug2Bug Travel Web site. The example queries the client for a name and password, then displays information based on data entered. For simplicity, the example does not encrypt the data sent to the server. Figure 6.11 displays the opening page. It is a static XHTML document containing a form that posts data to the fig06_12.py CGI script line 14 . The form contains one field to collect the...

Formulating Algorithms with Top Down Stepwise Refinement Case Study Nested Control Structures

Let us work another complete problem. We once again formulate the algorithm using pseudocode and top-down, stepwise refinement and we develop a corresponding Python program. Consider the following problem statement A college offers a course that prepares students for the state licensing exam for real estate brokers. Last year, several of the students who completed this course took the licensing examination. Naturally, the college wants to know how well its students did on the exam. You have...

Internet and World Wide Web Resources

The World Wide Web Consortium page on CGI is concerned with security issues involving the Common Gateway Interface. This page provides links to CGI specifications, as indicated by the National Center for Supercomputing Applications NCSA . This document provides links to MIME RFCs Request for Comments , MIME related RFCs and other MIME-related information. This is a collection of tutorials and scripts related to CGI. This is the home page of fast CGI an extension to CGI that for high performance...

Break and continue Statements

Python offers the break and continue statements, which alter the flow of control. The break statement, when executed in a while or for structure, causes immediate exit from that structure. Program execution continues with the first statement after the structure. Figure 3.24 demonstrates the break statement in a for repetition structure. When the if structure detects that x equals 5, it executes the break statement. This terminates the for statement and the program continues with the print...

Common Programming Error

Failure to indent all statements that belong to an if suite or an else suite results in a syntax error. The flowchart of Fig. 3.4 illustrates the flow of control in the if else structure. Once again, note that besides small circles and arrows the symbols in the flowchart are rectangles for actions and diamonds for decisions . We continue to emphasize this action decision model of computing. Imagine again a bin containing empty double-selection structures. The programmer's job is to assemble...

If Selection Structure

Selection Structure Flow Chart

Selection structures choose among alternative courses of action. For example, suppose that the passing grade on an examination is 60. Then the pseudocode statement If student's grade is greater than or equal to 60 PrintPassed determines whether the condition student's grade is greater than or equal to 60 is true or false. If the condition is true, then Passed is printed, and the next pseudocode statement in order is performed. Remember that pseudocode is not a real programming language. If the...

Structured Programming Summary

Structures Flowchart

Just as architects design buildings by employing the collective wisdom of their profession, so should programmers design their programs. The field of computer programming is younger than architecture, and our collective wisdom is considerably sparser. We have learned that structured programming produces programs that are easier than unstructured programs to understand and hence are easier to test, debug, modify, and even prove correct in a mathematical sense. Figure 3.32 summarizes Python's...

While Repetition Structure

A repetition structure allows the programmer to specify that a program should repeat an action while some condition remains true. The pseudocode statement While there are more items on my shopping list Purchase next item and cross it off my list 26, Nov 16 2001, 11 44 11 MSC 32 bit Intel on copyright, credits or license for more informa- describes the repetition that occurs during a shopping trip. The condition, there are more items on my shopping list is either true or false. If it is true,...

Write A Program That Prints The Following Patterns Separately In Python

3.3 Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several tankfuls of gasoline by recording miles driven and gallons used for each tankful. Develop a Python program that prompts the user to input the miles driven and gallons used for each tank-ful. The program should calculate and display the miles per gallon obtained for each tankful. After processing all input information, the program should calculate and print the combined miles per gallon...

Example A Game of Chance

One of the most popular games of chance is a dice game known as craps, which is played in casinos and back alleys throughout the world. The rules of the game are straightforward A player rolls two dice. Each die has six faces. These faces contain 1, 2, 3, 4, 5 and 6 spots. After the dice have come to rest, the sum of the spots on the two upward faces is calculated. If the sum is 7 or 11 on the first throw, the player wins. If the sum is 2, 3 or 12 on the first throw called craps , the player...

Introduction

Before writing a program to solve a particular problem, it is essential to have a thorough understanding of the problem and a carefully planned approach to solving the problem. When writing a program, it is equally essential to understand the types of building blocks that are available and to use proven program-construction principles. In this chapter, we discuss these issues in our presentation of the theory and principles of structured programming. The techniques that you learn are applicable...