CS115 Final Exam

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

•allow you to execute code multiple times. with a variable that is different each time -Two kinds: definite and indefinite

loops

What are the different sequences of for loops?

- lists - strings - numeric ranges

How can you draw polygons?

-Any number of sides, at any angle -How could we specify all that? -List the vertices (corners) tri = Polygon(Point(100, 100), Point (300, 100), Point (200, 250)) -tri would be a triangle (has 3 corners) •You can have any number of points, 1 or more. -Draws a line from the first point to the second -Then from the second to the third -Finally, from the last point back to the first -Order matters! If you have more than 3 points, anyway.

How can you avoid aliasing?

-Call the constructor every time you want to make a new object. eye2 = Circle(Point(200, 250), 50) print(id(eye2)) → 4147339756 -Or clone the object (for graphics shapes only) eye2 = eye.clone() print(id(eye2)) → 4148132104 -alias-fixed.py •Aliasing isn't a problem for integers, strings, etc. -These objects are immutable. •The number 42 never changes. •Immutable object can still be aliased, but since they can't be modified, the aliasing doesn't cause problems. -More on this in chapter 8 about lists.

What if we wrote range(1, 1)?

-It gives an empty sequence: stops before getting to 1 -The loop won't run at all! Loops can run for 0 iterations! -Similarly, range(5, 1) is an empty sequence for i in range(5, 1): print(i) •The body never executes (is dead code)

What does structured programming guarantee with a while loop?

-One entrance: always starts by checking the condition at the top -One exit: ends only when the condition is False -Only checks the condition again after running the entire body •Does NOT jump out of the body statements

How do you create a graphics window?

-The class for windows is called GraphWin •Constructor: graphics.GraphWin (title, width, height) •Or just graphics.GraphWin() (default values: "Graphics Window", 200 x 200) -Call the constructor, and save the new object in a variable (an assignment statement) We'll need it later. window = graphics.GraphWin("115 Program", 600, 400)

Why did we have to write it as Point(100, 100)?

-Unlike Python's built-in types (3, 4.5, 'abc'), most classes don't have literals - symbols that stand for an object. -Instead, you call a constructor

How can you know where the user clicked?

-We don't even need a new method to do that! -getMouse actually returns a Point object clickpos = win.getMouse() -You can use this variable as a Point, anywhere a Point would work, like clickpos.draw(win) Or Line(clickpos, Point(0,0)) -You can get the x and y coordinates of the point they clicked on click_x = clickpos.getX() click_y = clickpos.getY() •When we called getMouse before, for a pause, we were just throwing this Point object away. -To wait for a click and get its location: pt = win.getMouse() To just wait for a click: win.getMouse()

What occurs loops to break?

-unconditional flag -break

What is the semantics for a while loop?

1.Check the loop condition 2.If False, end the loop 3.If True, run the body and repeat steps 1-3 -If the condition is False to begin with, the body never runs!

How could you summarize graphical input?

1.Display a prompt for the user (using Text) 2.Create an Entry object with settings as desired 3.Draw the Entry object 4.win.getMouse() # to give user time to type 5.user_input = Entryobject.getText() And cast user_input as needed for type desired

How do we use files in programming?

As in other programs (word processors, IDEs, etc.) you must open a file before you can use it in your program. •Create a file object in your program that represents the file on disk •You can read from or write to the object depending on the mode "r","w","a" •Input or output comes from the file instead of from the user •Syntax: fileobj = open(filename, "r") # r for reading (input) fileobj = open(filename) # default is reading fileobj = open(filename, "w") # w for writing •fileobj is a variable that will hold the file object •filename is a string that names the file (can be a constant or a variable)

How can we catch exceptions?

By default, exceptions cause the program to crash. •Because that's better than continuing to run and doing the wrong thing •But sometimes you might have a better idea for how to handle it •For example, type-casting a string to int •if the string wasn't numeric, Python can't give you a number •You asked Python to do something and it can't •Exception! •But maybe you know what to do in this particular case •If it was user input, repeat the input and ask again •If it came from a file, maybe ignore that line •Maybe the program can use a default value •Sometimes you can prevent the exception by checking before you do the action, like comparing a denominator to zero before dividing by it But there are errors that you cannot check for without trying it

Describe the graphics library.

• developed by John Zelle -Not part of Python; a third-party library -can also use turtle, based on a moving cursor, and Tkinter, which does graphical user interfaces based around widgets like checkboxes, labels, text fields

How do numeric ranges work?

In Python, you create numeric ranges with the range function. It always creates integers. There are three ways to call range: •range(3): counts from 0 up to 2 -Computer scientists usually count from zero, not one -Goes up to but not including the final number (just like randrange!) for i in range(3): print(i, "squared is", i**2) prints: 0 squared is 0 1 squared is 1 2 squared is 2 -Note the loop ran 3 times (for i = 0, 1, and 2)

Explain IOError

If we are trying to read from a file, what can go wrong? •Maybe the file isn't there •Or it's there but you don't have permissions to access it •Or you do but then your hard drive crashes •In these situations, opening a file raises an IOError exception •Renamed to OSError in Python 3.4 •You can catch the exception just like any other •But there's no point in trying to open again with the same filename •A common fix is to ask the user for another filename

run until some condition is satisfied

Indefinite loops

What is the try/except syntax?

To catch an exception, you use a try / except statement: try: body that might raise an exception except ExceptionClass: handle the exception code that comes after •ExceptionClass is one of that list: ValueError, IOError, etc.

How do you draw a graphics object?

Let's make a line going from the upper left to lower right of the graphics window. To do that, we use the Line class. -Constructor: graphics.Line(point1, point2) -Constructor: graphics.Point(x, y) (x and y are floats or ints) •By default, (0, 0) is the upper left corner of graphics window •Upside-down compared to Cartesian plane in math! •You can use a constructor as an argument, so from graphics import Line, Point diagonal = Line(Point(0,0), Point(600, 400)) •Making the line does not actually draw it! -One more step: tell it to draw itself in the window diagonal.draw(window)

How can you perform input validatation?

Users input all kinds of values which are not valid for the program. The program should protect itself from this "bad data" by refusing it and asking for another value. This logic is similar to sentinel value logic but as a slight twist: -You repeat the loop if the input is bad -So the "sentinel" is any good input -What goes in the body of the loop? •An error message to the user •Get the next input -Keep asking until we get what we want -Now a good value makes us leave the loop -While the number is not positive... -Inside the loop, print an error message Process the valid input after the loop is over.

How can we read a whole file at once?

Python also gives us two methods that read in the whole file at once •That's much easier if we need to process the contents out of order •Or if we need to process each line several times •But it doesn't work if the file is larger than RAM. •readlines gives us the whole file as a list of strings (note the s on the end of the name) line_list = infile.readlines() infile.close() #close, the file is exhausted for line in line_list: •The lines still contain one newline each, at the end •After the readlines, there is nothing left to read so might as well close •Technically, it gives you the rest of the file, from the file pointer to the end •Maybe you read in the first line with readline, then called readlines. •read gives us the whole (rest of the) file as a single string •newlines and all content = infile.read() infile.close() •As with readlines, you might as well close it immediately •What to do with the string? •You can use split line_list = content.split("\n") •Unlike other methods, this gives you a list of strings without newlines Because split removes the delimiter

What is a line in a text file?

So if a text file is a sequence of characters, what's a line? •A sequence of characters delimited by the newline character •Newline ('\n') is the line delimiter (so it cannot appear in the middle of a line!) •(Technically a little more complicated on Windows, but Python hides that) •What would two newlines in a row mean? •There's an empty line between them •So this file: Hello, world How's it going? Would look like: Hello, world\n\nHow's it going?\n

How can we deal with large amounts of data?

Some programs need a lot of data. How do you handle it? •Hard code it into the source? •That's hard to change if you're not a programmer •Ask the user to type it in each time the program runs? •If it's more than a few pieces, your users will refuse! Or make typos! •Store your data in an external file! Can be as big as your device can hold! •When you type your program, you save it in a file. Data can be saved too!

How does the previous-current loop work?

Sometimes a loop needs two items from a sequence at one time •Drawing lines (needs 2 points at once), computing distances •Or to see if user input has changed •We can save the "previous" item in a variable 1.Initialize prev 2.Loop: 1.curr = the new item 2.Do something with prev and Curr 3.prev = curr •In the first iteration, prev is the initial value •On following iterations, prev is the value from the preceding iteration

How can we extract individual characters from a string?

The characters in a string are numbered from 0 to length -1 HAL 9000 (length = 8) 01234567 •Each number is called a position or index or subscript of the character •You can use square brackets to get the character at a given position first = name[0] # this is "H" •This is called subscripting or indexing •The position must be smaller than the length print(name[8]) # ERROR: string index out of range

How do you import the graphics library?

import graphics -Or: from graphics import *

Each run of the body

iteration

How can we convert characters to numeric codes?

The last time we heard about ASCII and Unicode •They assign a numeric code to each possible character •Python has functions to covert between characters and the code •ord takes a character and returns its numeric code code = ord("A") •Argument is a single character as a string, returns an integer •chr takes a numeric code and returns the corresponding character char = chr(65) •Argument is an integer, returns a one-character string Codes below 32 are control characters (newline, tab, ...) •We can use these to convert letters into a useful list subscript •We want to put the counter for "A" at position 0, the counter for "B" at position 1, etc. •So the subscript can be ord(char) - ord("A") gives a number from 0 to 25 •To convert back: chr(i + ord("A")) if i is an integer from 0 to 25

How can you find the length of a string?

The length of a string is the number of characters in it. •Spaces count! •So do newlines and other escaped characters •To get the length of a string, use the len function: name = "HAL 9000" numchars = len(name) # that's 8 characters •Argument type: string •Return type: integer •What's len("")? •zero We'll see later that len works with lists too.

What does looping over the lines in a file look like?

The simplest way to use an input file once you have successfully opened it is to loop over the lines in the file •A file object can be used as a sequence of lines for a for loop: for line in myfile: •Each line is a string delimited by a newline character. •myfile is a file object, NOT a filename! •Each line ends with the newline character •You may need to use strip, rstrip, or split •When you're finished with a file, make sure to close the file! •Frees up resources associated with the file •If you don't, the file will take up memory until the program exits •... if not longer than that!

How does slicing work?

The square-bracket notation also lets us extract multiple characters. HAL 9000 (length = 8) 01234567 •For example, "the first 3 characters" or "characters 2 through 4" or "the fifth character" (a substring can be only one character long, or can be empty too!) •Subscript using a slice ("slicing") •Syntax: start position, a colon ":", and stop position (one-past-the-end) •Similar semantics to range (start, stop) •The first three characters: name[0:3] # is "HAL" •"Start at character 0 and stop before character 3" •Characters two through four: name[2:5] # is "L 9" •You can leave out either the start or the stop position (or both!) •Leaving out the start position means "start at the 0th character" first = name[:3] # "HAL" •Leaving out the stopping position means "go all the way to the end of the string" last = name[4:] # "9000" •Leaving out both means "the whole string" (seems silly here) copy = name[:] # "HAL 9000" •Slicing does NOT change the original string, it makes (returns) a new one!

How can we write to an output file?

There are two ways to write to an output file: •You can use the same print function that we've been using •Just give an extra argument at the end, file = fileobj print("Hello,", name, file = outfile) • You can use all the functionality of print •Printing strings, numbers, lists, etc. •sep = " ", end = " " •You can also write a string with the write method •Takes one string argument (nothing else!) outfile.write("Hello, world!\n") •Does not automatically add a newline character!

•Temporary (life of the program) •Smaller (must fit in memory) •Faster to access •Random or sequential access

lists

What are some variations you can do with range?

We can also tell range to start at a different number: •Syntax: range(start, stop) -Produces a sequence of integers from start to stop -Includes the start number (inclusive), does NOT include the stop number (exclusive) for i in range(3, 6): print(i) prints: 3 4 5 -Runs for (stop - start) iterations The last variation on range: We can count by steps bigger than 1, only considering every nth number: •Syntax: range(start, stop, step) -Instead of adding 1 in each iteration, adds step. -The first number is still start -The next number is start + step, then start + 2*step, ... for i in range(10, 25, 5): print(i) -Prints: 10 15 20 -Does not include 25, the stop number is still exclusive. •What about range(10, 2) ? # common error! -Since there are only two arguments, it means start at 10 and stop at 2, NOT start at 0, stop at 10 and step 2!

What do while loops with a counter look like?

While loops can be combined with a counter to simulate a for loop over a range •Initialize the counter to the starting value •While the counter is less than the stop value: -Do stuff Add the step value to the counter variable i = 0 while i < 4: print(i, "squared is", i**2) i += 1 -Why would you ever write it this way? •Maybe the step size changes •Maybe there are multiple stopping conditions, not just the counter reaching the stop value

How can you count backwards using range?

You can count down by providing a negative step. for i in range(3, 0, -1): print("Counting down:", i) print("Lift off!") •Prints: Counting down: 3 Counting down: 2 Counting down: 1 Lift off! •The stop number is still exclusive (not included)! •range(1, 5, -1) is an empty sequence

What does a loop with sentinel logic look like?

You get the input in two places -Just before the loop starts -as the last step of the loop body 1.Get the first input 2.while the input is not a sentinel: 2.1 Do something with the input 2.2 Get the next input num = int(input("Enter a number, 0 to exit: ")) while num != 0: print("Its reciprocal is", 1 / num) num = int(input("Enter a number, 0 to exit: "))

a variable to keep track of the sum -A logical concept, used in most programming languages

accumulator

happens because the assignment operator (=) does NOT create NEW objects •You must be careful when using the assignment operator (=) with shapes. eye = Circle (Point(200, 250), 50) eye.draw(win) eye2 = eye eye2.move(100, 0) -There is really only one circle here, with two different names. •They have the same identity: -print(id(eye)) → 4147736844 -print(id(eye2)) → 4147736844 -We say that eye2 is an ______ for eye. -You can check for ___)_____ with the is operator: print(eye is eye2) → True •This is NOT the same as asking if they are equal More detail on that later with relational operators.

aliasing

•The interpreter knows in advance how many times the loop will run •That does not change once the loop starts. For i in range(5): i = 1 print(i) Even though we are changing I, the loop still runs five times! •That's kind of nice because it prevents infinite loops!

bounded/definite loops

•When you open a file in a Python program, Python and the OS set up a _______ for that file. •It's a piece of memory that holds some of the file's data before you need it •Why? Disks are much much slower than RAM •And disks are faster if you read from them in large chunks, not byte by byte. •When you call readline, etc., that gets data from the _____ •If the program asks for data that isn't in the ______ yet, the OS refills the ______ with new data from the file. -holds data our program has already read... and data it has not read yet

buffer

•a type that represents a particular kind of thing (the kind of thing that can be stored in a variable) •a template for making objects of that type -Especially a user- or library-defined type -In Python, str, float, int, etc.

class

What is included in object oriented programming?

classes, objects and methods

a function that creates an object belonging to a class -to make a new object. •A special function that returns a new object •The name of the __________ is the same as the name of the class. Uses the class template to "stamp out" a new object

constructor

know in advance now many times to run

definite loops

Another name for a run-time error in Python is an _________ •Probably from "the __________, not the rule" •Signaling a run-time error is called raising an _________ •By default, raising an ______ crashes your program, but ________ can be caught and handled. •Also called "throwing" an _________ (C++ and Java)

exception

•indicates the beginning of the unread part of the program •Starts out at the beginning of the file (except in append mode) •When you do a sequential read, like readline: •It starts reading at the location of the _______ •When it sees the newline character, it advances the _______ to the next byte •So that every input will get a different line •Sequential access means the ______ does not skip anything and never moves backward.

file pointer

•Permanent "persistent" •Bigger (although must fit on your secondary storage device) •Slower to access •Sequential-access (as we do it in this class)

files

Sometimes we only discover inside the loop that we want to leave the loop •For example, "do you want to play again?" •The best way to control this is to use a ______ -A Boolean variable, we saw these with the if -Use the ______ as the condition of the while -Initialize the______ before the loop -When we discover that we're done, change the ______'s value done = False while not done: play a round done = play_again()

flag

a function that belongs to an object and does something to or with the object -In OOP, methods are how the program interacts with objects •Syntax: obj.method(arguments) -obj is an object (usually a variable) -method is the name of the method •Semantics: calls the function named "method" in obj's class, sending it obj as the object to work on •Methods can return values just like ordinary functions x = point.getX() •The draw method does not return anything (like the function print) It's a stand-alone statement. diagonal.draw(win)

methods

•a thing that can be stored in a variable •a particular thing of that type. -So int is a class, and 42 is an _______ of that class. -str is a class and "abracadabra" is an ______. -Point is a class, Point(100, 100) is an ______

object

How can we close files in our program?

outfile.close() •Frees resources (like the file buffer!) •Closing files is even more important for output files •The buffer isn't written to the disk until either it's full or the file is closed. •Until you close the file, the most recent buffer-full is not 'committed' to disk •And what if your program crashes without closing? •Closing allows the file to be marked as "closed" = "not busy" by the OS •Ever had a file that had been created during an application that crashed? •Lots of times you cannot do anything to the file because Windows says "it's busy"

•reading or writing without regard to order •"Go to byte 7563 and put a 7 there" •Like lists: we can use mylist[5] without having to go through indexes 0 through 4 first Also called direct access •access does not work that well with text files •Bytes don't always match up with characters •And they definitely don't match up with lines. At what byte number does line 10 start? •You'd have to go through the lines sequentially and count

random access

•repeating some code until you see a special value (or values) •Get input both before the loop and at the bottom of the body of the loop •We want to keep getting more data until we see a special value -Read from a file until you see a blank line -Ask for a number until the user enters zero. -Get commands from the user until they type "quit" -Read and log temperatures until one is out of range -This special value (or values) is called a _________ •Just a fancy word for "guard" •Sounds like a job for a while loop! -But a while loop checks the condition at the start Be we can't check until we have the first input data!

sentinel logic

•reading or writing the file in order starting from the beginning and going to the end •Similar to how a for loop works on a list or string •Read the first line, then the second line, etc. No skipping, no backing up! -Text files usually use

sequential access

What kind of access do binary files use?

sequential or random

How can you find an average of a list?

temperatures = [67.0, 69.2, 55.3, 71.2, 65.4] •We can get the number of measurements by a function called len: len(temperatures) •For the sum, we need some kind of a loop for temp in temperatures: •We need to add another number in each iteration •We need an accumulator, a variable to keep track of the sum

-Run through code line-by-line, simulating its behavior -Keep track of the variables (RAM) and output -Pretend you are the interpreter and you are NOT SMART! -a debugging technique

tracing code

•need some way to make a loop that can run an unlimited number of times •Most loops should stop eventually - we just can't say when •"Repeat if necessary" - we just need to describe "necessary"

unbounded/indefinite

What is the syntax for a while loop?

while condition: body •The condition is a boolean expression, just like an if. •The body is an indented block of code

How do you keep the graphics window open by waiting for a mouse click?

win.getMouse() -Be safe by always calling win.close()at the end!

What are common errors with flags?

•Accidentally using or instead of and -The loop will run too long -If the condition is a tautology, it's an infinite loop •Accidentally using and instead of or -The loop won't run long enough -If the condition is a contradiction, doesn't run at all •Not initializing the flag -Causes a run-time error •Always setting the flag, every iteration -Let's see an example of that

How can you get user input from an Entry object?

•After you've drawn the Entry object, you MUST give the user time to actually type in the box •Use win.getMouse() •Then you use the getText() method to actually get what the user typed user_input = input_box.getText() •Returns a string just like the input function -Use a typecast if you need a number type •temperature = float(in_box.getText())

How can we draw ovals?

•An oval is a stretched-out "squashed" circle. -How would we specify an oval? •Several possibilities: center and two radii, two foci, ... -The graphics library uses a bounding box. •Class Oval •The constructor takes two Point arguments -The corners of a rectangle (the bounding box) -The oval will fit in the box as tightly as possible. -Does not actually draw the bounding box! ov = Oval (Point(100, 200), Point(400, 300)) ov.draw(win)

When should we close a file?

•As soon as you know you don't have to read / write it again •Immediately after your loop •With read or readlines, immediately after that statement

How can we split the string we get from read?

•Be careful! •If the last line in the file ends in a newline character, there will be an extra empty string in the list of lines content = 'Hello\nWorld\n' line_list = content.split('\n') gives line_list = ['Hello','World',''] •Not just in Python: some OSes and programs treat that as a blank line

What can accumulators be used for besides sums?

•Choose the initial value carefully so it doesn't change the result •Factorial: 1, 2 = (1 x 2), 6 = (1 x 2 x 3), ... -Inside the loop we will multiply the accumulator -If we started the accumulator at zero, we'd never get anything but zero! -The multiplicative identity is 1, use that. factorial = 1 for I in range (1, max + 1): factorial *= i -Counting: how many times does something happen? •Just like sum: initialize with zero. •Instead of adding I, just add 1. numoff = 0 for i in range(1, 100, 2) numodd += 1 •We call an accumulator like this a counter. •Reversing a string -Our accumulator will be a string -We'll loop over the characters of the input string -Concatenate each new character to the beginning of the accumulator string •What is the identity element for concatenation? •(That is, what can you concatenate with, without changing the original string?) The empty string instr = input("enter a string: ") reversed = "" for char in instr: reversed = char + reversed print(instr,"backwards is", reversed)

What is the semantics of the for loop?

•Execute the body once for each item in the sequence -Each time, the variable var will have the value of that item

How can we output files in our program?

•First, open the file for writing: outfile = open("out.txt", "w") # w for write mode •If the file does not already exist, it creates it •If the file already exists, truncates it to zero bytes!! •Cuts everything out of the file to start over •The old data in the file is lost forever! •Opening for writing is both creative and destructive. •You can also open a file for appending: logfile = open("audit.log", "a") # a for append •Adds to the end of an existing file - no truncation, no data lost •If the file doesn't exist, will still create it. •Which to use? Do you want to add to the file or overwrite it?

What are the classes in the graphics library?

•GraphWin - a window for drawing graphics •Point - an (x, y) coordinate •Line - a line segment with two endpoints •Circle - a circle with a center point and radius •Rectangle - a rectangle (given by two opposite corners) •Oval - an oval that fits inside a "bounding box" •Polygon - defined by connecting a sequence of Points. •Text - text with a given string value, position, size, etc. •Entry - box for user to enter input, has position, size, etc. •Image - object that holds a GIF file, has position, size, etc. and more!

What are some hints for catching exceptions?

•Have a plan! If you don't know how to fix the error, don't catch it •It's better to crash than to continue with bad data •Keep the try block as small as possible •It should contain the line that might raise the exception •And subsequent lines that depend on its success •Don't duplicate code in the try and except blocks •That code belongs after the try/except, so it happens either way •Don't wrap the whole main in a try! •The program probably won't know which error happened or how to fix it •If you can use it, if is usually simpler If you know in advance what situations will cause an error

How can we read one line at a time in a file?

•Here's one way to read a line at a time for line in file: •This technique is very useful but a little inflexible: •It only lets us use one line per iteration •But what if our file looked like this? Student 1 Score 1 ... •The readline method lets you control reading more precisely. line = infile.readline() •This reads a single line from the file •Returns a string, including the newline at the end •The next time you do input, you get the next line •Even if you use a different input technique next time •readfile-readline.py

What are the semantics of try/except code?

•If the code in the body raises the specified exception: •The body stops executing immediately (like a "goto") •Doesn't even finish the current line! •Then Python runs the except block (instead of crashing) •After the body (called the handler) is finished, go on to the code that follows •This applies even if the exception is raised inside a function call •Exceptions go up the call stack looking for a handler •If no handler is found, then the interpreter does its usual error message •You can have several except blocks for different exceptions for the same try block. •trysqrt.py •Or one block for more than one exception: except (ValueError, IndexError):

How are objects different than shapes?

•If you use the Rectangle constructor, you generate an object with properties like corner points, colors, thickness of lines, a name, etc. •If you want to "fill in" the object with a color, there is a method setFill that does it easily •IF you had drawn the rectangle by using four separate Line objects, the shape on the screen will look just like the Rectangle object •BUT you could not use setFill because that assumes the object has an "interior" - Lines don't have that •If you wanted to move the Rectangle object, there is a nice method called move - moves it as one thing. •But if you had used 4 Lines, you would have to move each one separately.

How can you change the coordinate system graphics use?

•In the default coordinate system for the library -(0,0) is at the upper left corner of the window -(width-1, height-1) is in the lower right corner -Coordinates are measured in pixels (integers) •Why would we want to change that? -To use different window sizes without changing the code -To put your origin at the bottom of the screen -Maybe it just makes the math easier. •win.setCoords (xll, yll, xur, yur) -Give the x and y coordinates of •The lower left corner: xll, yll (that's NOT x11 and y11) •The upper right corner: xur, yur •All drawing after this statement will be in this coordinate system. Example: win.setCoords (0, 0, 1, 1) -Now Point(0, 1) is in the upper left corner of the window -Point (0.5, 0.5) is in the center of the window -Point (0,0) is the lower left corner of the window -Note that coordinates can be floats, not just integers. -Note that y's are "right side up" now, they increase as you move UP the screen. •Handy methods for a GraphWin, getWidth() and getHeight()

What does a while loop with multiple exits look like?

•It still asks for more numbers after an odd one was seen. Let's fix that. •Stop the loop if anyodd is True. -It can never become False again. •But we still want to stop the loop if the input is zero -Stop the loop if anyodd is True or the input is 0. -Continue the loop if anyodd is False and the input is not zero. •deMorgan's Law: "not (A or B)" = "(not A) and (not B)" while not anyodd and num != 0:

What are the general patterns of accumulators?

•Make an accumulator variable to hold the "total" -Like the display on a calculator •Before the loop starts, initialize the accumulator to a known value -Like clearing out the calculator first -If we are calculating a sum, start at 0 total = 0 •0 is the identity for addition: adding 0 to a number doesn't change it •Inside the loop, use assignment to update the accumulator for temp in temperatures: total = total + temp -Or use augmented assignment: total += temp •What if we don't initialize total first? -NameError: name 'total' is not defined

What can we do with strings?

•Read them from the user: mystr = input("Name? ") •Print them to the screen: print(mystr) •Convert (type-cast) them into ints or floats: num = int(userin) •Concatenate them with +: name = first + " " + last •Compare with other strings: if "A" <= name <= "K": •Check whether they are all digits: if mystr.isdigit():

Why use flags instead of sentinel logic?

•Sentinel logic would ask before the loop starts •but we want to play a round before we ask!

How can you interact with color of objects?

•Shapes have two different colors associated with them: the fill and the outline -The fill color is used for inside the shape box.setFill("blue") •You specify the color name as a string •Points and Lines don't have an "inside" •This is why Rectangle and Polygon are better than just a bunch of Lines - they have "insides"! -The outline color is used for the border line1.setOutline("red") •For a Line or a Point, that's the entire shape -The window as a whole (GraphWin) has a background color. win.setBackground("yellow")

How does exception work?

•Suppose we want to keep asking for a float until we get one •So this will be an input validation loop (sentinel logic) •We'll use a flag to mark whether we got a good input while not ok: •How do we get the input and convert it to a number? number = float(input("please enter a number: ")) •float(...) raises a ValueError on a non-numeric input •So put that line inside a try block •If we catch the exception, set the ok flag to False •If there was NOT an exception, set the flag to True. Where? •In the try body after the input •Finally put that whole try/except in two places: •Before the loop, and as the last step of the loop •When the loop finishes, we know we have a valid number Another way to do loops involving an exception •Use a flag like we did before, initialized to False •Set the flag to True in the try block as before •Put the input try/except inside the loop only •Because the flag is False, the loop will run at least once •Put the error message in the except •So it only happens if there WAS an exception

How can you output numeric values in graphics?

•Suppose you had a variable like width which has an integer value and you want to put it on the graphics window. myresult = Text(Point(150, 100), width)#bad •But this is NOT good. It is only a number, no label! •It is easier to make ONE string which is used by ONE Text object. myresult = Text(Point(150, 100), "the width is " + str(width)) # better! •Typecast the numeric variable to a string then concatenate it with the label (including spaces as needed). •This makes one string which is then displayed with the Text object.

What are the three types of errors?

•Syntax error (code will not run) •Run-time error (detected when code runs, crashes) Semantic error (not detected by interpreter, program gives incorrect output or behavior)

How can you draw circles?

•The Circle class represents a circle (surprise!) •What information is needed to draw a circle? -The Center: that's a Point. -The Radius: that's a number (distance from center to edge). eye = Circle (Point(250, 250), 200) -its center is at (250, 250) -Its radius is 200, top is at (y = 50), bottom at (y = 450) •As with Line, we have to draw the circle to display it: eye.draw(win)

What should we name our files?

•The default location for a data file is the current directory, i.e., the file your py file is saved in •You can specify an absolute path if you want open("C:\\Users\\me\\input.txt")

How can we draw images?

•The graphics library can draw images -It supports GIF format files, not JPEG! -You give the position where you want the center of the image, and a filename pic = Image(Point(250, 250), "pic.gif") •The image will be centered at (250, 250) •The GIF file should be in the same folder location as your py file. •Whoever runs your program needs the image file too. •As usual, use pic.draw(win) to display the image.

Why do we use files to hold data?

•They're easier to edit than a source file •Files persist across runs of your program •And across reboots of your operating system •They can hold LARGE amounts of data (more than will fit in RAM!) •You can use the same data file as input for different programs •You can use the output of one program as input to another

What are the different kinds of exceptions?

•TypeError: argument has the wrong type •ValueError: argument has a good type but a bad value •IndexError: accessing a sequence (a string, a list) out of range •ZeroDivisionError: just what it says •IOError: file problem, such as "file not found" •RuntimeError: "none of the above"

How can you interact with users in graphics?

•We can make a graphical text-entry box input_box = Entry(center, width) -center is a Point object (where the box will be centered) -width is a number of characters (not pixels) •This controls the size of the input box, not the size of the input. •The user can enter more characters (it scrolls) •You can set the initial text, font size, color... input_box.setText("default") •Very useful to give default value that user can get by just clicking on the screen without any typing input_box.setSize(24) # 24 point input_box.setTextColor("green") •After you have the object the way you want, don't forget to draw it! input_box.draw(win)

How can you draw rectangles?

•We could draw a rectangle already, using four Lines. •But there is an easier way -which we will see also has another benefit shortly •What information do we need to draw a rectangle? -Four corners? -We really only need two opposite corners •The graphics library can figure out the other two points box = Rectangle (Point(50,100), Point(250, 350))

What are some common errors with loops?

•What happens if the condition is a tautology (always True)? -The loop never ends! -An infinite loop is usually an error •Unless you are writing an Operating System •Conversely, what if the condition is a contradiction (always False)? -The body will never run at all -Which is called dead code!

How are while loops and if statements different?

•While loops and if statements DO look similar on the surface -They both use boolean expressions on the first line of the structure -They both have indented bodies •They are NOT the same! -If you need to repeat code, use a while -If you need to test something only ONE time, use an if •If you need to test something repeatedly, you need an if statement INSIDE a loop (for or while)

How can we extract characters with negative subscripts?

•You can subscript with negative numbers, counting from the right end •name[-1] is the last, rightmost character •name[-2] is the next to last character •... •name[-len(name)] is the first, left most character •name[-i] is the same character as name[len(name) -i] •name[-9] is still out of range!

How can you draw text?

•You need the location (Point) where you want the center of the string, and a string greeting = Text(Point(250, 250), "Hello") •You can specify the font size greeting.setSize(30) # between 5 and 36 •You can also make it bold and/or italic greeting.setStyle("bold") greeting.setStyle("italic") •The library supports a few typefaces: greeting.setFace("courier") greeting.setFace("times roman")

What's going on with the diagonal.draw(window)?

•draw is a method of the Line class -A method is like a function that works on an object -"Something the object can do"

What is the syntax of the for loop?

•for var in sequence: -Followed by a block (collection of indented lines) called the body. •The body must be indented more than the "for" line! -var is an identifier (variable name) for color in ['red', 'green', 'blue']: print(color, "is a primary color.")

How can you move an object?

•obj.move(dx, dy) -Moves the shape by dx in the x direction, by dy in the y direction (can be positive or negative or zero) -The numbers are added to the original coordinates Can do this even after the shape is drawn - so animation!

How can you change the width of an object?

•obj.setWidth(pixels) -Changes the width of the shape's lines

How can you undraw an object?

•obj.undraw() -Erases the shape immediately -Anything "behind" becomes visible again Be careful not to UNdraw something that has not been DRAWN yet! Gives a Run-time error


Set pelajaran terkait

日本語総まとめN2語彙 第1週 2日目

View Set

Econ Fiscal Policy & Debt Sapling

View Set

PY 361 Chapter 6: Other Sensory Systems

View Set

Pharm 3 Final Exam- Chapter 18: Drugs Used for Seizure Disorders

View Set

This is Philosophy Chapters 1 & 2

View Set

Mastering Biology Chapter 10 and Final

View Set