• Tidak ada hasil yang ditemukan

Python Programming AN INTRODUCTION TO COMPUTER SCIENCE

N/A
N/A
Tang NingJun

Academic year: 2023

Membagikan "Python Programming AN INTRODUCTION TO COMPUTER SCIENCE"

Copied!
554
0
0

Teks penuh

It takes a fairly traditional approach, emphasizing problem solving, design and programming as core computer science skills. In addition to using Python, there are other features in this book designed to make it a gentler introduction to computer science.

Chapter 1

Program Power

First, the instructions that make up the program are copied from the (more) permanent secondary memory to the computer's main memory. The dotted line in the diagram represents the execution of the machine code (also known as "running the program").

Figure  1.1:  Functional view of a computer
Figure 1.1: Functional view of a computer

Chapter 2

The Software Development Process

For simple programs, this involves carefully describing what the input and output of the program will be and how they relate to each other. Testing/debugging the program Try out your program and see if it works as expected.

Example Program: Temperature Converter

During the debugging phase, your goal is to find bugs, so try anything you can think of that might "break" the program. Maintain the Program Continue to develop the program in response to the needs of your users.

Elements of Programs

  • Names
  • Expressions

When you type an expression into a Python shell, the shell evaluates the expression and prints a textual representation of the result. As you can see, the effect is to create a new string that is the result of "gluing" the threads together.

Output Statements

The first indicates that a print statement can consist of the function name print followed by a series of expressions in parentheses, separated by commas. Notice how the output of the first print statement ends with a space instead of a line break character.

Assignment Statements

  • Simple Assignment
  • Assigning Input
  • Simultaneous Assignment

I usually put a space at the end of a prompt so that the input the user types doesn't start right next to the prompt. Concurrent assignment can also be used to get multiple numbers from the user in a single input.

Figure  2.1:  Variable as box view of  x =  x  +  1
Figure 2.1: Variable as box view of x = x + 1

Definite Loops

The extent of the body is indicated by its indentation below the loop header (for . in : part). When the body is finished, the program returns to the loop header and searches for another value in the sequence.

Figure  2.3:  Flowchart of a  for loop
Figure 2.3: Flowchart of a for loop

Example Program: Future Value

When Python reaches the head of the loop, it checks to see if there are any elements left in the sequence. The loop closes when there are no more items and the program moves on to the statements that come after the loop.

Chapter Summary

A Python list is often used in a for loop to provide a sequence of values ​​for the loop. An important use of a for statement is to implement a counted loop, which is a loop designed specifically for the purpose of repeating a portion of the program a specified number of times. A counted loop in Python is created by using the built-in range function to produce a sequence of numbers of the appropriate size.

Exercises

A user-friendly program should print an introduction that tells the user what the program does. The program should prompt the user for the annual rate and the number of times the interest is compounded each year (periods). The program should allow the user to type a mathematical expression and then print the value of the expression.

Chapter 3

Numeric Data Types

As the table shows, Python (as of version 3.0) provides two different operators for division. II) is used to indicate division of integers. Consider division of integers as 'gozinta'. The expression 10 I I 3 yields 3 because three gozinta (goes into) three times ten (with a remainder of one). Note again that the data type of the result depends on the type of operands.

Table  3.1:  Python built-in numeric operations
Table 3.1: Python built-in numeric operations

Type Conversions and Rounding

As an example application, suppose we calculated the value of our loose change in cents (instead of dollars). If you want a rounded result, you can add 0.5 to the value before using int 0, assuming the value is positive. As a matter of good practice, you should use appropriate type conversion functions instead of eval wherever possible.

Using the Math Library

An added advantage is that this version of the program emphasizes that the inputs must be integers. This program uses the square root sqrt function from the math library module. In general, if your program requires a common math function, the math library is the first place to look.

Accumulating Results: Factorials

Once we realize that this is the pattern that solves the factorial problem, we just need to fill in the details. What we really want is a program that can calculate the factor for a given input n. Given our input value n, we have a few different range commands that produce a suitable list of factors for calculating the factor of n.

Limitations of Computer Arithmetic

The problem in this Java program is that it represents integers using the computer's basic int data type and relies on the computer's multiplication operation for int. The reason for the -1 at the top end is to account for the representation of 0 in the top half of the range. Of course, in order to perform operations on larger numbers, Python must break the operations down into smaller units that the computer's hardware can handle - much like you might do long division by hand.

Chapter Summary

These operations won't be as efficient (they require more steps), but they allow our Python ints to grow to arbitrary size. Numerical results are often calculated by calculating the sum or product of a series of values. Both ints and floats are represented on the underlying computer using a fixed-length sequence of bits.

Exercises

Information that is stored and manipulated by computers is called data

Since floating-point numbers are extremely accurate, they should gener- ally be used instead of ints

Operations like addition and subtraction are defined in the math library

The sqrt function computes the squirt of a number

The float data type is identical to the mathematical concept of a real num

Computers represent numbers using base-2 (binary) representations

A hardware float can represent a larger range of values than a hardware int

Type conversion functions such as float are a safe alternative to eval for getting a number as user input

Which of the following is not a built-in Python data type?

Which of the following is not a built-in operation?

In order to use functions in the math library, a program must include a) a comment b) a loop c) an operator d) an import statement

In a mixed-type expression involving ints and floats, Python will convert a) floats to ints b) ints to strings

Which of the following is not a Python type-conversion function?

The pattern used to compute factorials is a) accumulator b) input, process, output

In modern Python, an int value that grows larger than the underlying hardware int

Translate each of the following mathematical expressions into an equiva

Show the sequence of numbers that would be generated by each of the following range expressions

Show the output that would be generated by each of the following pro

What do you think will happen if you use a negative number as the second parameter in the round function? For example, what should be the result

What do you think will happen when the operands to the integer division or remainder operations are negative? Consider each of the following

Write a program to calculate the volume and surface area of a sphere from its radius, given as input. Here are some formulas that might be useful

Write a program that computes the molecular weight of a carbohydrate (in grams per mole) based on the number of hydrogen, carbon, and oxygen

Write a program that determines the distance to a lightning strike based on the time elapsed between the flash and the sound of thunder. The speed

Write a program that accepts two points (see previous problem) and de

Write a program to calculate the area of a triangle given the length of its three sides-a, b, and c-using these formulas

Write a program to determine the length of a ladder required to reach a given height when leaned against a house. The height and angle of the

Write a program that queries the user for a 4-digit year and then outputs the epact value. The program should prompt the user for n, the number of terms to add, and then output the sum of the first n terms of this series. A Fibonacci sequence is a sequence of numbers where each consecutive number is the sum of the previous two.

You have seen that the math library contains a function that computes the square root of numbers. In this exercise, you are to write your own

Chapter 4

Overview

It covers a number of principles for designing and implementing software, principles that we will return to often throughout this book. During this process, you will also learn the principles of computer graphics that underlie many modern computer applications. Still, at this point in your programming career, learning the intricacies of any GUI framework would be challenging, and would not contribute much to the main objectives of this chapter, which are to introduce you to objects and the fundamental principles. . To make learning these basic concepts easier, we will use a graphics library. Pictures.

The Object of Objects

A student object would contain certain data such as name, ID number, courses taken, campus address, home address, GPA, etc. In our example, each course in the college can also be represented by an object. For example, course objects know who the instructor is, which students are taking the course, what the requirements are, and when and where the course takes place.

Simple Graphics Programming

Notice the use of dot notation to call the GraphWin function that "lives" in the graphics library. We will use quite a few commands from the graphics library and it will become tedious to type "graphics". record every time we use it. All other graphics examples will assume that the entire graphics module has been imported using from.

Figure 4.1:  Screen shot with a Python shell and a GraphWin
Figure 4.1: Screen shot with a Python shell and a GraphWin

Using Graphical Objects

The set of messages that an object responds to are called the methods of the object. Other methods change the values ​​of an object's instance variables, thus changing the state of the object. The graphics library offers a better solution; all graphics objects support a clone method that makes a copy of the object.

Figure 4.4:  The variable  p  refers to a new  Point
Figure 4.4: The variable p refers to a new Point

Graphing Future Value

Recall that the window size is given in terms of the number of pixels in each dimension. To find the upper right corner of the row, we add 25 (row width) to the x value of the lower left corner. The variable xll stands for x lower left - the value of x in the lower left corner of the line.

Table 4. 1: Table showing growth of $2000 at 10% interest
Table 4. 1: Table showing growth of $2000 at 10% interest

Choosing Coordinates

Another benefit of this approach is that the size of the window can be changed simply by changing the dimensions used when the window is created (eg. Because the same coordinates span the window (due to setCoords) the objects will be scaled to compatible with the new original program, all calculations must be redone to fit.

Interactive Graphics

Fortunately, the graphics library provides an Entry object that allows the user to actually type input right into a GraphWin. The difference is that the content of an Entry can be edited by the user. Note that the point where the user clicks is not even saved; the getMouse method is only used to pause the program until the user has a chance to enter a value in the input box.

Graphics Module Reference

This example can be made much nicer by using some of the options in the graphics library to change the colors, sizes, and line widths of the various widgets. One of the biggest hurdles to learning an API is familiarizing yourself with the different data types used. As you read through the reference, pay close attention to the types of parameters and return values ​​of the vari.

Figure 4.10:  Graphical temperature converter after user input
Figure 4.10: Graphical temperature converter after user input

0 , getP2 0 Returns a clone of the corresponding point used to con

  • Chapter Summary
  • I Exercises
  • Using graphics . py allows graphics to be drawn in a Python shell window
  • Traditionally, the upper-left comer of a graphics window has coordinates (0,0)
  • A single point on a graphics screen is called a pixel
  • A function that creates a new instance of a class is called an accessor
  • Instance variables are used to store data inside an object
  • Aliasing occurs when two variables refer to the same object
  • The copy method is provided to make a copy of a graphics object
  • A method that returns the value of an object's instance variable is called a(n)
  • A method that changes the state of an object is called a(n) a) stator b) mutator c) constructor d) changor
  • What graphics class would be best for drawing a square?
  • What command would set the coordinates of win to go from (0,0) in the lower-left corner to (10, 10) in the upper-right?
  • What expression would create a line from (2,3) to (4,5)?
  • What command would be used to draw the graphics object shape into the graphics window win?
  • Which of the following computes the horizontal distance between points
  • What kind of object can be used to get text input in a graphics window?
  • A user interface organized around visual elements and user actions is called a(n)
  • Describe what happens when the following interactive graphics program runs
  • Alter the program from the last discussion question in the following ways
  • An archery target consists of a central circle of yellow surrounded by con
  • Write a program that draws some sort of face
  • Write a program that draws a winter scene with a Christmas tree and a snowman
  • Modify the graphical future value program so that the input (principal and APR) also are done in a graphical fashion using Entry objects
  • Circle Intersection
  • Line Segment Information
  • Triangle Information

Image(anchor point, filename) Constructs an image from the contents of the given file, centered at the given anchor point. In this case, a blank (transparent) image is created of the given width and height (in pixels). The door must have a total width that is � of the width of the house frame.

Chapter 5

Programming an Encoder

It is easy to get the message from the user; an input takes care of that for us.

Programming a Decoder

Then we'll split the large string into a sequence of smaller strings, each of which represents one of the numbers. This number is converted to the corresponding Unicode character via chr and appended to the end of the accumulator message. This program converts a sequence of Unicode numbers into the text string it represents.

More String Methods

I called the loop variable numStr to emphasize that its value is a string of digits that represents some number. Each time you go through the loop, the next substring is converted to a number by entering it. When the loop is finished, each number in the inString has been processed and the message contains the decoded text.

String Formatting

The information inside the curly brackets tells what value goes into the slot and how the value should be formatted. The part of the description after the colon specifies what the value should look like when inserted into the slot. You can change the default behavior by including an explicit justification character at the beginning of the format specifier.

Better Change Counter

Normally a statement ends at the end of the line, but sometimes it's nicer to break a long condition. The zero before the justification character tells Python to pad the field (if necessary) with zeros instead of spaces. I began the chapter with a reference to word processing as an application of the string data type.

Multi-line Strings

In this case, it is OK, and preferable, to break the statement across two lines rather than having one really long line. A critical feature of any word processor is the ability to save and retrieve documents as files on disk. In this section, we'll take a look at file input and output, which, as it turns out, is really just another form of string processing.

Goodbye 32

  • File Processing

In programming terminology, the file is opened for reading, and the contents of the file are then read into memory via file read operations. The entire contents of the file are then read as one large string and stored in the variable. The dialog allows the user to either enter the name of the file or simply select it with the mouse.

Figure  5.2:  File dialog box from  askopenfil ename
Figure 5.2: File dialog box from askopenfil ename

Chapter 6 Defining Functions

  • The Function of Functions
  • Functions, Informally
  • Future Value with a Function
  • Functions and Parameters: The Exciting Details

Failure to keep related pieces of code in sync is a common problem in program maintenance. Note that the only difference between singFred and singLucy is the name at the end of the third print statement. Remember, the problem is that the graph bars are drawn in two different places in the program.

Gambar

Figure  1.1:  Functional view of a computer
Figure  1.2:  Compiling a high-level language
Figure  1.3:  Interpreting a high-level language
Figure  2.2:  Variable as sticky note  (Python) view of  x =  x  +  1
+7

Referensi

Dokumen terkait

Dari hasil analisa uji t didapatkan nilai t hitung sebesar 2,029 dan nilai signifikansi 0,046. Dasar pengambilan keputusan sebagai berikut:.. b) Didapatkan nilai

Interface yang lebih baik: misalnya data history pelanggan yang ditampilkan dengan jelas ke customer service officer yang melayani pelanggan di telepon.. Pemanfaatan sumber daya yang