Introduction to Computer. Science Using Python: A Computational. Problem- Solving Focus. Charles Dierbach Title: Python programming: an introduction to computer science I John M. Zelle, Wartburg College. Inside a Python Program. . Using the Math Library. Charles Dierbach is an Associate Professor of computer science at Towson University. He received his Ph.D. in Computer Science from the University of.

Introduction To Computer Science Using Python Pdf

Language:English, German, Arabic
Published (Last):09.05.2016
ePub File Size:24.67 MB
PDF File Size:14.17 MB
Distribution:Free* [*Registration needed]
Uploaded by: GUILLERMO

The Book focuses on computational problem solving from Chapter 1, this text provides numerous hands-on exercises and examples, each chapter ending with a. Introduction to Computer Science Using Python: A Computational Problem- Solving Focus,recommended by Guido van Rossum, the creator of. Python Programming: An Introduction to Computer Science. John M. Zelle Here I have tried out three examples using the Python print statement. The first.

Zelle This book is designed to be used as the primary textbook in a college-level first course in computing With the book, John Zelle has updated his famous introduction to programming using Python to cover Python 3. This book is a more traditional one as its approach to programming is such; it focuses on problem solving, design and implementation, and programming as the fundamental skills of computer science. When you want to get this It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills of computer science.

However, these ideas are illustrated using a non-traditional language, namely Python. Although Python is used as the language, teaching Python is not the main point of this book. Rather, Python is used to illustrate fundamental principles of design and. To be able to create objects in programs and call appropriate methods to perform Python Programming An Introduction to Computer Science 2e Python Programming: This book is designed to be used as the primary textbook in a college-level first course in computing.

It takes a fairly traditional approach, emphasizing problem solving, design, and programming as the core skills John Zelle introduces you to computer science concepts while keeping it in the context of programming. It is a very text heavy book but in no way is the author verbose. He succinctly explains concepts or describes the inner workings of the provided code without getting bogged down in theory. Python Programming: Com Chapter 2 Hello, Python Programs are made up of commands that a computer can understand.

These commands are called statements, which the computer executes. The computer itself is assembled from pieces of hardware, including a processor that can execute instructions and do arithmetic, a place to store data such as a hard drive, and various other pieces such as computer monitor, a keyboard, a card for connecting to a network, and so on.

When any other program on the computer wants to draw on the screen, find out what key was just pressed on the keyboard, or fetch data from the hard drive, it sends a request to the OS see Figure 2. This may seem a roundabout way of doing things, but it means that only the people writing the OS have to worry about the differences between one network card and another.

Everyone else—everyone analyzing scientific data or creating 3D virtual chat rooms—only has to Prepared exclusively for Trieu Nguyen Download at Boykma. Talking to the operating system learn their way around the OS, and their programs will then run on thousands of different kinds of hardware. Instead, another program, called an interpreter or virtual machine, takes your program and runs it for you, translating your commands into a language the OS understands.

One way to do this is to run a text-oriented program called a shell that reads commands from the keyboard, does what they ask, and shows their output as text, all in one window.

Shells exist for various programming languages as well as for interacting with the OS; we will be exploring Python in this chapter using a Python shell. The more modern way to interact with Python is to use an integrated development environment, or IDE. This is a full-blown graphical interface with menus and windows, much like a web browser, word processor, or drawing program. See http: We prefer Wing because it was designed specifically for beginning programmers, but IDLE is a capable development environment.

The Wing interface is shown in Figure 2.

Introduction to Computer Science Using Python

The top part is the editing pane where we will write Python programs; the bottom half, labeled as Python Shell, is where we will experiment with snippets of Python programs. One kind of statement is an expression statement, or expression for short. Like any programming language, Python can evaluate basic mathematical expressions. For example, the following expression adds 4 and The Wing interface When an expression is evaluated, it produces a single result. However, computers do not always play by the rules you learned in primary school.

For example, look at what happens when we divide 17 by Python 3. In Python, an expression involving values of a certain type produces a value of that same type. For example, 17 and 10 are integers—in Python, we say they are of type int.

When we divide one by the other, the result is also an int. If it did, the result would have been 2. Instead, it takes the floor of the intermediate result. Since Python takes the floor of the result of an integer division, the result is one smaller than you might expect: The word float is short for floating point, which refers to the decimal point that moves around between digits of the number. An expression involving two floats produces a float: This is why the following two expressions both return the same answer as the earlier one: In computing, a type is a set of values, along with a set of operations that can be performed on those values.

For example, the type int is the values On the other hand, Arithmetic was invented before Python, so the int and float types have exactly the same operators. We can see what happens when these are applied to various values in Figure 2.

Arithmetic operators Finite Precision Floating-point numbers are not exactly the fractions you learned in grade school. The problem is that real computers have a finite amount of memory, which limits how much information they can store about any single number.

The number 0. To do this, we subtract 32 from the temperature in Fahrenheit and then multiply by This is another floating-point approximation. Because of this, computers can store int values only in a certain range. A modern desktop or laptop machine, for example, can store the numbers only from to Computers can store only approximations to real numbers for the same reason.

The difference between 31 and 0. But if we use that value in a calculation, then the error may get compounded. For example, if we add the float to itself, the result ends in For example, suppose we add 10,,, and 0.

In fact, numerical analysis, the study of algorithms to approximate continuous mathematics, is one of the largest subfields of computer science and mathematics.

This means that what we actually calculated was - We can alter the order of precedence by putting parentheses around parts of the expression, just as we did in Mrs.

These store a value so that it can be used later. In Python, we can do this with a variable, which is just a name that has a value associated with it. You create a new variable simply by giving it a value: And cell phones, and wristwatches, and An assignment statement is executed as follows: In Figure 2. Once a variable has been created, we can use its value in other calculations.

This means that we can create new variables from old ones: For example, we can assign difference a new value: Changes to other variables, like difference, have no effect. We can even use a variable on both sides of an assignment statement: Gets the value currently associated with number 2. Multiplies it by 2 to create a new value 3.

Assigns that value to number Combined Operators In the previous example, variable number appeared on both sides of the assignment statement. This is so common that Python provides a shorthand notation for this operation: For example, we can square a number by multiplying it by itself: File " " , line 1, in NameError: The last line is the one that tells us what went wrong: We can write functions in Python, too.

As in mathematics, they are used to define common formulas. Here is the conversion function in Python: It has these major differences from its mathematical equivalent: The line is indented four spaces and marked with the keyword return.

This is another reason to use Wing instead of a basic text editor like Notepad or Pico: We have to define a function only once; we can call it any number of times. The general form of a function definition is as follows: The name of the function comes next, followed by zero or more parameters in parentheses and a colon. Those actual values are called the arguments to the function. What the function does is specified by the block of statements inside it.

Finally, the return statement has this general form: Function control flow and is executed as follows: Evaluate the expression to the right of the keyword return. Use that value as the result of the function.

Dierbach C. Introduction to Computer Science Using Python: A Computational Problem-Solving Focus

When the function is called, Python jumps to the first line of that function and starts running it see Figure 2. When the function is finished, Python returns to the place where the function was originally called. Local Variables Some computations are complex, and breaking them down into separate steps can lead to clearer code. These variables exist only during function execution; when the function finishes executing, the variables no longer exist. This means that trying to access a local variable from outside the Report erratum Prepared exclusively for Trieu Nguyen this copy is P1.

As you might expect, if a function is defined to take a certain number of parameters, it must be passed the same number of arguments: File " " , line 1, in TypeError: For example, the scope of a local variable runs from the line on which it is first defined to the end of the function.

One example is abs, which produces the absolute value of a number: For example, we can calculate 24 using the power function pow: The type names int and float can be used as if they were functions: As a result, the more inconsistencies there are in a piece of text, the longer it takes to read. Some of your classmates may have strong opinions about this as well.

If they do, ask them what data they have to back up their beliefs, in other words, whether they know of any field studies that prove that spaces after commas make programs easier to read than no spaces. An interpreter or virtual machine is a program that sits on top of the operating system and runs your programs for you. Building layers like this is the best way we have found so far for constructing complicated systems.

These can be simple expressions which are evaluated immediately , assignment statements which create new variables or change the values of existing variables , and function definitions which teach Python how to do new things. The two types used to represent numbers are int and float. However, you can change that order by putting parentheses around subexpressions. For each of the following expressions, what value will the expression give? Verify your answers by typing the expressions into Python.

Unary minus negates a number. Should it leave the sign of the number alone? Should it act like absolute value, removing any negation? Use the Python shell to find out its behavior. Many function names are verb phrases because functions actively do things.

We also assumed the original unit was Fahrenheit, but Kelvin is a temperature scale too, and there are many others see Section 6. Write a paragraph describing which name you think is best and why. Consider ease of remembering, ease of typing, and readability.

In the metric system, it is usually measured in liters per kilometers. Explain the difference between a parameter and an argument. Which of those two functions finishes executing first? Using these functions, write expressions that do the following: Com Chapter 3 Strings Numbers are fundamental to computing—in fact, crunching numbers is what computers were invented to do—but there are many other kinds of data in the world as well, such as addresses, pictures, and music.

Account Options

Each of these can be represented as a data type, and knowing how to manipulate those data types is a big part of being able to program. This chapter introduces a non-numeric data type that represents text, such as the words in this sentence or a strand of DNA.

Along the way, we will see how to make programs a little more interactive. From desktop chat programs to Google, computers create text, store it, search it, and move it from one place to another. In Python, a piece of text is represented as a string, which is a sequence of characters letters, numbers, and symbols. The simplest data type for storing sequences of characters is str; it can store characters from the Latin alphabet found on most North American keyboards.

Another data type called unicode can store strings containing any characters at all, including Chinese ideograms, chemical symbols, and Klingon. We will use the simpler type, str, in our examples. EOL while scanning single-quoted string We can join two strings together by putting them side by side: If we want a space between the words, then we can add a space either to the end of Albert or to the beginning of Einstein: It performs different functions based on the type of operands that it is applied to.

The shortest string is the empty string, containing no characters at all. If so, what function would be applied, addition or concatenation? File " " , line 1, in? The first time, in Section 2. But what about this example? If you write it directly, Python will complain: One simple way to fix this is to use double quotes around the string: Escape sequences If you need to put a double quote in a string, you can use single quotes around the string.

But what if you want to put both kinds of quote in one string? You could do this: If you type the previous expression into Python, the result is as follows: When Python sees a backslash inside a string, it means that the next character represents something special—in this case, a single quote, rather than the end of the string. The backslash is called an escape character, since it signals the start of an escape sequence. As shown in Figure 3. In order to see how most are used, we will have to introduce two more ideas: File " " , line 1, in Could not execute because an error occurred: EOL while scanning single-quoted string: To span multiple lines, put three single quotes or three double quotes around the string instead of one of each.

The string can then span as many lines as you want: In reality, each of the three major operating systems uses a different set of characters to indicate the end of a line. This set of characters is called a newline. Real programs often want to display more information, such as the values of multiple variable values. This can be done using a print statement: This example makes the difference between the two even clearer: And the following example shows that when Python prints a string, it prints the values of any escape sequences in the string, rather than their backslashed representations: A print statement takes a comma-separated list of items to print and displays them on a line of their own.

If no values are given, print simply displays a blank line. You can use any mix of types in the list; Python always inserts a single space between each value: In these cases, we can specify the exact format we want for our output by providing Python with a format string: It indicates where the value of the variable area is to be inserted. Instead, the string formatting operator returns a new string. We can use the string formatting operator to lay out several values at once. Here, for example, we are laying out a float and an int at the same time: As we said earlier, print automatically puts a newline at the end of a string.

To prevent the newline from being added, put a comma at the end of the print statement: File " " , line 1, in ValueError: Multiline strings can be created using matching pairs of triple quotes.

Verify your answers by typing the expressions into the Python shell. For each of the following phrases, express them as Python strings using the appropriate type of quotation marks single, double or triple and, if necessary, escape sequences: Rewrite the following string using single or double quotes instead of triple quotes: Use the built-in function len to find the length of the empty string.

Given variables x and y, which refer to values 3 and When numbers appear in the messages, the variables x and y should be used in the print statement. State whether each expression listed here evaluates to True or False: Some people believe that multiplying a string by a negative number ought to produce an error, rather than an empty string. Explain why they might think this. Instead, they build their proofs on the truths their predecessors have already established.

A module is a collection of functions that are grouped together in a single file. Functions in a module are usually related to each other in some way; for example, the math module contains mathematical functions such as cos cosine and sqrt square root.

This chapter shows you how to use some of the hundreds of modules that come with Python and how to create new modules of your own. You will also see how you can use Python to explore and view images. When you want to use a function from a module, you have to import it.

To tell Python that you want to use functions in the math module, for example, you use this import statement: It provides access to the mathematical functions defined by the C standard. Great—our program can now use all the standard mathematical functions. When we try to calculate a square root, though, we get an error telling us that Python is still unable to find the function sqrt: For example, does the following call to floor refer to the function from the math module that rounds a number down or the function from the completely fictional building module that calculates a price given an area see Figure 4.

Modules can contain more than just functions. The math module, for example, also defines some variables like pi. Once the module has been imported, you can use these variables like any others: As the name suggests, the value of a constant cannot be changed after it has been defined: For this reason, Python lets you specify exactly what you want to import from a module, like this: If you import a function called spell from a module called magic and then you import another function called spell from the module grammar, the second replaces the first.

It saves some typing: The full list is online at http: You can then tell Python to run the code in that file, rather than typing commands in at the interactive prompt. The name of the module is the same as the name of the file, but without the. For example, the following function is taken from Section 2. Put the following in a file called experiment.

Start a fresh Python session, and try importing the experiment module twice in a row: Suppose we put the following into echo. This means that a module can tell whether it is the main program: Knowing whether a module is being imported or not turns out to allow a few handy programming tricks. For example, think about what happens when you run the following on the command line vs. After all, it has only two functions, and their names are pretty descriptive of what they do.

Small programs have a way of turning into larger and more complicated ones. One of the exercises discusses why it needs a separate download. In order to understand how media works, we first have to introduce two concepts that are fundamental to modern program design. And to do that, we have to back up and take another look at strings. There are dozens of other things we might want to do to strings, such as capitalize them, strip off any leading or trailing blanks, or find out whether one string is contained inside another.

These are called just like the functions inside a module. Every string we create automatically shares all the methods that belong to the string data type. The most commonly used ones are listed in Figure 4. Using methods is almost the same as using functions, though a method almost always does something to or with the thing that owns it. String also has an endswith method: Common string methods We can chain multiple method calls together in a single line by calling a method of the value returned by another method call.

Something that has methods is called an object. It turns out that everything in Python is an object, even the number zero: A floating point argument will be truncated towards zero this does not include a string representation of a floating point number! When converting a string, use the optional base.

It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead. Methods defined here: For our running example, we will write some programs that display and manipulate pictures and other images. Suppose you have a file called pic You could double-click to open it, but what does that actually do? To start to answer that question, type the following into a Python prompt: The result should be the awesomely cute photo shown in Figure 4.

Import the functions from the media module. This call returns a string that contains the path to the picture file.

This creates a Python object, which is assigned to the variable pic. Double-clicking would definitely have been easier. The third tells us the path to the file containing the picture. Now try this: Madeleine cropped As you can guess from the name, crop crops the picture. The upperleft corner is , 50 , and the lower-right corner is , ; the resulting picture is shown in Figure 4. The code also shows the new picture and then writes it to a new file.

This file is saved in the current working directory, which by default is the directory in which the program is running. Example color values 4. You might also want to convert pictures to black and white for printing, highlight certain objects, and so on.

To do these things, you must work with the individual pixels that make up the image. The media module represents pixels using the RGB color model discussed in the sidebar on page Module media provides a Color type and more than predefined Color values. Several of them are listed in Figure 4. The media module provides functions for getting and changing the colors in pixels see Figure 4. We will talk about for loops in detail in Section 5.

Try this code on a picture of your own, and see how convincing the result is. Color functions 4. The programs that run CAT scanners and other medical equipment must be even more reliable, since lives depend on them. Checking that software is doing the right thing is called quality assurance, or QA. Quality has to be designed in, and software must be tested and retested to check that it meets standards. The good news is that putting effort into QA actually makes you more productive overall.

The later you find a bug, the more expensive it is to fix, so catching bugs early reduces overall effort. This takes a little more time up front but makes programmers more productive overall, since every hour invested in preventing bugs saves two, three, or ten frustrating hours tracking bugs down.

To show how it works, we will use it to test our temperature module. The name is important: Every Nose test module should contain the following: Using the structure outlined earlier, our first sketch of a testing module looks like this: Com T ESTING RGB and Hexadecimal In the red-green-blue or RGB color system, each pixel in a picture has a certain amount of the three primary colors in it, and each color component is specified by a number in the range 0— which is the range of numbers that can be represented in a single 8-bit byte.

By tradition, RGB values are represented in hexadecimal, or base, rather than in the usual base decimal system. This means that the number after is not , but A16 ; the number after A16 is B16 , and so on, up to F16 , which is followed by An RGB color is therefore six hexadecimal digits: Black is therefore no color of any kind , while white is FFFFFF all colors saturated , and is a bluish-green no red, half-strength green, halfstrength blue.

For now, each test function contains nothing except a docstring and a pass statement. If you run the test module, the output starts with two dots to say that two tests have run successfully.

The summary after the dashed line tells us that Nose found and ran two tests, that it took less than a millisecond to do so, and that everything was OK: The next step is to fill them in so that they actually do something useful. Instead, we select a few representative values and make sure the function does the right thing for them.

For example, Fahrenheit is The actual value matches the expected value. The actual value is different from the expected value. Something went wrong inside the test itself; in other words, the test code contains a bug.

That is helpful, but the reason for failure can be made even clearer by adding a description of what is being tested to each assert statement. File "c: Returning an unrounded result Ran 1 test in 0. The description of that test case states that it is a positive value, which implies that we may also want to test our code with a value of 0 or a negative value.

The real question is whether our code will behave differently for those values. Finally, we should also test that the function does the right thing for the dividing case, when the temperature is exactly freezing.

Values like this are often called boundary cases, since they lie on the boundary between Report erratum Prepared exclusively for Trieu Nguyen this copy is P1. The test module, including comments, is now complete: The reason is that as far as Nose is concerned, each function is one test. It is therefore generally a good idea to write lots of small test functions, each of which only checks a small number of things, rather than putting dozens of assertions in each function.

If you have functions and variables that logically belong together, you should put them in the same module. What about basic statistical functions? Going back to the previous paragraph, should a function that calculates gas mileage go in the same module as one that calculates carbon monoxide emissions? You can always find a reason why two functions should not be in the same module, but 1, modules with one function each are going to be hard for people including you to find their way around.

These are just guidelines, though; in the end, you will have to decide based on how more experienced programmers have organized modules like the ones in the Python standard library and eventually on your own sense of style. To use a module, you must first import it. After it has been imported, you refer to its contents using modulename.

Methods are called using object. One way to ensure that they do is to test them, which you can do in Python using the Nose module. Import module math, and use its functions to complete the following exercises: Use isLeap to determine the next leap year.

Using string methods, write expressions that do the following: Why do you think the media module mentioned in Section 4. Write a program that allows the user to choose a file and then shows the picture twice. Write a program that allows the user to choose a file, sets the red value of each pixel in the picture to 0, and shows the picture.

Write a program that allows the user to pick a file, halves the green value of each pixel in the picture, and shows the picture. Write a program that allows the user to pick a file and makes it grayscale; it should calculate the average of red, green, and blue values of each pixel and then set the red, green, and blue values to that average.

Write a program that allows the user to pick a file, doubles the red value of each pixel in the picture, and shows the picture. What happens when a value larger than is calculated? Do you think they should be allowed to use only unmodified images? Given that almost all pictures and TV footage are now digital and have to be processed somehow for display, what would that rule actually mean in practice? Suppose we want to test a function that calculates the distance between two XY points: Explain why this makes testing more difficult.

As gently as you can, point out two flaws in his approach. Com Chapter 5 Lists Up to this point, each variable we have created has referred to a single number or string.

In this chapter, we will work with collections of data and use a Python type named list. Lists contain 0 or more objects, and they allow us to store data such as 90 experiment measurements or 10, student IDs. Using what we have seen so far, we would have to create fourteen variables to keep track of these numbers see Figure 5.

The solution is to store all the values together in a list. Lists show up everywhere in the real world: To create a list in Python, we put the values, separated by commas, inside square brackets: Gray whale census day1 day2 day3 day4 day5 day6 day7 day8 day9 day10 day11 day12 day13 day14 5 4 7 3 2 3 2 6 4 2 1 7 1 3 Figure 5.

List example A list is an object; like any other object, it can be assigned to a variable: So, how do we get at the objects in a list? By providing an index that specifies the one we want. The first item in a list is at index 0, the second at index 1, and so on. In a fourteen-item list, the legal indices are 0, 1, 2, and so on, up to Trying to use an out-of-range index is an error, just like trying to divide by zero. Yes, it would be more natural to use 1 as the first index, as human languages do.

Python, however, uses the same convention as languages like C and Java and starts counting at zero. The last item is at index -1, the one before it at index -2, and so on: There is also an empty list, in other words, a list with no items in it. As you might guess, it is written [ ]. Trying to index an empty list always results in an error: Here is a list of information about the element Krypton, including its name, symbol, melting point in degrees Celsius , and boiling point also in degrees Celsius.

Using a list to aggregate related information is somewhat prone to error; a better, but more advanced, way to do this is described in Chapter 13, Object-Oriented Programming, on page Rather than retyping the whole list, we can assign a new value to a specific element of the list: List mutation In Figure 5. It also shows that lists are mutable, in other words, that their contents can be changed after they have been created. In contrast, numbers and strings are immutable.

You cannot, for example, change a letter in a string after you have created it. Methods that appear to, like upper, actually create new strings: List functions 5. Here they are in action working on a list of the half-lives3 of our plutonium isotopes: After twice this time has gone by, three quarters of the material will have decayed; after three times, seven eighths, and so on.

It hints that we might be able to concatenate lists with lists to create new lists, just as we concatenated strings to create new strings. A little experimentation shows that this does in fact work: Instead, it creates a new list whose entries refer to the entries of the original lists. Notice, by the way, how we use string. This is a common trick in Python programs.

For the same reason, Python has a for loop that lets us process each element in a list in turn, without having to write one statement per element. The general form of a for loop is as follows: Each pass through the block is called an iteration, and at the start of each iteration, Python assigns the next value in the list to the specified variable.

In this way, the program can do something with each value in turn. We use four spaces in this book; check with your instructors to find out whether they prefer something else. In this case, we created a new variable v to store the current value taken from the list inside the loop. We could equally well have used an existing variable. If we do this, the loop still starts with the first element of the list—whatever value the variable had before the loop is lost: Notice, by the way, that the last print statement in this program is not indented, so it is not part of the for loop.

It is executed after the for loop has finished and is executed only once. Nested Loops We said earlier that the block of statements inside a loop could contain anything.

This means that it can also contain another loop. One special case of this is when the inner and outer loops are running over the same list of length N, in which case the inner loop executes N2 times. This can be used to generate a multiplication table; after printing the header row, we use a nested loop to print each row of the table in turn, using tabs to make the columns line up: Print the column number and the contents of the table. We can thus keep a list: The first index in the slice is the starting point.

The second index is one more than the index of the last item we want to include. Aliasing lists 5. In Python, two variables are said to be aliases when they refer to the same value. For example, the following code creates two variables, both of which refer to a single list see Figure 5. When we modify the list using one of the variables, references through the other variable show the change as well: Aliasing in Function Calls Aliasing occurs when we use list parameters as well, since parameters are variables.

Com Method L. List methods Here is a simple function that takes a list, sorts it, and then reverses it: Some of the most commonly used are listed in Figure 5. Here is a sample interaction showing how we can use these methods to construct a list containing all the colors of the rainbow: Beginning programmers often forget that many list methods return None rather than creating and returning a new list.

Experienced programmers sometimes forget too. As a result, their lists sometimes seem to disappear: They do this because lists can grow very, very large—a million patient records, for example, or a billion measurements of a magnetic field. Creating a new list every time someone wanted to make a change to such a list would slow Python down so much that it would no longer be useful; having Python guess when it should make a copy, and when it should operate on the list in place, would make it impossible to figure out.

Second, append modifies the list rather than creating a new one.

That means that they can contain other lists, just as the body of a loop can contain another loop. For example, the following nested list describes life expectancies in different countries: We use the standard notation to access the items in the outer list: Aliasing sublists Since each of these items is also a list, we can immediately index it again, just as we can chain together method calls or pass the result of one function call as an argument to another function: As before, any change we make through the sublist reference will show up when we access the main list, and vice versa: Formally, a string is an immutable sequence of characters.

Tuples are written using parentheses instead of square brackets; like strings and lists, they can be subscripted, sliced, and looped over: This has to be done to avoid ambiguity. Once a tuple is created, it cannot be changed: It would be more accurate to say this: The answer is that they make some operations more efficient and others safer. The second argument indicates a mode.

The three options are "r" for reading, "w" for writing, and "a" for appending. The result of open is not the contents of the file. Instead, open returns a file object whose methods allow the program to access the contents of the file. The most fundamental of these methods is read. When it is called without any arguments, it reads all the data in the file and returns it as a string of characters. If we give read a positive integer argument, it reads only up to that many characters; this is useful when we are working with very large files.

Shop by category

Although read gives us access to the bytes in a file, we usually use higher-level methods to do our work. If the file contains text, for example, we will probably want to process it one line at a time. A line is defined as being all the characters up to and including the next end-of-line marker see Section 3. The neatest thing about readline is that Python calls it for us automatically when a file object is used in a for loop.

Assume this data is in a file called data. There are only four characters in the word Mars, but our program is reporting that the line Report erratum Prepared exclusively for Trieu Nguyen this copy is P1.

The reason for this is that each of the lines we read from the file has an end-of-line character at the end. We can get rid of it using string. Using string. For example, we might want to read the first three lines one time and lines 2 to 4 another time. We can do this using command-line arguments. When we run a program, we can send arguments to it, much like when we call a function or method.

These values end up in a special variable of the system module sys called argv, which is just a list of the arguments as strings.

The rest of the command-line arguments are in sys. Here, then, is a program that reads all the data from a file and displays lines with line numbers within the start and end line range: The docstring is primarily for people who want to use the program; it describes what the program does but not how. Comments, on the other hand, are written for the benefit of future developers.

We can put whatever we want in comments, because Python ignores them completely. Here are a few rules for good commenting: In particular, if you develop a program or function by writing a simple point-form description in English, then making the points more and more specific until they turn into code, you should keep the original points as comments. We will discuss this style of development further in Chapter 10, Algorithms, on page For example, if you have to keep reminding readers what each of the fifteen lists in a function are for, you should break the function into smaller pieces, each of which works only with a few of those lists.

Including future versions of ourselves, who might have forgotten the details of this program by the time a change needs to be made or a bug needs to be fixed. We call the objects in a list its elements and refer to them by position using indices ranging from zero to one less than the length of the list. Lists can contain any type of data, including other lists. Tuples are similar to lists, except they are immutable.

Write the answer in two ways, one using a positive index and one using a negative index. Write a for loop that adds up all the values and stores them in variable total.

Create a list of temperatures in degrees Celsius with the values Using one of the list methods, sort temps in ascending order. Create a nested list where each element of the outer list contains the atomic number and atomic weight for an alkaline earth metal. The values are beryllium 4 and 9.

Draw a memory model showing the effect of the following statements: The following function does not have a docstring or comments. Write enough of both to make it easy for the next person to understand what the function does, and how, and then compare your solution with those of at least two other people. How similar are they? Why do they differ? Section 5.

Why might mutable strings be useful? Why do you think Python made them immutable? Is this consistent with the rules given in Chapter 3, Strings, on page 39 and Chapter 6, Making Choices, on the next page for how comparison operators like Report erratum Prepared exclusively for Trieu Nguyen this copy is P1.

Com Chapter 6 Making Choices This chapter introduces another fundamental concepts of programming: For example, we might want to do different things depending on whether a solution is acidic or basic.

We have already met one control flow statement— the loops introduced in Section 5. Unlike the integers, floating-point numbers, and strings we have already seen, this type has only two values and three operators, but it is extremely powerful.

His work led directly to the use of Boolean logic to design computer circuits. Unlike int and float, which have billions of possible values, bool has only two: True and False.

True and False are values, just as much as the numbers 0 and Boolean Operators There are only three basic Boolean operators: An expression involving not produces True if the original value is False, and it produces False if the original value is True: Rather than apply not directly to a Boolean value, we would typically apply not to a Boolean variable or a more complex Boolean expression.

Relational and equality operators or is also a binary operator. It produces True if either operand is True, and it produces False only if both are False: In English, the word or is also sometimes an exclusive or. Like most programming languages, Python always interprets or as inclusive. We will see in the exercises how to create an exclusive or. We mentioned earlier that Boolean operators are usually applied to Boolean expressions, rather than Boolean constants.

A truth table for each alternative is shown in Figure 6. The most common way to produce them in programs is not to write them down directly but rather to create them in expressions. The most common way to do that is to do a comparison using a relational operator. Integers are automatically converted to floating point when we do this, just as they are when we add 14 to Relational operators therefore almost always involve variables, like this: For example, comparisons are evaluated before and, or, and not.

These rules also mean that you can often skip the parentheses in complicated expressions: You can do this in Python by combining the comparisons with and: However, the first one is equivalent to this: This kind of expression is an example of something that is a bad idea even though it is legal.

Use simple comparisons and combine them with and in order to keep your code readable. Applying Boolean Operators to Integers, Floats, and Strings We have already seen that Python converts ints to floats in mixed expressions. It also converts numbers to bools, which means that the three Boolean operators can be applied directly to numbers.

When this happens, Python treats 0 and 0. When Python evaluates an expression containing either of these operators, it always does so from left to right. The result is the last thing that was evaluated, which is not necessarily either True or False. This is much easier to demonstrate than explain. Here are three expressions involving and: Python also checks both operands in the third expression; as you can see, it takes the value of Report erratum Prepared exclusively for Trieu Nguyen this copy is P1.

With or, if the first operand is considered to be true, or evaluates to that value immediately, without even checking the second operand.

The reason for this is that Python already knows the answer: True or X is True, regardless of the value of X. If the first operand is equivalent to False, though, or has to check the second operand. We claimed that if the first operand to the or operator is true, then or evaluates to that value immediately without evaluating the second operand. In order to show that this is what happens, try an expression that divides by zero: File " " , line 1, in ZeroDivisionError: The characters in strings are represented by integers: If the character from one string is greater than the character from the other, the first string is greater than the second.

If all the characters are the same, the two strings are equal; if one string runs out of characters while the comparison is being done in other words, is shorter than the other , then it is less. The following code fragment shows a few comparisons in action: True becomes 1, while False becomes 0: If the condition is true, then the statements in the block are executed; otherwise, they are not. As with loops and functions, the block of statements must be indented to show that it belongs to the if statement.

Here is a table of solution categories based on pH level: If the condition is false, the statements in the block are not executed: As soon as the indentation ends, Python assumes that the block has ended as well.

This is therefore legal: If there are multiple criteria to examine, there are a couple of ways to handle it. One way is to use multiple if statements. For example, we might print different messages depending on whether a pH level is acidic or basic: In Figure 6.

An if statement can be followed by multiple elif clauses. This longer example translates a chemical formula into English: To do this, we add an else clause at the end of the chain: Notice there is no condition associated with the else; logically, the following statement: An if statement inside another is called a nested if statement.

The first, or outer, if statement checks whether the user typed something, which determines whether we examine the value of pH with the inner if statement.

Nested if statements are sometimes necessary, but they can get complicated and difficult to understand. The most common situation in which you would want to do this comes up when translating decision tables into software.Python in the browser: For beginners, one of the challenges of getting started is installing Python. To do this, we subtract 32 from the temperature in Fahrenheit and then multiply by Since Python takes the floor of the result of an integer division, the result is one smaller than you might expect: Draw a memory model showing the effect of the following statements: As you might guess, it is written [ ].

VANDA from Daytona Beach
I do like recklessly . Feel free to read my other posts. I'm keen on metal detecting.