• Tidak ada hasil yang ditemukan

Fundamentals of Python Programming

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

Academic year: 2023

Membagikan "Fundamentals of Python Programming"

Copied!
669
0
0

Teks penuh

Preface

The Context of Software Development

  • SOFTWARE 2
  • Software
  • Development Tools
  • DEVELOPMENT TOOLS 3 by most humans, are inherently ambiguous. To understand properly all but a very limited subset of a
  • Learning Programming with Python
  • Writing a Python Program
  • WRITING A PYTHON PROGRAM 6
  • WRITING A PYTHON PROGRAM 7 Figure 1.3 The new, untitled editor pane ready for code
  • WRITING A PYTHON PROGRAM 8
  • The Python Interactive Shell
  • THE PYTHON INTERACTIVE SHELL 10 Figure 1.12 Running a Python program from the command line
  • A Longer Python program
  • Exercises

When debugging the program, the output of the executing program appears in the Debug I/Opane as shown in Figure 1.10. As we'll see later (see Section 5.7), the debug option gives developers more control over program execution, so save the Python program during development.

Figure 1.1 WingIDE 101 running under Microsoft Windows
Figure 1.1 WingIDE 101 running under Microsoft Windows

Values and Variables

Integer and String Values

INTEGER AND STRING VALUES 14

INTEGER AND STRING VALUES 15 beginning of a string, and the right ' symbol that follows specifies the end of the string. If a single quote

INTEGER AND STRING VALUES 16

Variables and Assignment

In Python, = causes the variable on the left to take the value of the expression on the right. It is best to read x = 5 as "xis ​​assigned the value 5", or "x is given the value 5." This distinction is important because equality in mathematics is symmetric: if x=5, we know 5=x.

VARIABLES AND ASSIGNMENT 19 This program demonstrates that can we cannot always predict the behavior of a statement in isolation,

VARIABLES AND ASSIGNMENT 20 Figure 2.1 Binding a variable to an object

VARIABLES AND ASSIGNMENT 21 Figure 2.2 How variable bindings change as a program runs: step 1

VARIABLES AND ASSIGNMENT 22

VARIABLES AND ASSIGNMENT 23

Identifiers

IDENTIFIERS 25 Table 2.1 Python keywords

FLOATING-POINT NUMBERS 26

Floating-point Numbers

FLOATING-POINT NUMBERS 27 Table 2.2 Characteristics of Floating-point Numbers

Truncation simply removes the fractional part of the floating-point number, thus keeping the integer part that remains. We can also use the round function to round a floating point number to a specified number of decimal places.

FLOATING-POINT NUMBERS 29

Control Codes within Strings

USER INPUT 31

User Input

We can express Listing 2.13 (addintegers.py) more compactly by using this form of the input function, as shown in Listing 2.14 (addintegers2.py). The result of the import function is passed directly to the int function instead of using the intermediate variables shown in Listing 2.14 (addintegers2.py).

USER INPUT 33 Be careful about code such as

CONTROLLING THE PRINT FUNCTION 34

Controlling the print Function

String Formatting

STRING FORMATTING 36 print(2, 10**2)

This format string serves as a template that the second part of the expression will use.{0}and{1}. The first argument, 2, will take the position of the {0}position parameter in the format string.

STRING FORMATTING 38 Figure 2.8 Placeholder substitution within a formatting string

MULTI-LINE STRINGS 39

Multi-line Strings

Exercises

EXERCISES 42 (u) wilma's

Expressions and Arithmetic

Expressions

EXPRESSIONS 44 Table 3.1 Commonly used Python arithmetic binary operators

EXPRESSIONS 46 Figure 3.1 Integer division and modulus

EXPRESSIONS 47

EXPRESSIONS 48 The last closing parenthesis on the second line corresponds to the first opening parenthesis on the first line.

EXPRESSIONS 48 The last closing parenthesis on the second line matches the first opening parenthesis on the first line. No

MIXED TYPE EXPRESSIONS 49

Mixed Type Expressions

Operator Precedence and Associativity

OPERATOR PRECEDENCE AND ASSOCIATIVITY 50 Table 3.2 Operator precedence and associativity. The operators in each row have a higher precedence than

Formatting Expressions

Comments

ERRORS 53

Errors

  • Syntax Errors
  • Run-time Exceptions

If the user enters e.g. 32 and 4, the program works fine Please enter two numbers to divide. So far, so good, but what if the user doesn't follow the on-screen instructions.

ERRORS 56

  • Logic Errors

Arithmetic Examples

ARITHMETIC EXAMPLES 58

More Arithmetic Operators

ALGORITHMS 61

Algorithms

Exercises

EXERCISES 63 2. Is the variable x a valid Python expression?

EXERCISES 64 (q) d1/d2*i1

EXERCISES 65 13. What is the purpose of comments?

Conditional Execution

  • Boolean Expressions
  • Boolean Expressions
  • The Simple if Statement
  • THE SIMPLE IF STATEMENT 70 print('Please enter two numbers to divide.')
  • THE SIMPLE IF STATEMENT 71
  • THE SIMPLE IF STATEMENT 72 if must be indented more spaces than the line that begins the if statement. The block technically is
  • THE SIMPLE IF STATEMENT 73
  • THE SIMPLE IF STATEMENT 74 to use the relational equality operator ( == ), not the assignment operator ( = )
  • The if/else Statement
  • THE IF/ELSE STATEMENT 76

One way Listing 3.6 (divedanger.py) can fail is when the user enters a zero for the divider. Listing 4.3 (alternatedivision.py) optionally executes two statements depending on the input values ​​provided by the user. In Listing 4.4 (leadingzeros.py), the two if statements at the beginning ensure that the number is in range.

An undesirable aspect of Listing 4.2 (betterdivision.py) is that if the user enters a zero divisor, the program prints nothing. A given run of Listing 4.5 (betterfeedback.py) will execute exactly one of either theifblock or elseblock. Theelseblock contains an alternative block of code that the program executes when the condition is false.

COMPOUND BOOLEAN STATEMENTS 77 Listing 4.5 (betterfeedback.py) avoids the divide-by-zero runtime error that causes the program to drop Listing 4.5 (betterfeedback.py) avoids the divide-by-zero runtime error that causes the program to terminate prematurely terminated, but it still warns the user that there is a problem.

Table 4.2 Examples of some Simple Relational Expressions
Table 4.2 Examples of some Simple Relational Expressions

Compound Boolean Expressions

COMPOUND BOOLEAN EXPRESSIONS 78 Table 4.3 Logical operators—e 1 and e 2 are Boolean expressions

Some programmers prefer to use the parentheses as shown here, although they are not required. The parentheses improve the readability of complex expressions, and the interpreted code is no less efficient.

The pass Statement

Floating-point Equality

Nested Conditionals

NESTED CONDITIONALS 84 message. From this perspective, the program can be rewritten to behave the same way with only one if

NESTED CONDITIONALS 85 Figure 4.3 The base 10 place value system

NESTED CONDITIONALS 86 binary_string += '1'

NESTED CONDITIONALS 87 Figure 4.5 The process of the binary number conversion program when the user supplies 805 as the input

NESTED CONDITIONALS 88 value %= 256

NESTED CONDITIONALS 89 Figure 4.6 Decision tree for troubleshooting a computer system

NESTED CONDITIONALS 91 print(minutes, end='')

In Listing 4.16 (timeconvcond2.py), each code segment responsible for printing a time value and its associated English word unit is protected by a statement that only allows the code to run if the time value is greater than zero. The exception is the handling of seconds: if all time values ​​are zero, the program should print 0 seconds. Note that each of the if/else statements responsible for determining the singular or plural form is nested within the if statement that determines whether the value is printed at all.

MULTI-WAY DECISION STATEMENTS 93

Multi-way Decision Statements

The if/elif/else statement is valuable for choosing exactly one block of code to execute from several different options.

MULTI-WAY DECISION STATEMENTS 95

Anif/elif/elsestatement that omits theelsblock may fail to execute code in any of its blocks if none of its conditions evaluates to true.

MULTI-WAY VERSUS SEQUENTIAL CONDITIONALS 97

Multi-way Versus Sequential Conditionals

MULTI-WAY VERSUS SEQUENTIAL CONDITIONALS 98

Conditional Expressions

CONDITIONAL EXPRESSIONS 100

CONDITIONAL EXPRESSIONS 101 This code assigns to variable c one of two possible values. As purely a syntactical convenience, Python

Errors in Conditional Statements

Please enter an integer between 0..5: 7 The entered number was not within the range. Of course, the program crashes with an error if the user enters a non-integer value (the int function will throw an exception), but the program should accept any integer value and always do the right thing. Please enter an integer between 0..5: 3 The number entered was not within the range.

The program resets the originalanswer variable for each option, except when the user supplies the value 3. When the user enters 3, the program creates a new variable that is not reported in the final print statement. Listing 4.27 (digittoworderror.py) is small and focused, so the logic error introduced by the misspelled variable was easy to find.

As our programs grow in size and our logic becomes more complex, a typo that creates a new variable can sometimes be hard to find without it.

Logic Complexity

Listing 4.28 (max4a.py) uses a multiwayif/elif/else construct to select the correct value to assign to its maxvariable. Listing 4.28 (max4a.py) works correctly for any four integers a user may enter, but its logic is somewhat complicated. Ifn2 is greater than max, change maxto haven2's value to reflect the fact that we have determined n2 is greater; ifn2 is not greater than max, we have no reason to change max, so don't change it.

Ifn3 is greater than max, change maxto haven3's value to reflect the fact that we have determined n3 is greater; ifn3 is not greater than max, we have no reason to change max, so don't change it. Ifn4 is greater than max, maxna changes haven4's value to reflect the fact that we determine n4 is greater; ifn4 is not greater than max, we have no reason to change max, so don't change it. In the end, the meaning of the maximum variable remains the same – "maximum I have determined so far".

Listing 4.29 (max4b.py) uses our revised selection logic to provide an alternative to Listing 4.28 (max4a.py).

EXERCISES 107

Exercises

EXERCISES 109 (w) not b1 and not b2 and not b3

EXERCISES 110

EXERCISES 111

EXERCISES 112

Iteration

  • The while Statement
  • THE WHILE STATEMENT 114
  • THE WHILE STATEMENT 115
  • THE WHILE STATEMENT 116 The executing program checks the condition before executing the while block and then checks the
  • THE WHILE STATEMENT 117 is true if entry is neither N not n
  • THE WHILE STATEMENT 118 Figure 5.2 Decision tree for troubleshooting a computer system
  • THE WHILE STATEMENT 120 Speaking of floating-point values, Section 3.1 demonstrated how the limited precision of floating-point
  • Definite Loops vs. Indefinite Loops
  • The for Statement
  • THE FOR STATEMENT 124
  • THE FOR STATEMENT 125 for i in range(10)
  • Nested Loops
  • NESTED LOOPS 127 Figure 5.3 A 10 × 10 multiplication table
  • NESTED LOOPS 128 for column in range(1, size + 1)
  • NESTED LOOPS 129
  • NESTED LOOPS 130 When the user supplies the value 10, Listing 5.19 ( timestable4.py ) produces
  • NESTED LOOPS 131 1 | 1
  • ABNORMAL LOOP TERMINATION 132
  • Abnormal Loop Termination
  • ABNORMAL LOOP TERMINATION 133 Listing 5.22 ( whileexitattop.py ) prints
    • The break statement
  • ABNORMAL LOOP TERMINATION 135 Figure 5.4 The code on the left generically represents any while loop that uses a break statement. The
  • ABNORMAL LOOP TERMINATION 136
    • The continue Statement
  • while/else and for/else
  • WHILE/ELSE AND FOR/ELSE 138
  • Infinite Loops
  • INFINITE LOOPS 141
  • INFINITE LOOPS 142 We can use a debugger can be used to step through a program to see where and why an infinite loop
  • Iteration Examples
    • Computing Square Root
  • ITERATION EXAMPLES 144 The program is based on a simple algorithm that uses successive approximations to zero in on an answer
    • Drawing a Tree
  • ITERATION EXAMPLES 146
    • Printing Prime Numbers
  • ITERATION EXAMPLES 148 Some important questions must be answered
  • ITERATION EXAMPLES 149 if is_prime never becomes false, the loop ends when trial_factor becomes equal to value . Because of
  • Exercises
  • EXERCISES 151 a = 0
  • EXERCISES 152 10. How many asterisks does the following code fragment print?
  • EXERCISES 154 a = 0
  • EXERCISES 155
  • EXERCISES 156

Listing 5.4 (addnonnegatives.py) is a program that allows the user to enter any number of nonnegative integers. We can use a while statement to make Listing 4.14 (troubleshoot.py) more user-friendly. Listing 5.7 (stopatonefixed.py) uses <= to control the loop instead of != and behaves as expected.

Because of this, the loop in Listing 5.9 (definite2.py) is also considered a definite loop. Listing 5.15 (countvowels.py) counts the number of vowels in user-supplied text. Listing 5.20 (permuteabc.py) uses a triple nested loop to print all the different arrangements of the letters A, B, and C.

Listing 5.21 (permuteabcd.py) uses a four-deep nested loop to print all the different arrangements of the letters A, B, C, and D. The break keyword means "break out of the loop." The placement of the break statement in Listing 5.23 (addmiddleexit.py) makes it impossible to add a negative number to the sum variable. Even in Listing 5.31 (findfactors.py), the debugging task is non-trivial since the program involves nested loops.

Figure 5.1 shows how program execution flows through Listing 5.2 ( iterativecounttofive.py ).
Figure 5.1 shows how program execution flows through Listing 5.2 ( iterativecounttofive.py ).

Using Functions

Introduction to Using Functions

The function is like a black box - callers do not need to know the details of the code inside the function to use it. To introduce the function concept, we will look at the standard Python function that implements the mathematical square root. If an executing program needs to perform such a task, it calls the function to do the work.

The square root function accepts a numeric value (integer or floating point) and produces a floating point result; for example, Callers do not need to know the details of the code inside the function to use it. The new version, Listing 6.1 (standardsquareroot.py), uses the functions of the qrt library, eliminating the complex logic of the original code.

INTRODUCTION TO USING FUNCTIONS 159 is a function invocation, also known as a function call. A function provides a service to the code that uses

As Listing 6.2 (usingsqrt.py) shows, the parameter the caller passes to tosqrt can be a literal number, a numeric variable, an arithmetic expression, or even a function call that produces a numeric result. The caller can use this return value in a variety of ways, as shown in Listing 6.2 (usingsqrt.py). Although we know that we could convert the string parameter '16' to the integer 16 (using the intfunction) or the floating-point value 16.0 (using the float function), the qrt function does not automatically do this for us.

Listing 6.2 (usingsqrt.py) shows that a program can call the sqrt function as many times and in as many places as necessary. Usually we can only influence the function's behavior through the parameters we pass it in, and nothing else we do can affect what the function does or how it does it. Additionally, for the types of objects we've considered so far (integers, floating-point numbers, and strings), when a caller passes data to a function, the function cannot affect the caller's copy of that data.

INTRODUCTION TO USING FUNCTIONS 161 use the function's return value to modify any of its variables.

INTRODUCTION TO USING FUNCTIONS 161 use the return value of function to modify any of its variables. The important distinction is that the caller is

FUNCTIONS AND MODULES 162

Functions and Modules

The interpreter knows where to find these standard modules when the runtime needs to import them. It's not uncommon for a complex program to import a dozen separate modules to get all the functionality it needs to do its job. Themathmodule provides many other math functions—for example, theatanfunction, which calculates the arctangent—but this restricted import statement does not provide the interpreter with these other definitions.

Such an import command is suitable for smaller Python programs that use a small number of functions from a module. This kind of import statement allows callers to use the simple name of an imported function, as in y = sqrt(x). Python offers a way to import everything a module has to offer, as we'll see in Section 6.10, but we'll also see why this isn't desirable.

This import statement makes all functions of the module available to the program, but to use the function, the caller must include the name of the module during the call.

The Built-in Functions

THE BUILT-IN FUNCTIONS 165 9506056

THE BUILT-IN FUNCTIONS 166 import the appropriate modules that provide the needed services

STANDARD MATHEMATICAL FUNCTIONS 167

Standard Mathematical Functions

We wish to calculate how far the satellite will be from the spacecraft when it has progressed °degree along its orbital path. We will let the origin of our coordinate system (0,0) be located at the center of the planet. The satellite is located as a point, (x,y) and the spacecraft is stationary at the point (px,py).

We wish to calculate the distances between the moving point (the satellite) and the fixed point (the spacecraft) as the satellite orbits the planet. Problem: We need to recalculate the location of the moving point as it moves along the circle. Problem: We need to recalculate the distance between the floating point and the fixed point as the floating point moves to a new position.

Solution: The distance in figure 6.4 between two points (px,py) and (x,y) is given by formula.

STANDARD MATHEMATICAL FUNCTIONS 169 Listing 6.3 ( orbitdist.py ) uses these mathematical results to compute a table of distances that span a

TIME FUNCTIONS 171 and Mac OS X), time.clock returns the numbers of seconds elapsed since the program began executing

TIME FUNCTIONS 172 if value % trial_factor == 0

Random Numbers

RANDOM NUMBERS 174 Table 6.2 A few of the functions from the random module

SYSTEM-SPECIFIC FUNCTIONS 176

System-specific Functions

The eval and exec Functions

THE EVAL AND EXEC FUNCTIONS 177 x = float(input('Please enter a number: '))

THE EVAL AND EXEC FUNCTIONS 178 could enter multiple entries separated by commas, and the eval function would evaluate the text typed

Turtle Graphics

TURTLE GRAPHICS 180 Figure 6.6 A very simple drawing made with Turtle graphics

TURTLE GRAPHICS 181 Figure 6.7 The default coordinate system for a Turtle graphics picture. The x and y axes do not appear in an

TURTLE GRAPHICS 182 Figure 6.8 More Turtle graphics fun: a spiral within an octogon

TURTLE GRAPHICS 183

TURTLE GRAPHICS 184 Figure 6.9 Listing 6.20 ( speedvsdelay.py ) demonstrates the different effects of the turtle.speed versus

Other Techniques for Importing Functions and Modules

OTHER TECHNIQUES FOR IMPORTING FUNCTIONS AND MODULES 186 in published Python code

OTHER TECHNIQUES FOR IMPORTING FUNCTIONS AND MODULES 187

OTHER TECHNIQUES FOR IMPORTING FUNCTIONS AND MODULES 188 from math import *

OTHER TECHNIQUES FOR IMPORTING FUNCTIONS AND MODULES 189 t.right(45) # Each vertex is 45 degrees

Gambar

Figure 1.1 WingIDE 101 running under Microsoft Windows
Figure 1.2 The menu selection to create a new Python program.
Figure 1.4 The code for the simple program after typed into the editor pane.
Figure 1.6 The file save dialog allows the user to name the Python file and locate the file in a particular folder.
+7

Referensi

Dokumen terkait

To prove the teacher’s statement, the English teacher was interviewed and observed by recording students’ speaking activity and it was found that most of students spoke English with low