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
Python Tutorial: Getting Started What is Python? Python is a relatively new language which is both great for beginning programmers and a language really used in the world today. The following are its key ingredients: An interactive interpreter Relaxed typing Object-less or object-oriented Lots of cool libraries (e.g., media computing, Google/Amazon web services) Bare-bones syntax Allows beginning students to focus on problem solving allows beginning students to create cool programs early on. Why Use Python? With so many programming environments available, why select Python? First of all, it's free. You won't need to invest an arm and a leg just to get started. All you will need to do is go to http://www.python.org/ and download the software. Using the Interactive Python Interpreter 1. On Windows, Select Start | Programs | Python2.4 | IDLE 2. In the window that appears, you should see the python prompt >>>. This is asking you to enter python commands. Type in the following to see what happens (don't type the >>>): >>> print 'hello'. >>> print 3*6 >>> print 3/6 >>> print 3.0/6.0 >>> print 2+4*2 >>> print 'abc'+'def' >>> first='david' >>> last='wolber' >>> print first+' '+last >>> x = 5 >>> print x*7 >>> print 'x'*7 >>> grades=['a','b','c'] >>> grades[1] >>> grades[2]=44 >>> list >>> grades[3]=55 Don’t be afraid to experiment. Whenever you learn something new that you can do with Python, try making slight changes (or bigger changes!) and play around until you’re confident that you understand just what’s going on. Don’t limit yourself to what’s actually printed on the sheets! Questions Why does 3/6=0 2. What is the value of 2+4*2? Why? 3. Python lets you add strings, e.g., 'abc'+'xyz'. What does '+' do? 4. what is the result of 'x'*7 5. What does the 'type' command do? 6. What is a type? 7. What types did you explore above? 8. Are python lists homogeneous or heterogeneous? 9. Can Python lists grow? Writing a Program in a File You can also write a program in a file and run the whole thing at once. Select File | New Window. Then just enter some python commands in the window and save the file with a ".py" extension, e.g., hello.py. 1. Create a new file and enter the following statements: print "hello" print "world" name = "jive" print name 2. Save the file as 'hello.py' in a subdirectory 'pythonCode' of your h: directory. Run the program by selecting Run | Run Module. The following should print: hello world jive. In-class Problems 1. Create a new file named addup.py. Inside it, write a program that adds up all the elements of a list. The first line in the program should create a list, e.g., list=[3,4,5]. The program in this case should print 12. Introduction to Python I/O I/O is short for input-output. Input usually means the data entered by the end-user of the program. When you use Microsoft Word, you are playing the role of the end-user (sometimes shortened to just plain 'user'). The player of a video game is its 'end-user'. When programming, we often switch between playing the role of programmer and end-user. We're the end-user when we are testing whether the program works. We usually call the program itself the system, as in 'when the end-user enters a number, the system responds by calculating a result and displaying it.' The input of a program can also come from a file, e.g., banking software might run through all the data in its files, adding interest to every account. Output is what the program produces. For command-line programs, its just whatever is printed on the screen. Of course for programs with graphical user interfaces, its much more complex. User Input in Python Python has two key functions to deal with end-user input, one called raw_input() and one called input(). When you call these functions, the system will wait for the end-user to enter something. The system return the user's entry as a string result from the function. If you execute the statement: >>> result = raw_input() Python will wait for you (the end-user) to enter something. Enter some text and hit return. Then type >>> result This should print whatever the end-user typed. Generally, we want to prompt the user for input. You can do this by adding a parameter to the 'raw_input()' call: >>> x = raw_input('please enter a string:') please enter a string: hello >>> x 'hello' Generally, we use input functions from a program, not the interactive interpreter. Open an IDLE window and create a file with the following line: result = raw_input('please enter a string:)' print result save the file as io.py, then run the program. User input and types The function raw-input() always returns a string. So if the user enters 7, Python interprets it as the string '7'. Sometimes this is fine, but often we want to perform computations on numbers, and as far as the computer is concerned, '7' is a symbol and not a number. If you want to 'interpret' input as an integer, you need to convert it. Python provides some type conversion functions to do so, such as: x=int('7') # puts the integer 7 into x. f=float('7.7') #puts the floating point number 7.7 into f. Using a type converter, one could get an integer from the user, and peform a computation on it, with the following: >> s=raw_input('enter a number:') enter a number: 6 >> x = int(s) >> y = x+3 >> y 9 Because this is a bit laborious, Python provides the 'input()' function, which converts things automatically. 'input()' basically looks at what the user enters, and automatically determines the correct type. >> x = input('enter a number:') enter a number: 4 >> x 4 The only problem with 'input' is you have to assume the user will enter what you are expecting. If they don't, you are in trouble. For instance,suppose as a programmer I'm expecting an integer. What happens on the following: >> x = input('enter a number:') enter a number: abce >> y = x+3 For now, just use the input() function when you are expecting an integer from the end-user, and raw_input when you are expecting a string. In-Class Problem Write a program that asks the end-user for an account balance and an interest rate, and then displays what the balance will be after one Media Computing Intro Jython Environment for Students (JES) year. JES is a development environment for Python. To run it from Linux, select USF CS | JES. From Windows, select Start | All Programs | JES. Loading JES might take a few seconds. After it comes up, Click on Help | Table of Contents. This will get you to some information and tutorials on how to create images, sound, and movies with JES. For now, just follow the instructions below. JES has two main windows. The top one is a text editor in which you can create .py python programs. The bottom one is a python interactive interpreter. After creating or opening a python file, you can click 'Load' and it will automatically be loaded into the interpreter. JES provides some library methods of its own that are not part of python. One is pickAFile() which pops up a file choosing dialog. In the interactive interpreter, enter the following: >>> fileName= pickAFile() When the file chooser appears, choose some file. >>> print fileName This should print out the full path of whatever file you chose. Now let's view a picture. 1. Open a web browser and find an image. Right-click the image and save it to your home directory. 2. Call pickAFile and this time pick the image file you just downloaded. >>> filename= pickAFile() 3. Create a picture object with the 'makePicture' function provided by JES >>> pic = makePicture(filename) 4. Show it: >>> show(pic) The image should appear. 5. Now let's manipulate the picture. There's a list of functions that can be executed on pictures. To see what exists, select Help ! Understanding Pictures | Picture Functions in JES. For now, let's just draw a line on our picture. Try the following: >>> addLine(pic,0,0,500,500) >>> repaint(pic) Do you see the line on the picture? 6. Draw some text on the picture: >>> addText(pic,100,100,'HELLO') 7. Note that the manipulations take place on an in-memory (RAM) version of the picture. If you want to modify the actual picture file you loaded, you must call >>> writePictureTo(pic,filename) After doing this, go into the folder where the pic is and double-click it. Whatever application opens it should show it with the line. Media Computing: Manipulating Pixels A Picture is worth a Thousand Words Pixels! An image is a matrix of pixels. Below is a snapshot of an image being viewed in the Jython Environment for Students (JES). The left top corner of the image below is coordinate x=1,y=1. The bottom right corner is x=635,y = 740) A pixel is a color. Colors are defined with three attributes: how much red, how much blue, and how much green. Pixel - {redValue, GreenValue, BlueValue} A pixel is thus an example of a complex data type, an object. In this case, the object has three parts. Each of the RGB attributes are between 0 and 255 (how much data is needed to store such an attribute?) {0,0,0} is black. {255,255,255} is white What is Red? Blue? Green? Here's how you can explore an image, including the value of each pixel, in the JES environment: 1. Load an image with a Python program (e.g., pic=MakePicture(filename)), 2. Choose Media Tools | Picture Tool. When the picture appears, click on it. The environment will display the x-y coordinate and RGB values for each pixel. Manipulating Pixels Here are some key functions provided by the JES environment: makeColor(r,g,b) -> this returns a color, e.g., white=makeColor(255,255,255) To make some other color, open a picture, use the Picture Tool, and click on a color to see what its RGB is. Then call makeColor with the same R,G, and B. getPixel(pic,x,y) -> this returns a pixel from an image, e.g., pixel=getPixel(myPic,100,100) Call getPixel when you want to modify some particular pixel. Generally, you'll call setColor after calling getPixel to make the change, see example below. setColor(pixel,color) --> this modifies a pixel to be the given color, e.g., the following changes the pixel at 100,100 to white: white=makeColor(255,255,255) pixel=getPixel(myPic,100,100) setColor(pixel,white) repaint(pic) -->gets the system to redraw the picture. Besides these functions, you'll also need to use nested loops. A nested loop is a while loop within a while loop. The outer loop is used to go through the columns of the image. We usually use "x" to denote the column. The inner loop goes through the rows of an image. We usually use y to denote the row. Conceptually, you set x to 1, then, using the inner loop, go through the entire column (all the rows y). Then the outer loop sets x to 2, and you go through the entire 2nd column. The process is repeated until you've visited every pixel of the image. Here's a program that draws a rectangle in the top-left corner, as in the above picture: name=pickAFile() pic=makePicture(name) show(pic) color=makeColor(255,255,255) # white max=100 x=1 while x <max: y=1 while y < max: pixel=getPixel(pic,x,y) setColor(pixel,color) y=y+1 x=x+1 repaint(pic) In-class Problems 1. Copy the code above. Open JES and paste the code into the top window. You may need to fix the indentation in the file-- if so, do it very carefully. Save the file as whitebox.py. Click the Load button to run the program. 2. Write a program that loads the image at http://www.cs.usfca.edu/~schong/SummerEnrichmentCamp/NumberPlate.j pg, then draws a personalized number plate. Tips: a. Load an image with a Python program (e.g., pic=MakePicture(filename)). b. Use the Picture Tool. When the picture appears, click on the x-y coordinate where you want your number plate to start from. c. Use the function addText. C++ Function Arguments Printing int func(int parm1, int parm2, int parm3, int parm4 = 0); Python deff func(parm1, parm2, parm3, parm4 = 0): ... Easy enough. We're just showing what's required in the header file here to note the mechanism for handling the default argument. This handles an incorrect number of arguments (no extra code needed, Python enforces this, like C++) and the default argument. The named parameters have function scope. cout << argv[0] << '\n'; print sys.argv[0] Easy enough. Python has chosen to not redefine the argv array, so the process name resides in the expected place. The only possible confusion in the Python C++ Python version is that argv lives in the "sys" module, so you need to qualify the name with sys.. File Iteration ifstream infile("in.txt"); infile = open("in.txt") const int MAX_LINE_LEN = 256; char line[MAX_LINE_LEN]; while(infile.getline(line, MAX_LINE_LEN)) { ... do something with line } for line in infile: ... do something with line Somewhat messy due to the need for a buffer to hold the line. String Character Access if(line[0] == 'H') { Reads like pseudocode. if line[0] == 'H': ... ... or if line.startswith('H'): ... Reference Passing Basic C++ stuff. The first form is natural for a C++ programmer. And you have the option of making it more English with endswith. void addItem(vector<string>& theList) def addItem(theList): theList.append('xyz') { theList.push_back("xyz"); } aList = ['abc'] addItem(aList) vector<string> aList; aList.push_back("abc"); addItem(aList); Length This would be pass-by-reference in C++. After the call to addItem, the aList will contain two strings: "abc" and "xyz". Everything is passed by reference in Python, so no special handling is required. vector<string> list; aList = [] ... ... C++ vector<string>::size_type length = list.size(); ... if(list.size() > 0) { ... string str; ... string::size_type strLength = str.size(); Python length = len(aList) ... if len(aList) > 0: ... str = '' ... strLength = len(str) Python, much like C++, uses the We're showing the use of the length same mechanism to find the length in different contexts (assigning to a of various data types, the built-in local variable, using in a function len. comparison). WARNINGS! Ooops. Here is an example of what Python calls a "syntax error". Python sees that we made a typo, and warns us to take a much closer look at our program. The designers of Python feel that having the system point out the error is better than trying to guess at what the programmer meant. It's the idea of explicitness versus implicitness. There are certain rules that Python follows that measure what looks good and what looks suspicious. As we speak the language, we'll get a feel for these rules. And if you're feeling suspicious, yes, this is a bit like grammar. *grin* Python is often perceptive enough to direct us toward the problem, and in this case, it's telling us that we forgot to put something at the end of this line. In this case, we need to add an additional quotation mark. When something goes wrong, Python responds by giving you a rude message that might look something like this: Traceback (innermost last): File "<stdin>", line 1, in ? File "<stdin>", line 1, in f TypeError: illegal argument type for built-in operation You can usually ignore everything except the last line, although the earlier lines may – if you look at them closely – give some hints about where the trouble happened. This sheet is a brief guide to some of the commoner things you might see on that last line, what they mean and what you might have done to provoke them. Error messages Attribute Errors, Key Errors, Index Errors These have messages starting “AttributeError:”, “KeyError:” or “IndexError:”. They all mean something rather similar: you were trying to get at a part of an object (one element of a list, for instance), but you asked for a nonexistent part of the object. So, if x is the list [1,2,3] and you ask for x[100] you’ll get an IndexError. Name Errors These all have messages starting “NameError:”. They mean “I’ve never heard of this thing”. The “thing” Python’s never heard of is what comes after “NameError:”. This might mean that you mistyped something: primt x instead of print x, say. It might also mean that you used a variable (i.e., a name) before it was defined. Or that you used a function before it was defed. One way this can sometimes happen is if you forget the quotation marks around a string. Syntax Errors These all have messages starting “SyntaxError:”. What they have in common is that you said something Python couldn’t even begin to make sense of. If someone says “I apple eat like the to” then that’s a syntax error! SyntaxError: invalid syntax This can mean lots of things. Here are some examples of things that provoke it. +++ 1z6 for while if: def 1(x): f([) if 1==2 if x=y: Add what to what? Is it a number? Is it a variable? Is it a mistake? After for there ought to be some more stuff if isn’t a thing that can be true or false! 1 is a number. You can’t use it as a name for a function The [ starts a list, but you never finished it You missed out the ‘‘:’’ at the end of the line That should say ==, not = One way in which you can get slightly surprising syntax errors is if you mess up the indentation (spaces at starts of lines), so if you can’t find anything else wrong it’s worth checking that the indentation is right. SyntaxError: invalid token This usually means that you messed up when typing a string. Maybe you missed off the final quotation mark, or tried to put apostrophes into a string surrounded by single quotes, or something like that. Type Errors These all have messages starting “TypeError:”. What they have in common is that Python was expecting one kind of object (a number, maybe) and you gave it another (a string, or a list, perhaps). A lot of these things can happen in non-obvious ways. For instance, if you hand something that isn’t a number to one of the graphics functions – move(), draw() etc – then you are likely to get a TypeError. TypeError: illegal argument type for built-in operation Means: You asked Python to do a “built-in operation” (i.e., something like +) on the wrong sort of object. For instance, you might have asked it to add a number to a string. TypeError: len() of unsized object You asked for the length of something that doesn’t have a length. len() makes sense for strings, lists and tuples (you don’t need to know what a “tuple” is), and not much else. TypeError: not enough arguments; expected 1, got 0 You tried to use a function, but the function was defined with more arguments than you gave it. You probably forgot one! TypeError: number coercion failed You tried to do something using numbers, but one of the things involved wasn’t a number. You can get this by doing 4+’ouch’. TypeError: too many arguments; expected 1, got 3 You tried to use a function, but the function was defined with fewer arguments than you gave it. TypeError: unsubscriptable object You tried to do something like a[3] where a was the wrong kind of thing. This can easily happen if you use a function that expects a string and give it something else instead. JES First, here are some general utility functions provided by JES: setMediaFolder() Prompt the user to choose a folder that will be used as the default location for files pickAFile() Prompt the user to choose a file; returns the full filename as a string printNow(s) Print the string s in the interactive console (works from a script) pause(sec) Pause script execution for sec seconds (defaults to 0.1) Pictures A picture is a rectangular collection of pixels (dots), each of which has an associated color. Here are the related functions: makePicture(file) Return a picture loaded from a GIF, JPEG, or PNG file makeEmptyPicture(w, h) Return a blank picture (all pixels black) with the given width and height writePictureTo(pic, file) Save pic in JPEG format to the given file name openPictureTool(pic) Open the picture exploration window for pic show(pic) Display the picture pic on the screen repaint(pic) Refresh the picture pic on the screen after pixels have changed getPixels(pic) Return a list of all the pixels (all the rows concatenated together) getPixel(pic, x, y) Return the pixel from row x, column y (upper-left is at 1, 1) Return the number of columns or rows in pic Picture objects also have a number of associated methods (a method is basically an alternate way to write a function so that it is clear that it applies to a particular object; the object is written in front of the method name instead of as an argument: x.f(y) instead of f(x, y)--the advantage is that different kinds of objects can respond to the same method name by running different code, since the method definition is looked up relative to the object): getWidth(pic), getHeight(pic) pic.clear(c) Clear all the pixels to the color c (defaults to black) pic.copy() Return a new picture which is a copy of pic pic.setTitle(s) Set the title for pic's window to the string s pic.addLine(c, x1, y1, x2, y2) Draw a line with color c from (x1,y1) to (x2,y2) pic.addRect(c, x, y, w, h) Draw a rectangle with color c, corner at (x,y), and size w by h pic.addRectFilled(c, x, y, w, h) Same, but fill with color c pic.addOval(c, x, y, w, h) Draw an oval inside the given rectangle pic.addOvalFilled(c, x, y, w, h) Fill the oval pic.addArc(c, x, y, w, h, s, a) Draw part of an oval, starting at angle s (in degrees; 0o is the xaxis, increasing counterclockwise) and spanning angle a pic.addArcFilled(c,x,y,w,h,s,a) Fill in the wedge defined by the arc pic.addText(c, x, y, s) Write the string s with color c and lower-left corner at (x,y) There is also a method pic.addTextWithStyle(c, x, y, s, style) which has an extra argument describing the font. You can create a style object with the function makeStyle(font, emphasis, size), where font can be sansSerif, serif, or mono, emphasis can be plain, bold, italic, or bold+italic, and size is the point size (roughly the height of the characters). The default is makeStyle(sansSerif, plain, 15). If you have a list of pictures, say frames, you can create a QuickTime movie file with the function makeMovieFromPictures(frames, file). The file name (file) should end in .mov. There is an optional third argument to specify the number of frames per second; it defaults to 30. If you have QuickTime for Java installed, you can view the movie with openMovie(file). Pixels A pixel object contains a color, and also remembers where it came from (which picture, and what coordinates). It recognizes the following functions (each can also be called as a method: p.setRed(r) instead of setRed(p, r), for example): setRed(p, r), setGreen(p, g), setBlue(p, b) Change the given color component of p getRed(p), getGreen(p), getBlue(p) Return the given color component of p setColor(p, c), getColor(p) Change or return the color of p getX(p), getY(p) Return the coordinates of p Colors A color object represents a combination of red, green, and blue components, plus an alpha component determining transparency. Each of these four components takes on values from 0 to 255; higher values correspond to brighter colors and greater opacity. Here are the relevant functions: pickAColor() Prompt the user to choose a color; returns the color chosen Color(r, g, b, alpha) Create a new color object with the given components (alpha defaults to 255 if not given) c.r, c.g, c.b, c.alpha Return the value of a color component distance(c1, c2) Compute the (Euclidean) distance between colors c1 and c2 increaseBrightness(c, f) Return a new color whose brightness level is scaled up by f, from no change if f is 0.0, up to full brightness (white) if f is 1.0; f defaults to 0.5 decreaseBrightness(c, f) Return a new color whose brightness level is scaled down by f, from no change if f is 0.0, down to no brightness (black) if f is 1.0; f defaults to 0.5 increaseSaturation(c, f) Similar, for saturation level (the difference between the maximum and minimum color components) decreaseSaturation(c, f) Ditto increaseRed(c, f) Similar, for the red component decreaseRed(c, f) Guess ... Similar functions for Green, Blue, Yellow, Cyan, and Magenta rotateHue(c, a) Return a new color whose hue is shifted by angle a, in degrees ( 120o from red is green, 240o is blue, etc.); a defaults to 60o A number of colors are predefined: black, white, gray, darkGray, lightGray, red, green, blue, yellow, cyan, magenta, orange, and pink. Sound A sound is treated as a collection of sample values, much as a picture is a collection of pixels. Here are the functions on sounds: Return a sound loaded from a WAV, makeSound(file) AU, or AIFF file makeEmptySound(sec) Return a blank sound (all samples 0) of length sec seconds writeSoundTo(s, file) Save s in the given file; uses the same format as when loaded (makeEmptySound creates a sound in WAV format) openSoundTool(s) Open the sound exploration window for s play(s) Play sound s in the background playAtRate(s, r) Play s at speed r--1.0 is normal, 2.0 is twice as fast, etc. playInRange(s, b, e) Play s from sample number b to e playAtRateInRange(s, r, b, e) Play s from b to e at speed r blockingPlay(s) Play s and wait for it to finish (also, blockingPlayInRange and blockingPlayAtRateInRange) getSamples(s) Return the collection of samples in s (not quite a list, but indexable and usable in a for loop) getLength(s) Return the number of samples in s getSamplingRate(s) Return the number of samples per second in s There are also some useful methods on sound and sample objects: s.getSampleValue(i) Return the (left channel, if stereo) value of the ith sample in s (the first sample is at index 1) s.getLeftSampleValue(i) Return the left channel value at index i s.getRightSampleValue(i) Return the right channel value at index i s.setSampleValue(i, v) Set the (left) value of sample i to v; the range of sample values is 32,768 to +32,767 s.setLeftSampleValue(i, v) Same s.setRightSampleValue(i, v) Guess what? s.getSampleObjectAt(i) Extracts the sample object at index i, without creating a whole collection of samples samp.value Return the value of sample samp; change the value by assigning to this samp.left Return or change the left channel value of samp samp.right Return or change the right channel value of samp Finally, JES provides a simple function to play a MIDI note: playNote(n, dur, vol) plays note number n (middle C is 60, C-sharp is 61, etc.; the range is 0-127) for dur milliseconds at volume vol (maximum is 127). The function pauses execution until the note is finished. For much more complete support of MIDI music, see the next section. WARNINGS This error occurred because both the text editor and interactive interpreter are using the same picture object name “pic”. To avoid this, use a different object name, for example “pic2”.