Boston drunks




















Python does do a considerable amount of semantic checking while running a program. If a program has no syntactic errors and no static semantic errors, it has a meaning, i. Of course, it might not have the semantics that its creator intended. When a program means something other than what its creator thinks it means, bad things can happen.

What might happen if the program has an error, and behaves in an unintended way? It might crash, i. In a properly designed computing system, when a program crashes, it does not damage the overall system. Alas, some very popular computer systems don't have this nice property.

Almost everyone who uses a personal computer has run a program that has managed to make it necessary to reboot the whole system. It might keep running, and running, and running, and never stop. If you have no idea of approximately how long the program is supposed to take to do its job, this situation can be hard to recognize. It might run to completion and produce an answer that might, or might not, be correct.

Each of these outcomes is bad, but the last one is certainly the worst. When a program appears to be doing the right thing but isn't, bad things can follow: fortunes can be lost, patients can receive fatal doses of radiation therapy, airplanes can crash. Whenever possible, programs should be written so that when they don't work properly, it is self-evident.

We will discuss how to do this throughout the book. Finger exercise: Computers can be annoyingly literal. If you don't tell them exactly what you want them to do, they are likely to do the wrong thing. Try writing an algorithm for driving between two destinations.

Write it the way you would for a person, and then imagine what would happen if that person were as stupid as a computer, and executed the algorithm exactly as written. People actually carried small devices that could be used only for arithmetic calculation. It implemented ideas previously described by John von Neumann and was anticipated by the theoretical concept of the Universal Turing Machine described by Alan Turing in Though each programming language is different though not as different as their designers would have us believe , they can be related along some dimensions.

Low-level versus high-level refers to whether we program using instructions and data objects at the level of the machine e. General versus targeted to an application domain refers to whether the primitive operations of the programming language are widely applicable or are fine-tuned to a domain.

For example, SQL is designed for extracting information from relational databases, but you wouldn't want to use it build an operating system. Interpreted versus compiled refers to whether the sequence of instructions written by the programmer, called source code, is executed directly by an interpreter or whether it is first converted by a compiler into a sequence of machine-level primitive operations. In the early days of computers, people had to write source code in a language close to the machine code that could be directly interpreted by the computer hardware.

There are advantages to both approaches. It is often easier to debug programs written in languages that are designed to be interpreted, because the interpreter can produce error messages that are easy to relate to the source code. In this book, we use Python. However, this book is not about Python. It will certainly help you learn Python, and that's a good thing. What is much more important, however, is that you will learn something about how to write programs that solve problems.

You can transfer this skill to any programming language. Python is a general-purpose programming language you can use effectively to build almost any kind of program that does not need direct access to the computer's hardware. Python is not optimal for programs that have high reliability constraints because of its weak static semantic checking or that are built and maintained by many people or over a long period of time again because of the weak static semantic checking.

Python does have several advantages over many other languages. It is a relatively simple language that is easy to learn. Because Python is designed to be interpreted, it can provide the kind of runtime feedback that is especially helpful to novice programmers.

A large and growing number of freely available libraries interface to Python and provide useful extended functionality. We use several of these libraries in this book. We are ready to introduce some of the basic elements of Python. These are common to almost all programming languages in concept, though not in detail.

This book is not just an introduction to Python. It uses Python as a vehicle to present concepts related to computational problem solving and thinking. The language is presented in dribs and drabs, as needed for this ulterior purpose. Python features that we don't need for that purpose are not presented at all. We feel comfortable about not covering every detail because excellent online resources describe every aspect of the language.

We suggest that you use these free online resources as needed. Python is a living language. Since its introduction by Guido von Rossum in , it has undergone many changes. For the first decade of its life, Python was a little known and little used language.

That changed with the arrival of Python 2. In addition to incorporating important improvements to the language itself, it marked a shift in the evolutionary path of the language. Python 3. This version of Python cleaned up many of the inconsistencies in the design of Python 2.

However, Python 3 is not backward compatible. This means that most programs and libraries written for earlier versions of Python cannot be run using implementations of Python 3.

By now, all of the important public domain Python libraries have been ported to Python 3. Today, there is no reason to use Python 2.

Once upon time, programmers used general-purpose text editors to enter their programs. Today, most programmers prefer to use a text editor that is part of an integrated development environment IDE.

As Python has grown in popularity, other IDEs have sprung up. Anaconda and Canopy are among the more popular of these IDEs. The code appearing in this book was created and tested using Anaconda. IDEs are applications, just like any other application on your computer.

Start one the same way you would start any other application, e. All of the Python IDEs provide. A text editor with syntax highlighting, auto completion, and smart indentation, A shell with syntax highlighting, and An integrated debugger, which you can safely ignore for now.

Once the installation is complete, start the application Anaconda- Navigator. A window containing a collection of Python tools will appear. The window will look something like Figure When you launch Spyder by clicking on its Launch button, of all things , a window similar to Figure will open. You can type and execute Python commands in this window. The pane on the upper right is a help window. It is often convenient to close that window by clicking on the x , so that more real estate is available for the IPython console.

The pane on the left is an edit window into which you can type programs that can be saved and run. The toolbar at the top of the window makes it easy to perform various tasks such as opening files and printing programs. A Python program, sometimes called a script, is a sequence of definitions and commands. The Python interpreter in the shell evaluates the definitions and executes the commands.

We recommend that you start a Python shell e. And, for that matter, in the rest of the book. A command, often called a statement, instructs the interpreter to do something. For example, the statement print 'Yankees rule! The sequence of commands print 'Yankees rule! But not in Boston! Yankees rule, but not in Boston! Notice that two values were passed to print in the third statement.

The print function takes a variable number of arguments separated by commas and prints them, separated by a space character, in the order in which they appear. Each object has a type that defines what programs can do with that object. Types are either scalar or non-scalar. Scalar objects are indivisible. Think of them as the atoms of the language. Many types of objects can be denoted by literals in the text of a program.

For example, the text 2 is a literal representing a number and the text 'abc' is a literal representing a string.

Python has four types of scalar objects:. Literals of type int are written in the way we typically denote integers e. Literals of type float always include a decimal point e. It is also possible to write literals of type float using scientific notation. For example, the literal 1. You might wonder why this type is not called real. Within the computer, values of type float are stored as floating-point numbers. This representation, which is used by all modern programming languages, has many advantages.

However, under some situations it causes floating-point arithmetic to behave in ways that are slightly different from arithmetic on real numbers. We discuss this in Section 3. None is a type with a single value. We will say more about None in Section 4. Objects and operators can be combined to form expressions, each of which evaluates to an object of some type. This is called the value of the expression. Keep an eye out for this error.

In a Spyder console, something that looks like In [1]: is a shell prompt indicating that the interpreter is expecting the user to type some Python code into the shell. The line below the prompt is produced when the interpreter evaluates the Python code entered at the prompt, as illustrated by the following interaction with the interpreter: 3 Out[1]: 3. The built-in Python function type can be used to find out the type of an object: type 3 Out[5]: int.

Operators on objects of type int and float are listed in Figure 2- 3. The arithmetic operators have the usual precedence. The order of evaluation can be changed by using parentheses to group subexpressions, e. Figure Operators on types int and float. The code first binds the names pi and radius to different objects of type int. This is depicted on the left side of Figure Figure Binding of variables to objects.

Note that this assignment has no effect on the value to which area is bound. In Python, a variable is just a name, nothing more. Remember this—it is important. Remember this too: an object can have one, more than one, or no name associated with it. Programming languages let us describe computations so that computers can execute them. This does not mean that only computers read programs. As you will soon discover, it's not always easy to write programs that work correctly. Experienced programmers will confirm that they spend a great deal of time reading programs in an attempt to understand why they behave as they do.

It is therefore of critical importance to write programs so that they are easy to read. Apt choice of variable names plays an important role in enhancing readability. When executed, they will do the same thing. To a human reader, however, they are quite different. When we read the fragment on the left, there is no a priori reason to suspect that anything is amiss. However, a quick glance at the code on the right should prompt us to suspect that something is wrong. Either the variable should have been named radius rather than diameter, or diameter should have been divided by 2.

Python variable names are case-sensitive e. Finally, a few reserved words sometimes called keywords in Python that have built-in meanings and cannot be used as variable names. Different versions of Python have slightly different lists of reserved words.

The reserved words in Python 3. Another good way to enhance the readability of code is to add comments. Text following the symbol is not interpreted by Python. All of the expressions on the right-hand side of the assignment are evaluated before any bindings are changed.

This is convenient since it allows you to use multiple assignment to swap the bindings of two variables. The kinds of computations we have been looking at so far are called straight-line programs. They execute one statement after another in the order in which they appear and stop when they run out of statements. The kinds of computations we can describe with straight-line programs are not very interesting.

In fact, they are downright boring. Branching programs are more interesting. The simplest branching statement is a conditional. As shown in the box in Figure , a conditional statement has three parts:. A test, i. After a conditional statement is executed, execution resumes at the code following the statement. Figure Flowchart for conditional statement.

In Python, a conditional statement has the form if Boolean expression: if Boolean expression: block of code or block of code else: block of code. In describing the form of Python statements, we use italics to identify the kinds of code that could occur at that point in a program. For example, Boolean expression indicates that any expression that evaluates to True or False can follow the reserved word if, and block of code indicates that any sequence of Python statements can follow else:.

Indentation is semantically meaningful in Python. Python is unusual in using indentation this way. Most other programming languages use bracketing symbols to delineate blocks of code, e. An advantage of the Python approach is that it ensures that the visual structure of a program is an accurate representation of its semantic structure. Because indentation is semantically important, the notion of a line is also important.

Long lines can also be wrapped using Python's implied line continuation. This is done with bracketing, i. Many Python programmers prefer using implied line continuations to using a backslash. Most commonly, programmers break long lines at commas or operators. Returning to conditionals, when either the true block or the false block of a conditional contains another conditional, the conditional statements are said to be nested.

The following code contains nested conditionals in both branches of the top-level if statement. Finger exercise: Write a program that examines three variables— x, y, and z—and prints the largest odd number among them.

If none of them are odd, it should print the smallest value of the three. You can attack this exercise in a number of ways. There are eight separate cases to consider: they are all odd one case , exactly two of them are odd three cases , exactly one of them is odd three cases , or none of them is odd one case. Not only is it 16 lines of code, but the variables are repeatedly tested for oddness. The code is based on a common programming paradigm. It starts by assigning a provisional value to a variable answer , updating it when appropriate, and then printing the final value of the variable.

Notice that it tests whether each variable is odd exactly once, and contains only a single print statement. This code is pretty much as well as we can do, since any correct program must check each variable for oddness and compare the values of the odd variables to find the largest of them.

Python supports conditional expressions as well as conditional statements. Conditional expressions are of the form expr1 if condition else expr2. If the condition evaluates to True, the value of the entire expression is expr1; otherwise it is expr2. A conditional expression can appear any place an ordinary expression can appear, including within conditional expressions. Conditionals allow us to write programs that are more interesting than straight-line programs, but the class of branching programs is still quite limited.

One way to think about the power of a class of programs is in terms of how long they can take to run. Assume that each line of code takes one unit of time to execute. What about a branching program with n lines of code? It might take less than n units of time to run, but it cannot take more, since each line of code is executed at most once. A program for which the maximum running time is bounded by the length of the program is said to run in constant time. This does not mean that each time the program is run it executes the same number of steps.

It means that there exists a constant, k, such that the program is guaranteed to take no more than k steps to run. This implies that the running time does not grow with the size of the input to the program. Constant-time programs are limited in what they can do. Consider writing a program to tally the votes in an election. It would be truly surprising if one could write a program that could do this in a time that was independent of the number of votes cast.

In fact, it is impossible to do so. The study of the intrinsic difficulty of problems is the topic of computational complexity. We will return to this topic several times in this book. Fortunately, we need only one more programming language construct, iteration, to allow us write programs of arbitrary complexity. We get to that in Section 2. Objects of type str are used to represent characters. The literal '' denotes a string of three characters, not the number Try typing the following expressions in to the Python interpreter.

It means what you expect it to mean when its operands are both numbers. There is a logic to this. Each of these lines generates an error message.

However, since that name is not bound to any object, attempting to use it causes a runtime error. That type checking exists is a good thing. It turns careless and sometimes subtle mistakes into errors that stop execution, rather than errors that lead programs to behave in mysterious ways.

The type checking in Python is not as strong as in some other programming languages e. Rather arbitrarily, the designers of Python 2 decided that it should be False, because all numeric values should be less than all values of type str.

The designers of Python 3, and most other modern languages, decided that since such expressions don't have an obvious meaning, they should generate an error message. Strings are one of several sequence types in Python.

They share the following operations with all sequence types. The length of a string can be found using the len function. For example, the value of len 'abc' is 3. Indexing can be used to extract individual characters from a string.

In Python, all indexing is zero-based. For example, typing 'abc'[0] into the interpreter will cause it to display the string 'a'. Typing 'abc'[3] will produce the error message IndexError: string index out of range. Since Python uses 0 to indicate the first element of a string, the last element of a string of length 3 is accessed using the index 2. Negative numbers are used to index from the end of a string.

Slicing is used to extract substrings of arbitrary length. If s is a string, the expression s[start:end] denotes the substring of s that starts at index start and ends at index end For example, 'abc'[] evaluates to 'bc'. Why does it end at index end-1 rather than end?

So that expressions such as 'abc'[0:len 'abc' ] have the value you might expect. If the value before the colon is omitted, it defaults to 0. If the value after the colon is omitted, it defaults to the length of the string. Consequently, the expression 'abc'[:] is semantically equivalent to the more verbose 'abc'[0:len 'abc' ].

It is also possible to supply a third argument to select a non-contiguous slice of a string. For example, the value of the expression ''[] is the string ''. It is often convenient to convert objects of other types to strings using the str function. Type conversions also called type casts are used often in Python code. We use the name of a type to convert values to that type.

When a float is converted to an int, the number is truncated not rounded , e. Returning to the output of our print statements, you might be wondering about that. The code. An f-string consists of the character f or F following by a special kind of string literal called a formatted string literal. Formatted string literals contain both sequences of characters like other string literals and expressions bracketed by curly braces.

These expressions are evaluated at runtime and automatically converted to strings. If you want to include a curly brace in the string denoted by an f-string, use two braces. The expression inside an f-string can contain modifiers that control the appearance of the output string. We will introduce other modifiers as convenient later in the book. The input function takes a string as an argument and displays it as a prompt in the shell.

The function then waits for the user to type something and press the enter key. The line typed by the user is treated as a string and becomes the value returned by the function. If you then type George Washington and press enter, the string 'George Washington' will be assigned to the variable name. If you then execute print 'Are you really', name, '? It does this because when print is given multiple arguments, it places a space between the values associated with the arguments.

For example, if the user had entered 3, n would be bound to the str '3' not the int 3. The good news is that whenever a string is a valid literal of some type, a type conversion can be applied to it. This standard included characters, plenty for representing the usual set of characters appearing in English-language text—but not enough to cover the characters and accents appearing in all the world's languages. The Unicode standard is a character coding system designed to support the digital processing and display of the written texts of all languages.

The standard contains more than , characters— covering modern and historic scripts and multiple symbol sets. The Unicode standard can be implemented using different internal character encodings. I didn't. Because most of the web uses UTF-8, I was able to cut the string from a webpage and paste it directly into my program.

There are ways to directly enter Unicode characters from a keyboard, but unless you have a special keyboard, they are all rather cumbersome. Near the end of Section 2. Consider, for example, writing a program that asks for the number of X's. But it would quickly become apparent that you would need as many conditionals as there are positive integers—and there are an infinite number of those.

A generic iteration also called looping mechanism is shown in the box in Figure Like a conditional statement, it begins with a test. If the test evaluates to True, the program executes the loop body once, and then goes back to reevaluate the test. This process is repeated until the test evaluates to False, after which control passes to the code following the iteration statement.

We can write the kind of loop depicted in Figure using a while statement. Consider the code in Figure It then proceeds to square x by using repetitive addition. The table in Figure shows the value associated with each variable each time the test at the start of the loop is reached. We constructed the table by hand- simulating the code, i.

Using pencil and paper might seem quaint, but it is an excellent way to understand how a program behaves. The fourth time the test is reached, it evaluates to False and flow of control proceeds to the print statement following the loop.

For what values of x will this program terminate? At this point the loop test evaluates to False, and control proceeds to the code following the while statement. Something very bad happens. The program will therefore continue executing the loop forever or until something else bad, e. The loop terminates, but it prints a negative value. It is sometimes convenient to exit a loop without testing the loop condition.

Executing a break statement terminates the loop in which it is contained and transfers control to the code immediately following the loop. If a break statement is executed inside a nested loop a loop inside another loop , the break will terminate the inner loop. Finger exercise: Write a program that asks the user to input 10 integers, and then prints the largest odd number that was entered.

If no odd number was entered, it should print a message to that effect. The while loops we have used so far are highly stylized, often iterating over a sequence of integers. The general form of a for statement is recall that the words in italics are descriptions of what can appear, not actual code : for variable in sequence: code block. The variable following for is bound to the first value in the sequence, and the code block is executed.

The variable is then assigned the second value in the sequence, and the code block is executed again. The process continues until the sequence is exhausted or a break statement is executed within the code block.

The expression 77, 11, 3 is a tuple. We discuss tuples in detail in Section 5. For now, just think of a tuple as a sequence of values. The sequence of values bound to variable is most commonly generated using the built-in function range, which returns a series of integers. The range function takes three integer arguments: start, stop, and step. For example, the expression range 5, 40, 10 yields the sequence 5, 15, 25, 35, and the expression range 40, 5, yields the sequence 40, 30, 20, If the first argument to range is omitted, it defaults to 0, and if the last argument the step size is omitted, it defaults to 1.

For example, range 0, 3 and range 3 both produce the sequence 0, 1, 2. We will discuss range in more depth in Section 5. The code in Figure reimplements the algorithm in Figure for squaring an integer corrected so that it works for negative numbers. This is typical, but not necessary, which raises the question of what happens if the index variable is modified within the for loop.

Do you think that it will print 0, 0, 1, 0, and then halt? Or do you think it will print 0 over and over again? The answer is 0, 0, 1, 0. Before the first iteration of the for loop, the range function is evaluated and the first value in the sequence it yields is assigned to the index variable, i.

When the sequence is exhausted, the loop terminates. Notice, by the way, that code with the while loop is considerably more cumbersome than the for loop. The for loop is a convenient linguistic mechanism. Just 0, because the arguments to the range function in the line with for are evaluated just before the first iteration of the loop, and not reevaluated for subsequent iterations.

Now, let's see how often things are evaluated when we nest loops. How many times is each of the two loops executed? We already saw that the range x controlling the outer loop is evaluated the first time it is reached and not reevaluated for each iteration, so there are four iterations of the outer loop.

That implies that the inner for loop is reached four times. The for statement can be used in conjunction with the in operator to conveniently iterate over characters of a string. Finger exercise: Write a program that prints the sum of the prime numbers greater than 2 and less than Hint: you probably want to use a for loop that is a primality test nested inside a for loop that iterates over the odd integers between 3 and Much of this book is devoted to helping you learn a programming language.

But knowing a language and knowing how to use a language well are two different things. But they are not equally compelling, and perhaps not equally easy to understand. Just as style matters when writing in English, style matters when writing in Python.

However, while having a distinctive voice might be an asset for a novelist, it is not an asset for a programmer. The less time readers of a program have to spend thinking about things irrelevant to the meaning of the code, the better. That's why good programmers follow coding conventions designed to make programs easy to understand, rather than fun to read. Most Python programmers follow the conventions laid out in the PEP 8 style guide.

For example, it prescribes using four spaces for indents. Why four spaces and not three or five? No particularly good reason.

But if everybody uses the same number of spaces, it is easier to read and perhaps combine code written by different people. More generally, if everyone uses the same set of conventions when writing Python, readers can concentrate on understanding the semantics of the code rather than wasting mental cycles assimilating stylistic decisions. The most important conventions have to do with naming.

We have already discussed the importance of using variable names that convey the meaning of the variable. Noun phrases work well for this. Again, this convention is arbitrary. Some programmers prefer to use what is often called camelCase, e. There are also some conventions for single-character variable names. The most important is to avoid using a lowercase L or uppercase I which are easily confused with the number one or an uppercase O which is easily confused with the number zero.

That's enough about conventions for now. Plus, we have the latest state-of-the-art arcade games to challenge your skills. Homemade pizzas, hand-crafted burgers, freshly-made salads, and more. In The Game E-Club members receive email notifications about news, events, promotions, and personalized offers. You must be 13 years of age or older to join. Parents of children who are added to an E-Club member profile may receive additional emails on behalf of the child.

Offer available to new subscribers only. See All Specials. Our Delicious Chef-Inspired Menu will satisfy even the pickiest eaters. See our Chef Created Menu. Batting Cages ashleewoods T Real name Peter Sydney Ernest Aylen. Bernard Lee, British actor. Tommy Lee, drummer. Founded rap-metal band Methods of Mayhem. Real name Thomas Lee Bass. Won gold medal in boxing at the Olympic Games. Boxing Hall of Fame. Demi Lovato, actor. Carson McCullers, writer and playwright. Malcolm McDowell, British actor.

Homeopathy for Treating Alcoholism. Tim McGraw, country music singer, songwriter and actor. McGraw has sold over 40 million albums and won three Grammy Awards. James Macklemore, rapper. Real name Benjamin Hammond Haggerty. Joe Manganiello, actor, narrator, director, and producer. Mickey Mantle, center fielder and first baseman baseball player.

The greatest switch hitter in baseball. Johnny Manziel, quarterback football player. Diego Maradona, Argentine football soccer player and manager. Many people consider him the greatest football player in history. Billy Martin, second baseman baseball player and manager. Elected to the American League All Star team. Real name Alfred Manuel Pesano, Jr. Joseph C. Martin, Roman Catholic priest and speaker on alcoholism.

Madan Mohan, Hindi film composer. Demi Moore, actor. Gary Moore, Northern Irish rock guitarist. Mary Tyler Moore, actor. Jim Morrison, musician, songwriter, and poet. Co-founder and lead singer of the Doors. Kate Moss, British supermodel and entreprenuar. Owns line of fashion clothing.

Real name Katherine Ann Moss. Eddie Murphy, comedic actor. Modest Mussorgsky, Russian composer. Sports broadcaster. Mike Ness, musician. Formed punk rock band Social Distortion. Guitarist, vocalist, producer and songwriter for the group. Stevie Nicks, singer. Member of Fleetwood Mac.

Solo career includes eight solo studio albums. Real name Stephanie Lynn Nicks. Jim Norton, comedian, actor, radio and TV host. Gary Oldman, British actor. Jack Osbourne, actor and reality TV personality. Son of Ozzy Osbourne.

Ozzy Osbourne, singer and reality TV personality. Lead vocalist of heavy metal band Black Sabbath. Also, a solo singer. Real name John Michael Osbourne. See Jack Osbourne. Hypnotherapy for Alcoholism. Named to the First All-Star Team. Pearson Award now called Ted Lindsay Award. Bernie Parent, ice hockey goaltender. Orthomolecular Treatment for Alcoholism.

Dorothy Parker, writer, poet, and critic. Formed a group of writers and wits called the Algonquin Round Table. Barbara Payton, actor and model. Edgar Allan Poe, writer, poet, and critic. Dennis Price, British actor. Daniel Radcliffe, actor. Harold Ramis, writer and actor. Oliver Reed, actor. Trent Reznor, singer, songwriter, and composer. Jean Rhys, writer. Christina Ricci, actor. Barret Robbins, center football player. Sabathia Carsten C. Sabathia, Jr. Cy Young Award.

Pitched an average of over innings per season during career. Steve Sarkisian, football player and coach. Bon Scott, Scottish singer and songwriter. Cognitive Behavioral Therapy for Alcoholism. Proven to be effective. Anne Sexton, writer and poet. Ramses Shaffy, Dutch singer and actor. Shailendra, Indian Hindi film lyricist. Real name Shankardas Kesarilal. William Shatner, Canadian actor, author, producer, and director.

Charlie Sheen, actor. Jada Pinkett Smith, actor. Dusty Springfield, British singer. Jean Stafford,short-story writer and novelist. Ringo Starr, British musician, writer, actor, and director. Drummer for The Beatles.

Real name Richard Starkey. Cat Stevens, singer and songwriter. Changed to Yusuf Islam after conversion to Islam. Darryl Strawberry, baseball fielder and sports commentator. Voted to the All-Star Game eight years in a row.



0コメント

  • 1000 / 1000