Chapter 1 – Exploring Python Almost everybody has used a computer. If you have used a bank ATM, you have used a computer...
14 downloads
491 Views
255KB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Chapter 1 – Exploring Python Almost everybody has used a computer. If you have used a bank ATM, you have used a computer. If you listen to music on an iPod, you have used a computer. If you have a cell phone, you have used a computer. Nowdays, even your credit card may have a computer embedded in it. The fact that the computer can be used in such a wide variety of different applications is astounding. But the computer is really just an extremely fast calculating machine-it performs a great many very simple tasks with extreme rapidity. Before the computer could be used in any of the applications named above, somebody had to lay out the exact instructions required to perform the task. This process is termed programming. A computer does not understand natural languages, such as English. You cannot tell the computer “Play for me again that tune you played last Tuesday afternoon around 4PM”. Instead, instructions for a computer must be presented in a very structured form, termed a programming language. There are a great many programming languages in common use. In this book you will learn one of these, a language named Python.
Interactive Execution Unlike many computer languages, Python allows the user to work in an interactive fashion, much like a calculator. You type an expression, and immediately the expression is executed and the result printed. If you start the Python system, you should first see a line containing version and copyright information. This will be immediately followed by a line beginning with three right arrows: Python 2.3.5 (#1, Mar 20 2005, 20:38:20) [GCC 3.3 20030304 (Apple Computer, Inc. build 1809)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
The three right arrows are the expression prompt. The prompt is telling you that the Python system is waiting for you to type an expression. The window in which the output is displayed and input is gathered is termed the console. Try entering a simple mathematical expression, such as 2 + 3. After you hit return, you should see the result printed, followed by a new prompt. >>> 2 + 3 5 >>>
You can try various other expressions to get used to this style of operation. (We will have a whole section on the range of operations that Python supports in a bit). You halt interactive execution by typing control-D or control-Z (that is, typing D while holding down the control key. It’s control-D on Macintosh and Unix machines, control-Z on windows machines). Try halting execution and restarting the Python system until you feel
Exloring Python – Chapter 1
1
comfortable with the process. If you haven’t made one already, try making a purposeful mistake. For example, try typing 2 plus three >>> 2 plus three
The Python system doesn’t know what to make of this statement. Therefore, it produces an error message; a text message that hopefully should tell you what it does not understand. Afterward the system resets itself, and issues a new prompt and waits for you to continue. >>> 2 plus three File "<stdin>", line 1 2 plus three ^ SyntaxError: invalid syntax >>>
Almost all Python expressions are typed on a single line. You can see this if you type a binary operation, and forget to fill in the right side: >>> 2 + File "<stdin>", line 1 2 + ^ SyntaxError: invalid syntax
An exception to this rule occurs when expressions are typed in parenthesis. Each opening parenthesis must be matched to a closing parenthesis. If the closing parenthesis is not found, a continuation prompt is given. Normally this continuation prompt looks like an ellipsis, that is, three dots. >>> (2 + ...
The continuation prompt is telling you that there is more to the expression you need to type. Fill in the rest of the expression, hit return, and the expression will be evaluated as before: >>> (2 + ... 3) 5
If you are faced with a three dot prompt and don’t know what to do you can simply enter right parenthesis until you get back to the top-level prompt.
Comments Any text that appears after a hash-mark (#) is termed a comment. Comments are ignored by the Python system. They are used purely to communicate information to a human reader. Exloring Python – Chapter 1
2
>>> 2 + 3 # print two plus three 5
In interactive input a line consisting entirely of comments will produce a continuation prompt. You can simply hit return to proceed. >>> # nothing at all ... >>>
While legal, comments are not common in interactive input. However they are very common when Python statements are gathered together in a file to form a program. We will describe this style of use in the next chapter.
Types Think of the information that is printed on your driver’s license. There is your name, your age, your date of birth, a driver license number issued by the state, probably an indication whether or not you need corrective glasses, and so on. Notice that this information comes in a variety of forms. Your age is a number. Your name is a string. Whether or not you need lenses is a true/false value. In programming languages we call these different forms of information types. The Python language has several built-in types. The type you have using up to this point is termed an integer. Integers are the counting numbers you are used to from mathematics, both positive and negative. Some programming languages place an upper bound on the size of integers you can use. Python does not. Integers can be as large as you can type. >>> 999999999999999999999999999999999999 + 1 1000000000000000000000000000000000000 >>>
On some systems you may find the capital letter L following the output, indicating that the result is Long. The integer type does not include fractional numbers, which in programming languages are termed floating-point. A floating-point number (or simply a float) has a decimal point and a fractional part. Arithmetic operations work with either integer or floating-point: >>> 2.4 + 3.7 6.0999999999999996
Notice that floating-point numbers are subject to a phenomenon called rounding error. Computations that would be precise when performed in base-ten arithmetic may not be when performed in the internal computer arithmetic. Floating-point numbers can also be written in scientific notation. This format is written as a number followed by the letter e (or E, either works) and an integer. The integer represents a power of ten.
Exloring Python – Chapter 1
3
>>> 2.3e3 2300.0 >>> 2.3e47 + 5.2e46 2.8199999999999998e+47 >>> 1.0 + 2.3e47 2.2999999999999999e+47
Often you can ignore the distinction between integer and floating-point, and simply think of a value as being a number. There is one common situation where the difference is important, although this is an area where the definition of Python is in transition. For versions of Python before version 3, and for most other programming languages, the division operator (that is, the slash), works differently for integers and floating point values. For integers the result is the integer part of the quotient; any remainders are simply thrown away: >>> 5 / 2 2
For floating point numbers the result is floating point: >>> 5.0 / 2.0 2.5
When one argument is integer and the other is float, the integer is converted into float and the result is float: >>> 5.0 / 2 2.5 >>> 5 / 2.0 2.5
This will change in Python version 3. After that point a single slash division will return a true division, that is, the value 5/2 will be 2.5. A new operator, written as two slashes, will be used to produce integer division. Another common type is a string. Strings can use either single or double quote marks. This is useful when a string must include a quote mark: >>> “hello” ‘hello’ >>> ‘hi there’ ‘hi there’ >>> “don’t do that” “don’t do that” >>> ‘I said: “stop right now” ’ ‘I said: “stop right now” ‘
Try creating several different string expressions, using both forms of quote mark. The boolean type represents a true or false value. The most common way to produce a Boolean value is with a relational operator. Exloring Python – Chapter 1
4
>>> 17 < 21 True >>> (2/3) < (3/5) False
The names True and False represent Boolean constants. There are also logical operators (and, or, not) that work with Boolean valued expressions in the expected fashion. >>> True and False False >>> True or False True
Python has a number of other built-in types. These include complex numbers (using, curiously, the letter J instead of the letter I to represent the square root of -1), lists, tuples, dictionaries, functions, and classes. We won’t use complex numbers in this book, however the others will be examined in later chapters.
Names (Variables) Computers are used to manipulate information. Often lots of information. In order to help keep track of things, values can be given names. A value is given a name by means of an assignment statement, or simply an assignment. The text to the left of the assignment is the name, and the text to the right is the value that will be remembered for the name: >>> name = ‘fred’ >>> count = 7
After an assignment, if you use the name, the value stored for the name is remembered. >>> name ‘fred’ >>> count + 2 9
You can change the value stored with a name simply by assigning the name a new value: >>> name = ‘sally’ >>> name ‘sally’
Notice that types are associated with values, not with names. A name can be given a different type simply by assigning it a new value: >>> name = 5.0/2 >>> name 2.5
Exloring Python – Chapter 1
5
A name must begin with a letter or underscore, and can include any number or letters, digits, or underscores. A name cannot begin with a digit, nor include any characters other than letters, digits, or the underscore character. A named value is often termed a variable (since it represents a quantity that can change over time, that is, can vary). You should at this point stop reading and experiment with the Python interpreter, creating and using several variable names, until you are comfortable with this idea. Variables are useful when we want to use a value more than once, or when we want to break a complicated computation into several smaller parts. Do not call the = operator ‘equals’, as that confuses the concept with the mathematical notation of equality, which uses a different operator. Instead, the symbol should be read as “assignment”. So if you are reading aloud the statement given earlier you would say something like “the variable name is assigned the value sally”. If you want to represent the mathematical idea of equals, which is asking the question whether a variable is or is not holding a value in question, you must use the == operator: >>> name == ‘sally’ True >>> name == ‘name’ False
Which brings us to a discussion of …
Operators Each of the built-in types brings with it a set of operators. The following are the binary operators recognized by Python. (Binary operators are those that appear between their two arguments, as in 2+4). Not all operators can be used with all types, and sometimes operators have surprising meanings. Try typing ‘abc’ * 3, for example. The exercises at the end of this chapter will lead you through an exploration of the operations provided by Python. +
-
*
**
/
%
<<
>>
&
|
^
<
>
<=
>=
==
!=
<>
The following can be used as unary operators +
-
~
You may remember from a mathematics class that multiplications are performed first, then additions. This is termed precedence. The order that operators are evaluated can be controlled using parenthesis. Using the idea of precedence, explain why the following two expressions produce different results. >>> 5 + 2 * 3 11 >>> (5 + 2) * 3 21
Exloring Python – Chapter 1
6
In mathematics there is also an issue termed associativity. This applies when two operators with the same precedence are used in one after another. For example, does the sequence 9 – 5 – 2 evaluate to 6, which would be the same as 9 – (5 – 2), or to 2, which is the same result as (9 – 5) – 2? Try it and see. What about 12 / 2 * 3 ? What does the latter expression tell you about the precedence of the multiplication and division operators? Python has precedence and associativity rules for all operations. When in doubt about these rules you should use explicit parenthesis. A few binary operations have a text name. The most common examples are the logical operations and, or and not. >>> (3 < 7) and (4 < 5) True >>> (3 < 2) or (6 > 4) True
Another operator with a text name is in. This can be used (among other purposes) to determine if a character value is found in a string. It returns true if the left argument is found in the right argument, and false otherwise. >>> ‘a’ in ‘abc’ True >>> ‘z’ in ‘abc’ False
Does the in operation work if the left argument is larger than a single character? Try it and see if you are correct.
Functions Not all operators use the binary operator syntax. An alternative syntax is termed the function call notation. In this notation the name of the operation is given first, followed by a list of the arguments surrounded by parenthesis. For example, the abs operation returns the absolute value of the argument: >>> abs(-3) 3
Just as the parenthesis in an arithmetic expression indicated that the enclosed expression needed to be evaluated first, the arguments to a function are first calculated, and then the function is applied: >>> abs(2 – 3 * 7) # first calculate 2-3*7, which is -19 19
The function len returns the number of characters (that is, the length) of a string.
Exloring Python – Chapter 1
7
>>> len(‘abc’) 3 >>> len(‘ha’ * 4) 8
Most operations defined using this syntax have a fixed number of arguments. However, a few can take any number of arguments. An example is the min function, which returns the smallest of the arguments, regardless how many are given: >>> min(2, 3) 2 >>> min(5, 6, 2.2, 17) 2.2
An important class of functions are used to convert values from one type to another. The function int, for example, can be used to convert a string into an integer. The function str goes the other way, converting a value (such as a number) into a string: >>> int(“42”) 42 >>> int(“42”) + 2 44 >>> “42” + “2” ‘422’ >>> str(42+2) ‘44’ >>> str(42+2) + “2” ‘442’
The int function can also be used to convert a floating point value into an integer. For example, suppose you live in a state where the sales tax rate is 8.7%. How much will you pay for an item marked $10.52? >>> 8.7 * 10.52 91.523999999999987
Since fractional pennies are not part of US currency, we can convert the amount in cents using the int function: >>> int(8.7 * 10.52) 91
Most states, however, don’t simply truncate the fractional cent amount, but instead round to the nearest cent. There is a function that will do this, but for a floating-point argument it returns a floating-point result: >>> round(8.7 * 10.52) 92.0
We can combine round and int to return a value that is both rounded and integer:
Exloring Python – Chapter 1
8
>>> int(round(8.7 * 10.52)) 92
The function eval takes a string, interprets it as an expression, and returns the result. >>> eval (“42+2”) 44
The function named type returns a somewhat cryptic value that nevertheless can be used to determine the type of a value. >>> type(42) >>> type(2.5) >>> type(999999999999999999)
Try using the type function with several different argument values. An extremely useful function is raw_input. This function takes as argument a prompt. It prints the prompt, waits for the user to respond, and returns as a string the value typed. >>> name = raw_input(“what is your name?:”) fred >>> name ‘fred’
# user types, e.g. fred
You can combine raw_input and eval to make a simple calculator: >>> expr = raw_input(“type an expression: ”) 2 + 3 >>> ‘answer is’ ‘answer is’ >>> eval(expr) 5
If you completed the exploration of operators suggested earlier you know that the + operator can be used to concatenate two strings, and that the str function can be used to convert a value into a string. Combining these provides a better way to produce multipart output, such as the earlier line. Instead, this could have been written as follows: >>> ‘answer is ‘ + str(eval(expr)) ‘answer is 5’
Notice how we have called one function (namely, eval) inside the argument list for another (the function named str). Just as before, the argument to str will be computed. But to do so, the function named eval must be computed. It is very common to nest function calls one inside another in this fashion. They are evaluated from the inside out, firs the innermost function, then the next level, and so on.
Exloring Python – Chapter 1
9
Print Statement An even simpler way to produce multipart output is to use the print statement. The print statement takes a series of values separated by commas. Each value is converted into a string (by implicitly invoking the str function) and then printed. Additionally, quote marks are removed from printed strings. >>> print ‘answer is’, eval(expr) answer is 5
The print statement also formats numbers slightly differently than simple expressions. For example, it produces fewer digits for floating values: >>> 1.0/3 0.33333333333333331 >>> print 1.0/3 0.333333333333
Finally, the print statement recognizes a few commands that can be used to format input. These are termed escape characters, and are written as a character following a backslash. The most common is the newline character, written \n. This moves the output on to a new line. The tab character, \t, moves the output to the next tab stop. To print a literal back slash character you use two slashes, \\. >>> print "one\ntwo\tthree" one two three
Escape characters can also be used to embed a quote mark within a quoted string. >>> print 'don\'t do that' don't do that
We will discuss the print statement, as well as other Python statements, in more detail in the next chapter. Escape characters are described in Appendix A. Experiment with the print statement and various different types of expressions.
Input from the User The combination of eval and raw_input occurs so frequently that Python provides this combination as a standard function, named input. Use input if you are reading a number, and raw_input if you want the response stored as a string. >>> x = input(“type a number:”) # user types a response, e.g. 5 >>> print x + 2 7
We can illustrate the use of input by a simple series of statements to convert a temperature from Celsius to Fahrenheit. Exloring Python – Chapter 1
10
>>> c = input(“what is the temp in Sault St. Marie, Ontario?”) what is the temp in Sault St. Marie, Ontario? 17 >>> f = c * 9.0 / 5.0 + 32 >>> print ‘across the river, in Sault St. Marie, Michigan, it is ‘, f across the river, in Sault St. Marie, Michigan, it is 62.6
Indexing (Slicing) Another common operation uses the square brackets. This is termed indexing, or slicing. An index or slice returns a portion of a larger value. In a string this can be used to produce a substring. Index values start at zero, and extend upwards to the number of characters in the string minus one. When a single argument is given it is one character out of the string. When two integers are written, separated by a colon, it is termed a slice. The second value is an ending position. A portion of the string starting at the given position up to but not including the ending position is produced. >>> ‘abc’[1] ‘b’ >>> 'realtor'[2:6] 'alto'
You should at this point stop reading, and experiment with the slicing operator with various different strings and argument values, until you are comfortable with the notation. If a colon is given but the last number is omitted the result is the remainder of the string starting from the given position. >>> ‘recurrent’[2:] ‘current’
Finally, if no number is given before the colon the result is the initial string up to but not including the given position. >>> ‘halter’[:4] ‘halt’
String are immutable, meaning they cannot be changed once assigned. Instead, a new string constructed out of an existing string can be formed in parts, using slicing commands. >>> word = 'red' >>> word[1] = 'a' # show word cannot be changed Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: object doesn't support item assignment >>> word = 'b' + word[:2] + 'a' + word[2:] >>> word # change red to bread 'bread'
Exloring Python – Chapter 1
11
Slicing may seem complicated, but is an extremely powerful operation. You should experiment with different slicing possibilities until you feel comfortable with the technique. And remember that whenever you are in doubt about the meaning of an expression you can simply try some examples at the keyboard. The concepts of indexing and slicing are also used with the list and dictionary data types, which we will investigate in a later chapter.
Modules and dot notation Another common syntax is termed dot (or class) notation. A name can be qualified by the class or module in which it is defined. A module is a library of functions used to provide a service. Most Python programs will use one or more modules. An example is the math module, which defines a number of common mathematical functions. To tell the Python system you want to make use of the services provided by the module you type an import statement, such as the following: >>> import math
After the import statement you can then use the functions defined in the math module. Each value or function is preceded by the name of the module in which it is defined. >>> math.pi # a value defined in the math module 3.1415926535897931 >>> math.sin(math.pi/2.0) 1.0 >>> math.sqrt(1000) 31.622776601683793
There are many modules defined in the standard Python distribution, and many more can be downloaded from public sources. The use of these modules greatly simplifies the creation of Python applications. Let us use the math library to write statements that will solve a quadratic equation. A quadratic equation has the form ax2 + bx + c = 0. Recall that such an equation has two solutions for the value of x, and these are given by the formula x = -b +- sqrt(b2 – 4ac) / 2a The input to our program consists of the three values a, b and c. These can be read using the input function. The outputs are the two values given by the formula. >>> >>> >>> >>> >>> >>>
import math a = input(‘type the b = input(‘type the c = input(‘type the d = b * b – 4 * a * d = math.sqrt(d)
Exloring Python – Chapter 1
value for the coefficient a’) value for the coefficient b’) value for the coefficient c’) c
12
>>> print ‘first root is ‘, (-b + d) / (2 * a) >>> print ‘second root is ‘, (-b – d) / (2 * a)
An Attitude of Exploration In this chapter we have introduced many new concepts and expressions. The reader may at first feel overwhelmed by the amount of information to remember. Don’t worry. With experience and practice all these ideas become second nature. As we noted in the discussion on slicing, an important part of gaining experience is experimentation. The interactive nature of the Python system makes experimentation extremely easy. Even experienced Python programmers will frequently start an interactive session just to type small statements and expressions to remind themselves how a particular operator or function works. You should develop this attitude of exploration, and whenever you are in doubt about a feature, try it out!
Bitwise Operators *1 If you have followed the instructions to explore the meaning of the various operators provided by the Python system you may have been confused by the operators <<, >>, &, |, ^ and ~. These operations make sense if you understand that computers process information in a different form than you are used to. Humans work with numbers in a base-10 system. When we see a value, such as 4,372, we read this as representing 4 times one thousand (that is, 103) plus 3 times one hundred (102), plus seven times 10 (101) plus 2. Internally, computers work in a much simpler system. They work with only two values, 0 and 1, termed bits, and a number system based on 2. Any number can be written in base 2. Take, for example, the number 42. This is written 101010. To convert back and forth, read the number from the right side, rather than the left. 101010 is 0 times 1 plus 1 times 2 plus 0 times 4 (22) plus 1 times 8 (23) plus 0 times 16 (24) plus 1 times 32 (25). 2 + 8 + 32 = 42. The operators <<, >>, & and | are best understood if you convert their arguments into this internal binary representation. Take, for example, the left shift operator, <<. This operation shifts the left argument represented in base two by an amount given by the right argument. For instance, consder the expression 5 << 3. The value 5 is 0101 in binary. Shift this left by 3 places, and you have 0101000. Convert this back to base 10, and you have the value 40. >>> 5 << 3 40
1
Sections marked with an asterisk indicate advanced and/or optional material, and can (probably should) be omitted on your first reading. Once you have grasped the remainder of the chapter, come back and examine the more advanced sections. Exloring Python – Chapter 1
13
The >> operator shifts values to the right. See if you can figure out the binary representation for the value 15. Then, using that representation, explain the following behavior: >>> 15 >> 2 3
The operators & and | perform a bitwise and and or, respectively. These operations work bit by bit. A 1 bit can be thought of as corresponding to the logical value true, and a 0 as the logical value false. An and of two bits is 1 if both bits are 1, and an or is 1 if either bit is 1. This is just like a logical and if true if both arguments are true, and a logical or is true if either argument is true. So the bitwise & of 5 and 12 (0101 and 1100, respectively) is 4 (0100) while the bitwise | is 13 (1101). >>> 5 & 12 4 >>> 5 | 12 13
The ^ operator is known as an exclusive-or. The exclusive-or of two bits is 1 if either is 1, but not both. So 5^12 is 9 (1001). >>> 5 ^ 12 9
The unary operator ~ performs a bitwise inverse. In the result every bit that was 0 becomes 1 and every bit that was 1 becomes 0. Because of the way that negative numbers are stored in the computer a positive value becomes negative, and a negative value will become positive. >>> ~4 -5 >>> ~ -7 6
A version of the int function that takes a string and a base can be used to convert base-2 numbers (or any other base, for that matter) into base-10 integers: >>> int(“0101”, 2) 5
Bitwise operations are useful in certain situations, but are infrequent in practice.
Encodings * The underlying hardware for a computer works with simple zeros and ones. These are called bits. All values manipulated by a computer must ultimately be represented by bits. The way the bits are interpreted is what gives meaning to the values.
Exloring Python – Chapter 1
14
You started to explore this in the previous section, where you experimented with the encoding for integer values. An integer value, such as 42, is encoded as a string of bits, for example 101010. For efficiency reasons computers normally work with a fixed block of bits. Some of the more common blocks are the byte (8 bits) and the word (on most machines, 32 bits). Integers, for example, are commonly stored as a 32-bit word. This means that the value 42 is really 00000000000000000000000000101010 A single character is normally stored as a byte, that is an 8-bit quantity. You can find the integer value of a character, as an integer, using the function named ord (short for ordinal). >>> ord(‘a’) 97
This tells you that internally the character ‘a’ is stored as the integer value 97. The mapping of characters to integer values is given by a standard, called ASCII (the American Standard Code for Information Interchange). We say that “the ASCII representation of the character a is 97”. An 8 bit byte allows 256 different values. This is fine for roman based languages with a small number of letters (for example, 26 letters in English), but is insufficient for languages such as Chinese or Korean. Letters in these languages are encoded in a 16-bit form, termed Unicode. Using a web search you can find the Unicode values for letters in various languages. A string is represented internally by a series of eight bit bytes. For example, the word ‘Python’ is represented internally as: 80 121 116 104 111 110 The numbers are the ASCII representation for the six characters. Use the ord function to determine how these particular numbers were selected. A block like this is sometimes termed an array. We will have much more to say about arrays in a later chapter. An integer that is larger than 32 bits is similarly represented by an array of integers. By the way, the function chr (short for ‘character’) is the opposite of ord. It takes an integer value, and returns the corresponding character: >>> print chr(97) ‘a’
A floating-point number is typically represented using a two integers, similar to the idea of scientific notation. In scientific notation a value of 24.35 can be represented as 2435 * 10-2. The base can be omitted, and only the two integers 2435 and -2 need be represented.
Exloring Python – Chapter 1
15
-2
2435
Computers, as we noted earlier, work in base 2 rather than base 10, however the underlying idea is the same. Larger data types require a more complicated encoding, ultimately, however, everything must be reduced to bits. Consider a picture. You may know that pictures are made up of little dots, termed pixels. Each of these dots is a distinct color. You may remember from an art class that all colors can be created from the basic colors red, green and blue. In a computer a color is often encoded as three bytes that represent the amount of red, green or blue. This is termed the RGB encoding. Each pixel in this system requires 24 bits (that is three colors times 8 bits for each color). A simple way to represent a picture would be an array of pixels. In a 640 by 480 pixel picture (a common size for digital images) this would require 921,600 bytes (that’s 640 times 480 times 3). Because large images are relatively common there are various more sophisticated techniques used to represent pictures that use less memory than the array of pixel format, but the ideas are similar. Sounds, movies, in fact all data values manipulated by a computer must ultimately be encoded as a series of bits.
Exercises 1. Examine each of the following expressions. Predict what the result should be, then evaluate the expression using the Python interpreter to check your predictions. Explain what the type is for each expression. If an expression is illegal, explain why. a. 10 / 5 b. 5 / 10 (or 5 // 10 in newer Python systems) c. 5.0 / 10 d. 10 % 4 + 8 / 4 e. 3 ** 10 / 3 2. Translate each of the following mathematical expressions into an equivalent Python representation. a. (3 + 4)(7) b. n (n – 1) / 2 c. sqrt(a * a + b * b) 3. Explain the difference between 42 + 2 and “42” + “2”. What is the + operator doing in each case? 4. What is wrong with this version of the quadratic formula?
Exloring Python – Chapter 1
16
r1 = (-b + d) / 2 * a 5. Write a series of Python statements that will first ask the user to type today’s exchange rate between US Dollars and Euros. Next, ask the user to type a value in Dollars. Finally, print the equivalent value in Euros. 6. Write a Python statement that reads a numeric value from the user, placing it into a variable named x. Then write a print statement that will print the values x, x2, x3 and x4. Use tab characters to separate the four resulting values. Write a second print statement, but use newline characters instead of tab stops. 7. Write three Python statements. The first should read a number from the user that represents a temperature in Fahrenheit, placing the value into a variable named f. The second statement should convert the value into Celsius, placing the result into a variable named c. The third statement should print the values of f and s with a descriptive notation. 8. Write a series of Python statements that will read a number from the user that represents the radius of a circle. Then use a print statement to show the circles diameter, circumference and area. You can import the math module and use the constant math.pi to represent the constant π. 9. Write a series of Python statements that will import the math module, read a number from the user that represents an angle given in radians, and then prints the sine and cosine for the given angle. 10. Try writing a print statement that uses the escape character \b. What do you think this is doing? Try placing several characters before and after the \b. Try typing several in a row after a series of characters. 11. Try writing a print statement that uses the escape character \a. What do you think this is doing? Can you think of a use for this feature? 12. Python supports eighteen different binary operators. Experiment with each of these, using arguments that are integer, floating point, and string. Not all operators work with each argument type. Fill in the following table. For each operator, give either a short description and indicate the type of the result or the words NOT LEGAL. Operator + * ** / %
Integer
Exloring Python – Chapter 1
Floating point
String
17
<< >> & | ^ < > <= >= == != <> 13. Assume the variable named n holds a positive integer value. How do you determine the last digit of n? (Hint, what does the % operator do?) 14. You have probably discovered that the % operator performs the remainder operation when used with two positive integer arguments. But what does it do when one or both arguments are negative? >>> 2 >>> -1 >>> 1 >>> -2
11 % 3 11 % -3 -11 % 3 -11 % -3
Try to come up with an explanation of this behavior. To do so, make a chart of the values from -15 to 15, and for each compute the result when used with the mod operator and the value 3. Then do the same chart with -3. Can you see a pattern? From this pattern can you explain the behavior of the mod operator? 15. Your explorations of the chart in exercise 1 may not have led you to explore what happens if the arguments are different types. Try each of the eighteen operators using the value ‘abc’ as the left argument and the value 2 as the right argument. Which of the 19 operators are legal? Can you explain what the result represents? Reverse the arguments, using 2 as the left argument and ‘abc’ as the right. Which are still legal? 4. Can you select values for x and y in the expression –x + y that will help you determine the precedence of the unary – operation in comparison to the binary + operator? 5. Python allows relational operators to be chained. If x is a number, what do you think the expression 3 < x < 5 means? Can you design an experiment to test your Exloring Python – Chapter 1
18
guess? What about 5 > x > 2. Does an expression such as 2 < x > 4 make any sense? What does it mean? 6. You may have noticed that integers come in two flavors, small integers and long. You can see this using the exponention operator. A value 28 is a normal integer, while 2100 is long. >>> 2**8 256 >>> 2**100 1267650600228229401496703205376L
The L at the end of the number indicates the value is Long. (If your system does not supply the L the same information can be found using the function named type). Find experimentally the smallest integer I for which 2 ** I is long. 7. Each row in the following table consists of a starting word and an ending word. Assign the starting word to the name w. Then using only indexing and slicing commands, convert the starting word into the ending word. The first is done for you as an example. Starting word w = ‘kyoto’ ‘bread’ ‘kartasura’ ‘listen’
Ending word ‘tokyo’ ‘bead’ ‘surakarta’ ‘silent’
command w[3:] + w[:3]
8. What happens when you try to index a string value with a number that is out of range? Such as ‘abcdef’[9]? What happens when you use a negative number, such as ‘abcdef’[-2]? How about ‘abcdef’[-9]? Can you provide a rule to explain the result? 9. Assume that the name w is assigned the value ‘abcdef’. Explain the meaning of each of the following: w[2], w[2:], w[:2], w[2:4], w[:]. 10. Try typing the following expressions: ‘abc’[0], ‘abc’[0][0], ‘abc’[0][0][0], ‘abc’[0][0][0][0]. Can you explain what is going on here? 11. What happens if you try to divide an integer value by zero? 12. What happens if you type control-D (control-Z on windows machines) when the Python system is waiting for input for a call on raw_input? 13. Assume that a year contains 365 days (that is, ignore leap years). Let y be the name holding a value that represents an age in years (e.g., 23). Write an
Exloring Python – Chapter 1
19
expression that represents the number of seconds in that period (e.g., the number of seconds in 23 years). 14. Using the fact that the unary ~ inverts each bit in an integer, and the knowledge of the binary representation for positive numbers, experimentally discover the representation of negative numbers. For example, you know the representation of 5 is 0101. The following tells you that the internal representation of -6 is the inverse, that is 1010. Experiment with other values. Can you develop a general rule that explains the representation of a negative number as the inverse of a positive number? >>> ~ -6 5
15. The functions max and min can also be used with string arguments. What is the value of max(‘abc’)? Of min(‘abc’)? Can you explain the meaning of the result? Using max and min, can you tell which is larger, the lower case letter ‘a’ or the upper case letter ‘A’? What about ‘a’ and ‘0’? 16. Include the module named random, and then print the value of the expression random.random(). Do it several times. What do you think the expression represents? Try typing random.randint(a, b) with various different integer values for a and b. What does it return? What happens if you use non-integer arguments with randint? 17. What happens if you take the square root of a negative number? Try importing the cmath module and using cmath.sqrt() instead. Now what happens? 18. Most of the assignment operations can be combined with an assignment, to form what is known as an assignment operator. For example, what do you suppose is the value of the variable a after the following two commands. Write down the statements you might use to verify your guess. Give examples to demonstrate what various other assignment operators do. What would happen if the following example used strings instead of integers? >>> a = 7 >>> a += 5
19. The function int can be used to convert a float into an integer, as in int(2.9). It can also be used to convert a string containing an integer into an int, as in int(“2”). You might then be tempted to think that it could convert a string containing a float into an int, as in int(“2.9”). Does this work? 20. What is the value of int(“0101”, 3). Explain how this value is derived. Then do the same for int(“0101”, x) for values of x between 4 and 10.
Exloring Python – Chapter 1
20
21. How many different possibilities can be represented using two binary digits (or bits?) How many with three? with 8? 22. The section on encodings gave an intuition for how floating point numbers could be encoded as a pair of integers. Do a web search using the terms “floating point encoding” and find a more detailed description of the actual encoding used by most computers. 23.
Exloring Python – Chapter 1
21