• Tidak ada hasil yang ditemukan

Fundamentals of Python: First Programs, Second Edition

N/A
N/A
Nguyễn Gia Hào

Academic year: 2023

Membagikan "Fundamentals of Python: First Programs, Second Edition"

Copied!
498
0
0

Teks penuh

For valuable information on pricing, previous editions, changes to current editions, and alternate formats, visit www.cengage.com/highered to search for material in your area of ​​interest by ISBN, author, title, or keyword. Buy any of our products at your local college store or at our favorite online store www.cengagebrain.com.

Why Python?

If students learn these ideas well in the first course, they should have no problem transitioning quickly to other languages ​​needed for courses later in the curriculum.

Some of these are then integrated into more realistic applications, to show how object-oriented software components can be used to build complex systems. Enough material is presented to enable you to perform simple runtime and memory usage analysis of algorithms and data structures, using search and sort algorithms as examples.

An Image Processing Software Toolkit - This book comes with an open-source Python toolkit for the simple image processing discussed in Chapter 7. A Software Toolkit for GUI Programming - This book comes with an open-source Python toolkit for the easy GUI programming introduced in Chapter 8.

The toolkit can be obtained from the student download page at www.cengage.com or at http://home.wlu .edu/~lambertk/python/. The toolkit can be obtained from the student download page at www.cengage.com or at http://home .wlu.edu/~lambertk/breezypythongui/.

The following learning tools are available for download at the companion site for this text. If an input file is required to run the program, it is included in the source code.

We Appreciate Your feedback

Use the content and learning path as is, or pick and choose how our materials wrap yours. If an input file is required to run the programming exercise, it is included in the solution file.

Acknowledgments

After completing this chapter, you will be able to describe the basic features of an algorithm. Computer technology plays an important role in entertainment, education, medicine, manufacturing, communication, government and commerce.

It's hard to imagine our world without computation, even if we don't think much about the actual computers. It's also hard to imagine that humanity got by without computer technology for thousands of years, and that computer technology has only shaped the world as we know it in the last 30 years or so.

Otherwise, move to the next column on the left and return to step 3. If a computer agent (in this case, a human) correctly follows each of these simple steps, the result of the entire process is the correct solution to the given problem.

It is important to know that algorithms that describe information processing can also be represented as information. Computer scientists have been able to present algorithms in a form that machines can execute efficiently and effectively.

The algorithms are converted to binary form and then loaded with their data into the computer's memory. Another important function of an operating system is to provide user interfaces—that is, ways for the human user to interact with the computer's software.

In the seventeenth century, the French mathematician Blaise Pascal built one of the first mechanical devices to automate the addition process (see Figure 1-5b). Jacquard's loom was designed to accept input in the form of a set of punched cards.

Figure 1-4  Summary of major developments in the history of computing
Figure 1-4 Summary of major developments in the history of computing

Getting Started with python programming

The IDLE programming environment uses color coding to help the reader pick out different elements in the code. When the script is run from the IDLE window, it produces the interaction with the user in the shell window shown in Figure 1-8.

Figure 1-6  Python shell window
Figure 1-6 Python shell window

Detecting and Correcting Syntax errors

However, in compensation, the Python language is much simpler than other programming languages. Why Python code generates fewer types of syntax errors than code in other programming languages.

Suggestions for Further reading

As a result, there are fewer types of syntax errors to encounter and fix, and much less syntax to learn. Suppose your script tries to print the value of a variable that has not yet been assigned a value.

Summary

SOFTWARE

Every year, almost everyone with an income faces the unpleasant task of calculating his/her income tax return. The program calculates the income tax based on the inputs and the tax law and then displays the income tax.

Figure 2-2  Relative costs of repairing mistakes that are found in different phases
Figure 2-2 Relative costs of repairing mistakes that are found in different phases

Strings, assignment, and Comments

When this happens to the variable name for the first time, it is called to define or initialize the variable. After you initialize a variable, subsequent uses of the variable name in expressions are known as variable references.

table 2-2  Literals for some Python data types
table 2-2 Literals for some Python data types

Numeric Data types and Character Sets

In the 1960s, the original ASCII set encoded each keyboard character and several control characters using integers from 0 to 127. As new function keys and some international characters were added to keyboards, the ASCII set doubled in size to 256 distinct ones. values ​​in the mid-1980s. Then, as characters and symbols were added from languages ​​other than English, the Unicode set was created to support 65,536 values ​​in the early 1990s.

Table 2-5 shows the mapping of character values to the first 128 ASCII codes. The digits in  the left column represent the leftmost digits of an ASCII code, and the digits in the top row  are the rightmost digits
Table 2-5 shows the mapping of character values to the first 128 ASCII codes. The digits in the left column represent the leftmost digits of an ASCII code, and the digits in the top row are the rightmost digits

With the exception of exact division, when both operands of an arithmetic expression are of the same numeric type (int or float), the resulting value is also of that type. When each operand is of a different type, the resulting value is of a more general type. When you're working with a handheld calculator, you don't think much about the fact that you're mixing integers and floating-point numbers.

table 2-6  Arithmetic operators
table 2-6 Arithmetic operators

If you are unsure of the data type associated with a particular function's arguments, read the documentation. For example, the statement of math import * imports all resources of the math module. Also note that the different parts of the program are separated by white space (blank lines).

Figure 2-5  A terminal window on a Macintosh
Figure 2-5 A terminal window on a Macintosh

Definite Iteration: the for Loop

Most often, off-by-one errors arise when the programmer incorrectly specifies the upper bound of the loop. The format string can contain string data and other information about the format of the date. The format of the outputs is guided by the requirement that they be nicely aligned in columns.

Figure 3-1  The user interface for the investment report programEnter the investment amount: 10000.00
Figure 3-1 The user interface for the investment report programEnter the investment amount: 10000.00

When a condition evaluates to True, the corresponding action is performed and control passes to the end of the entire select statement. The first rule of thumb is to make sure that all possible branches or alternatives in a select statement are exercised. Finally, you must test conditions that contain compound Boolean expressions using data that produces all possible combinations of operand values.

Figure 3-2  The semantics of the  if-else  statementtrue
Figure 3-2 The semantics of the if-else statementtrue

Conditional Iteration: the while Loop

The while loop is also called an entry control loop, because its condition is tested at the top of the loop. The output is a floating-point number representing the square root of the input number. A more orthodox use of the while loop would compare the difference to the tolerance in the loop header.

Write a program that allows the user to enter the initial height from which the ball was dropped and the number of times the ball can continue to bounce. Write a program that allows the user to specify the number of iterations used in this approximation and that displays the resulting value. The inputs are the starting salary, the percentage increase, and the number of years in the schedule.

The programmer counts down from –1 to access characters from the right end of the string. When the integer is omitted on either side of the colon, all characters extending to the end or beginning are included in the substring. Write a code segment that uses a loop to print the characters of the string in reverse order.

Data encryption

For positive spacings, the method goes back to the beginning of the sequence to locate the replacement characters for those characters at the end. This decoding method continues to the end of the sequence to find a replacement character for a character that is near the beginning. Note the enveloping effect for the last three plaintext characters, whose ciphertext characters begin at the beginning of the alphabet.

Figure 4-2  A Caesar cipher with distance 13 for the  lowercase alphabet
Figure 4-2 A Caesar cipher with distance 13 for the lowercase alphabet

Strings and Number Systems

In the following discussion, we occasionally refer to a binary number as a bit string or a bit string. 9 for the corresponding integers and the letters A. The conversion between numbers in the two systems works as follows. Each digit in the hexadecimal number is equal to four digits in the binary number.

table 4-1  The numbers 0 through 8 in binary
table 4-1 The numbers 0 through 8 in binary

String Methods

Thus, in our example, the method split builds a list of the words in the string object that the statement refers to and returns it. You can see the complete list and documentation of the string methods by typing dir(str) at a shell prompt; you enter. The split method returns a list of words in the string on which it was called.

When reading data from a file, another important consideration is the format of the data items in the file. Write a segment of code that opens a file called myfile.txt for input and prints the number of lines in the file. Write a segment of code that prints the names of all items in the current working directory.

table 4-4  Relative pathnames from current directory to myfile.txt in Figure 4-6
table 4-4 Relative pathnames from current directory to myfile.txt in Figure 4-6

Lists

Note that the subscript action refers to the target of the assignment statement, which is not the list, but the position of an element in it. When the index is greater than or equal to the length of the list, the new element is added to the end of the list. The add method expects only the new element as an argument and adds the new element to the end of the list.

Table 5-1 summarizes these operators and functions, where  L  refers to a list.
Table 5-1 summarizes these operators and functions, where L refers to a list.

Defining Simple Functions

Note that the argument name, also called a parameter, acts just like a variable in the body of the function. For example, the sentence "The girl hits the ball with the bat" contains three noun phrases, one verb phrase, and one prepositional phrase. So, a possible noun phrase is "the bat." Note that some of the phrases in the left column of Table 5-3 also appear in the right column as constituents of other phrases.

Dictionaries

The dictionary associates each unique word with the number of its occurrences in the list. So, to "My teacher always plays favorites," the program might answer, "Why do you say your teacher always plays favorites?". For example, when the program sees "I" in a patient's input, it should respond with a sentence containing "you". The best type of data structure to hold these correlations is a dictionary.

Figure 5-4 shows the program’s interface as it changes throughout a sequence of  exchanges with the user.
Figure 5-4 shows the program’s interface as it changes throughout a sequence of exchanges with the user.

There is no need to edit the parts of the program that call the function. The problem instances for our addition algorithm are the pairs of numbers that specify the lower and upper bounds of the range of numbers to be added. Each function is responsible for using some data, calculating some results, and sending it back to the parts of the program that requested it.

The design of the sentence generator differs from the design of the text parser in another important way. In contrast, the functions in the sentence generator get their data from a common data set defined at the beginning of the module and shown at the bottom of Figure 6-2. At the highest level, the designs of the doctor program (Section 5.5) and the sentence generation program are similar.

Figure 6-1  A structure chart for the text-analysis program string
Figure 6-1 A structure chart for the text-analysis program string

Design with recursive Functions

The loop’s body continues execution while lower < = upper

Each call to the recursive function visits the next number in the sequence, just as the loop does in the iterative version of the function. Earlier in this chapter, we defined an iterative version of the summation function that takes two arguments, called lower and upper. The addition function calculates and returns the sum of the numbers between these two values.

Gambar

Figure 1-4  Summary of major developments in the history of computing
Figure 1-5  Some early computing devices
Figure 1-5  (Continued)
Figure 1-6  Python shell window
+7

Referensi

Dokumen terkait

Are you having trouble in converting your website visitors into customers? Well here in this blog we have break down top 10 web design techniques to turn visitors