Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 1.1 Installing Python and an Integrated Development Environment Why Python? We have chosen to do our programming in Python because it is a popular programming language that is not part of an expensive software package. It also has extensive libraries of functions for mathematics and science. Python is not the only language with these properties, and if you already know another language well, by all means use it. 1.2 Python versions 2 and 3 Python 3.4.1 is the newest stable version of Python as of this writing. It is important to note that Python 3 is not completely backwards compatible with Python 2. All examples presented in the text have been made to work with either version of Python. As a consequence, certain shortcuts specific to either version 2 or 3 have been omitted. For example, in Python 2, “print” can be called with or without parentheses, but in Python 3, parentheses are required. Since “print” with parentheses works in either version, we will use the parentheses. 2 Installation and Requirements Python has no particular minimum requirements and will run on any major operating system (Windows, OSX, Linux). 2.1 Integrated Development Environments (IDEs) Although Python scripts can be written in nearly any text editor, an integrated development environment (IDE) provides many advantages. One of the simplest (but also most useful) features is syntax highlighting. Syntax highlighting automatically changes the color of the function names, variables, keywords, punctuation, and literals that you type, giving you immediate visual feedback to syntax problems in your code. We recommend Spyder as an IDE because it is free, there are versions for Windows, OSX, and Linux, and it has everything we need to get started. The default installation of Spyder also includes many Python libraries commonly used in math and science. 3 3.1 Python Basics Exploring in the Python Console Let’s begin with integers, floats (numbers written as decimals, e.g., 2.0 and 0.0012), and arithmetic operations. Even before you write your first Python 1 program, you can start to learn about variable types and operations by typing directly into the Python console. By default, Spyder has a Python console in the lower right portion of its window. If it is not visible, a new one can be opened through Spyder’s menu Interpreters -¿ Open a Python interpreter. The Python command line begins with three greater-than symbols where you can enter Python commands. Start with some integer arithmetic. Try out some addition, subtraction, multiplication, and exponentiation. Note that to compute ab you must type a ∗ ∗b. >>> 5 >>> -1 >>> 6 >>> 8 2+3 2-3 2*3 2**3 Let’s look at integer division because not all consoles will produce the same output. Try 10 divided by 2 and 2 divided by 10 and see what happens. It is possible you will see the following: >>> 10 / 2 5 >>> 2 / 10 0 Depending on your Python configuration, you might get 0.2 when you enter 2 divided by 10, or you might get 0. The latter happens because, unless some package overrides it, Python will return a value that is of the same type as those on which it operated. Because 2 and 10 are integers, Python will do the operation in the integers and return the integer part of the answer, which is 0 in this case. To avoid this situation, let Python know you want to do the operation in the real numbers by making the values clearly floating point values and not integers. Thus you’d type >>> 10.0 / 2.0 5.0 >>> 2.0 / 10.0 0.2 Because programming languages will take what you type literally and do operations in integers if you input integers, whatever output you obtained in our little experiment above, get in the habit of typing 2.0 instead of 2 whenever you’re thinking about doing your arithmetic in the rational or real number systems. 2 3.2 Your First Programs Usually you will not type directly into the console. Instead, you will want to type in the editor and then run the program, with the output displayed in the Python console. The canonical first program in any language is the one that simply prints the string Hello, world! as output. Because you want to print this string and not the value of some variable that has been given the name Hello, world!, you must put quotes around the string. Thus, you should type the following in your editor: print("Hello, world!") Then run the code and observe the output in the console. Exercise 1 What appears in the console if you run the code without the quotes? Of course, usually when you write a program, you are assigning values to variables, performing one or more operations, and outputting the result. Consider the following (still very boring) code: x = 11 y = 17 print(x+y) In Python, the symbol = performs the assignment of a value to a variable. Assignment commands are evaluated from right to left. This program assigns the value 11 to the variable x and assigns 17 to the variable y. Then we issue a print command. We take the integer assigned to x and the integer assigned to y, perform the indicated operation, and print the result. Thus the integer 28 appears in the console. Python allows you to create new variables at any time. Although you have a lot of flexibility when it comes to naming your variables, you should follow some basic rules: 1. Variable names are case-sensitive. The variables X and x are two distinct variables with no relationship to one another. Although sometimes in mathematics we may have two variables that differ only in case (e.g., we may let T (t) be the temperature of a liquid at time t), we will try to avoid such variable names in our Python code. Errors caused by incorrect capitalization are very common and, if their effect is subtle, they can be very time-consuming to fix. 2. Variable names may contain only letters, numbers, and the underscore “ ” character. They cannot start with a number. 3. There are keywords in Python that are reserved and cannot be used as variable names. These are: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, 3 not, or, pass, print, raise, return, try, while, and yield. If you’re using an IDE, these keywords will have a different color than your other variable names, which will tell you that Python will interpret them differently. 3.3 Operators and Precedence The mathematical operators have the usual precedence in Python; exponentiation happens before multiplication and division, which happen before addition and subtraction. But when writing code, because we enter mathematical expressions in plain text, parentheses are incredibly important. It never hurts to use more parentheses. Although assignment happens from right to left, when operators have the same precedence, they are evaluated from left to right, e.g., >>> 3 / 2 * -5 -7.5 >>> 3 / (2 * -5) -0.3 Division symbols are only one character, so very frequently the numerators and denominators need to be wrapped with parentheses. For example, the equation √ −b + b2 − 4ac x= 2a might be translated into Python as: x = (-b + sqrt(b**2 - 4 * a * c)) / (2 * a) Alternatively, there’s no harm in being verbose if it helps your script be easier to read. numerator = -b + sqrt( b**2 - (4*a*c) ) denominator = 2 * a x = numerator / denominator Note that when writing mathematics, it is acceptable to denote multiplication by juxtaposition, as in 4ac. In Python, it is essential to indicate the operation, typing 4*a*c. 3.4 Lists and strings With these examples in mind, let’s talk about lists and strings. A string is just a collection of characters - letters, numbers, symbols, and punctuation. In our first program, Hello, world! was a string of characters we wished to print as output. The words were not names of variables. When we want to represent a string, we put it in quotes, as we did above. If we put in quotes some collection 4 of characters that happen to appear elsewhere in the program, it doesn’t matter - we still just have a string of characters. For example, if we add the line print("x+y") to the second program above, we get x+y as output even though earlier in the program there is a variable named x and it was assigned the value 11, etc. Python treats the string literally as “x+y” and does not interpret the contents of the string. For this reason, you may hear strings like this referred to as “string literals.” We can perform the operation of concatenation on strings. This is done using +. Thus the print command print("Hello " + "world") takes the string literal “Hello ” and the string literal “world” and concatenates them. The output is Hello world. Strings may also contain special characters that help us format our output. For instance we may have a large collection of data that we want to display on different lines or in columns. The character \n is called the newline character, and \t represents a tab. We illustrate by considering two print commands and their outputs. >>> print("Hello, world!\nFrom Python") Hello, world! From Python >>> print("Hello,\tworld!\nFrom\tPython") Hello, world! From Python Suppose we want our program above to have output x + y is 28. We must be careful, because part is a string and part is an integer arising from doing a calculation. We must tell our program to think of them both as strings and concatenate them. The following gives the desired output, as you should check. print("x + y is " + str(x + y)) A list, on the other hand, is a variable type. The elements of a list can be integers, floats, or other lists. We put lists in square brackets, with the entries separated by commas. Here are two examples: S = [1,3,5,7,9] T = [ [1,2,3], [4,5,6], [7,8,9] 5 ] The first list, S, has 5 elements, each of which is an integer. The second list, T , has 3 elements, each of which is itself a list with 3 elements. S[i] denotes the i-th element of the list, but note that lists in Python are zero-indexed. Thus for list S above, S[0] = 1, S[1] = 3, S[2] = 5, S[3] = 7, S[4] = 9. whereas T [0] = [1, 2, 3], T [1] = [4, 5, 6], T [2] = [7, 8, 9]. We can perform operations on elements of lists. With S and T as defined above, consider the following code: x = S[0] + S[1] + S[2] + S[3] + S[4] y = T[0] + T[1] + T[2] Although the syntax looks similar, if we print x and y, we see that the results are very different. In the first case, each S[i] is an integer, so our code asks that the five integers be added, with the result assigned to the variable x. If we print x, we see 25. In the second case, each T [i] is itself a list, and the operation + performed on lists concatenates them, forming a new longer list. Thus if we print y, we see [1, 2, 3, 4, 5, 6, 7, 8]. If we instead want to think of T as a 3 × 3 matrix with first row [1, 2, 3], etc., and we want to add all 9 entries, we use the notation T [i][j] to refer to the j-th element of the i-th list and use the following command: z = T[0][0] + T[0][1] + T[0][2] + T[1][0] + T[1][1] + T[1][2] + T[2][0] + T[2][1] + T[2][2] In this book, we study sequences extensively and thus we generate many lists. We can specify a list by giving a formula for the i-th term or by giving a recursive definition, in which we specify the first term and then tell how to produce the i-th term from the previous. Both approaches require us to understand loops. Loops will be the topic of Subsection 3.6. 3.5 if . . . else structures Very often, we want what a program does next to depend on the result of some previous step. We use the “if. . . else” structure in these situations. Before we can describe this structure, we need to talk about comparison operators and blocks of code. As we have already discussed, in Python, the equal sign = is used to assign values to variable names. Thus a = 10 is a program takes the integer 10 and attaches it to the label a. If we wanted to express this idea in a mathematical proof, we would probably say “Let a = 10.” In mathematics, we are somewhat 6 more used to thinking of the equals sign as it is used in a statement with a truth value. In mathematics, 10 = 20/2 makes perfect sense; the integer 10 is the same as the integer obtained by taking 20 and dividing it by 2. In Python, however, the above makes no sense; we would be asking Python to take the result of the calculation 20/2 and assign it to a variable named 10. But 10 is not a valid variable name. We might, however, want to test whether two calculations give the same result. In this case, we use the comparison operator ==. The result of this operation is either True or False, depending on whether the two values are or are not equal. Let’s see how this works by looking at two operations performed in the Python console. >>> 5 * 4 == 40 / 2 True >>> 5 * 4 == 20 / 2 False. Comparison operators like ==, <, <=, etc., often appear in programs in combination with if. . . else statements. Let’s illustrate with a simple program that takes two numbers, multiplies them together, and prints different messages depending on whether or not the product is bigger than 7. a = 3.141592 b = 2.71812 if( a * b < 7): print("Yes, the product is less than 7.") else: print("The product is bigger than or equal to 7.") print("result " + str(a * b)) Observe that, in Python, we use a colon at the end of the “if” line and the “else” line and we indent the blocks of code that are to be executed in each case. We have also added a line of code that is not indented that will print the actual result of the calculation. If we had indented this line, it would only be executed if a ∗ b < 7 is false. We can also combine multiple comparisons with the keywords “and”, and “or” to do more complex logic: a = 3.141592 b = 2.71812 if( a*b < 7 or a+b < 7 ): print("The sum or the product is less than 7.") 7 if( a*b < 10 and a+b < 10 ): print("The sum and product are both less than 10.") We can also have three or more branches for the program to take by using an if. . . elif. . . else statement. “elif” is short for “else if.” We illustrate by writing a program that tests whether an integer x is has any of 2, 3, or 5 as a factor. if(remainder(x,2)==0): print("x is divisible by 2") elif(remainder(x,3)==0): print("x is divisible by 3") elif(remainder(x,5)==0) : print("x is divisible by 5") else: print("x is not divisible by 2, 3, or 5") Exercise 2 Write a program that takes a floating point number x, prints its (positive) square root if x is non-negative, and prints “x does not have a real square root” if x is negative. 3.6 Loop structures The for loop We use a loop whenever we need to perform a set of instructions repeatedly, for example when we are generating the first terms of a sequence. Because we spend a lot of time in this book studying infinite sequences, it is very important for you to master loops. We give lots of examples and exercises. We first illustrate the for loop by writing a short program to compute the first 15 elements in the list of perfect squares. Let’s name our list S. In this case, we have an explicit formula for the i-th term, namely S[i] = (i + 1)2 (Remember that lists are zero-indexed!) We obtain S by beginning with an empty list. We then go through a loop 15 times. We indicate this with the following syntax: for i in range(0,15): Note the colon at the end of the line. Such a command will begin with i = 0, will increment i by one after executing the indented block of code (as yet to be shown), and will continue as long as the incremented i is still strictly less than 15. Thus our block of code after our for statement will be executed for i = 0, 1, 2, . . . , 14. At each step i, we wish to add to our list the i-th term of our sequence. We use the list function “append” to add a new element. We’ll talk more about functions later, but for now know that “append” is one of many function that all 8 lists inherently have, and we call our list’s append function using “dot notation”. Of course after we generate our list we must remember to print it. Here’s the entire program. Note that the block of code to be executed each time through the loop must be indented. # start by defining an empty list S = [] # generate terms for i = 0, 1, 2,..., 14 for i in range(0,15): S.append( (i + 1)**2 ) print(S) Exercise 3 (a) Generate the first 20 terms in the sequence given by S[i] = 1.0/(i + 1). (b) What happens if you use 1/(1 + i) in your program instead of 1.0/(i + 1)? Explain! Next, let’s look at an example that takes a natural number a and computes a!. Recall that a! is the natural number obtained by multiplying together all the natural numbers less than or equal to a. Thus 1! = 1, 2! = 1 · 2 = 2, 3! = 1 · 2 · 3 = 6, and so on. Let’s write a program to find 8!. We write it in such a way that we could use it to compute factorials of other natural numbers by just changing the value of a in the first line of code. We thus begin by setting a equal to 8 and then define a variable called “result” that we initially set to 1 because 1 is the multiplicative identity. Next, we want to go through a loop 8 (or a) times, each time multiplying the old result by the next natural number. The line of code to be executed each time is simple - we just replace our result with that number times i + 1. Of course we need a print command at the end of the program if we want to know the result. Here’s the entire program. a = 8 result = 1 for i in range(0,a): result = result*(i+1) print(str(a)+"! is: "+str(result)) If you just want to output the result instead of outputting a fully-formatted sentence, you can end with the following: print(result) Exercise 4 The i-th triangular number, T [i], is the sum of all natural numbers less than or equal to i. Thus T [0] = 0 (there are no natural numbers less than 9 or equal to 0), T [1] = 1, T [2] = 1 + 2 = 3, T [3] = 1 + 2 + 3 = 6, etc. Write code to generate T [n] for n = 30. The while loop Loops can be constructed in other ways. For example, sometimes rather than running through a loop a fixed number of times, you want to run through it as long as some certain condition is met. The while loop is good for this situation. As an illustration, let us write a second program to compute a!, this time using a while loop. We start out the same way, setting a equal to 8 and “result” equal to 1. Each time through the loop, we take “result” and replace it with the old result times a natural number. The first time through, we multiply by a = 8. The second time though, we want to multiply by 7. We accomplish this by replacing the old a with a − 1. We keep going through the loop until the updated a is no longer positive, and then re print the result? a = 8 result = 1 while a>=1: result=result*a a=a-1 print( "The result is: "+str(result)) Exercise 5 What happens if you replace the last line of this program with print(str(a)+"! is: "+str(result) )? Explain. 10