Python Final Prep
The event handler function for a Button must be called handleButton.
False
When printed, a set containing strings will list the elements in alphabetical order.
False
The maximum number of sides on a Die object is 20.
False
The values of an object's instance data represent the object's identity.
False
Which of the following is NOT an arc type for a Tkinter Canvas? a)ARC b)WEDGE c)CHORD d)PIESLICE
b)WEDGE
The parameters to the create_rectangle method represent the upper left corner and lower right corner of the rectangle.
True
A widget can only generate one type of mouse event.
False
Python constants cannot be created for floating-point values
False
A color chooser is a specialized dialog box that changes the background color of a window.
False
A comprehension always produces a list.
False
item handle
Each item drawn on a Canvas has a unique item handle that identifies the item. The item handle is returned by all of the drawing methods, and can be used later to find, modify, or delete any item.
The event handler function for a mouse pressed event is called handle_mouse_press.
False A function that handles an event can be called anything you'd like.
Some problems can only be solved using recursion.
False Any recursive solution can be written as an interative solution.
The webcolors module is part of the Python Standard Library.
False Have to install the webcolors module if you plan to use it
instance data
The attributes of an object are called instance data, because each object (each instance) has its own set of instance variables; Each object has its own memory space for instance data.
A check button provides a single boolean choice.
True
event handler
a function that performs some action when an event occurs; specify how the program will respond when the user interacts with the interface. example: button being clicked with the mouse, a checkbox being toggled
conditional expression
is an expression that produces one of two possible values depending on a boolean condition. syntax: expr1 if boolean-expr else expr2
shape id
obtained when the polygon is created, then passed as an argument to the move method to shift shape
Keyboard events
occur immediately as keyboard keys are pressed and released; must bind an appropriate event string to a function that serves as an event handler. syntax ex: canvas.bind('<F7>', handle_function_key)
analogies of class to object relationship
- A class is like a cookie cutter and the objects are the cookies. - A class is like the blueprint of a house and the objects are the houses created from that blueprint. - A class is like the concept of a cat and the objects are actual cats (my cat, your cat, the neighbor's cat).
steps to setting up a basic GUI using Tkinter:
1)Import the package Tkinter is part of the Python Standard Library and does not have to be installed separately- import tkinter The Tk Themed Widgets module could be imported similarly- import tkinter.ttk 2)Create the main window Every GUI program needs at least one window for presenting the program interface to the user. This is the same sort of of window you see with any application you run on your computer. It contains a title bar with standard controls to close or minimize the window- root = tkinter.Tk()- root is often used to refer to the primary GUI window root.title('My Python GUI Program')- displays window's title bar root.geometry('400x100')- window's size changes 3)Add widgets The elements of a GUI are organized into a hierarchy—widgets are added to a parent widget. Example, the Label widget is added to the root window, specified using the first argument. label = tkinter.Label(root, text='Hello, World!') label.pack() 4)Add event handlers def say_hello(): label['text'] = 'Hello ' + label['text'] button = tkinter.Button(root, text='Say Hello', command=say_hello) button.pack() *prints out 'Hello' to the label['text'] everytime the button is pressed
breif overview of GUI functions
1)widgets: Controls that let the user interact with a program in various ways 2)event handler: A function that performs an action when the user interacts with a widget 3)GUI: Provides "point and click" interaction with a program 4)Tcl/ Tk: Scripting language that supports GUI development 5)geometry manager: Specifies how GUI elements are laid out visually in a window 6)Tkinter: Package that supports GUI development in Python
class
A class describes an object. It is the type of the object. The term class comes from the word classification. A class describes a group of similar objects.
What is recursion? a)A problem solution defined in terms of a list. b)A problem solution defined iteratively. c)A problem solution defined in terms of itself. d)A problem solution defined without function calls.
A problem solution defined in terms of itself. The problem solution is expressed in terms of a slightly smaller version of the same problem.
subclass
A subclass might be called a child class or a derived class; the new class; The subclass inherits the elements of the superclass, and can then go on to add data and methods that make it distinct from the superclass. The subclass can also redefine (override) inherited methods in favor of its own.
superclass
A superclass is sometimes called a parent class or a base class; the existing class
Graphical User Interface (GUI)
A visual display on a computer's screen that allows you to interact with your computer more easily by clicking graphical elements; lets the user interact with the program using a variety of widgets such as windows, buttons, checkboxes, text fields, color choosers, and file choosers. Most programs you run on a computer have a graphical user interface.
behaviors
An object's behavior is the list of services that object will perform. These behaviors are represented by methods that are invoked through the object. ex: A car's behaviors might include accelerating, stopping, changing gears, and turning. Behaviors often affect attributes. A car that accelerates will affect its current speed, for instance.
call stack
Each call to the factorial function causes a new activation record to be pushed onto the call stack. Therefore, each call has it's own parameter value (n). The recursive calls continue until the base case is reached, and then the return value of each call contributes to the solution of the previous call.
resolution
Every monitor displays graphics at a particular resolution, which specifies how many pixels are available to display graphical elements. Higher resolutions produce more clear and precise graphics
All values stored in a Python dictionary must be unique.
False
Python represents a color using the CMYK color model
False
The Die class is part of the Python Standard Library.
False
The Pillow package is part of the Python Standard Library.
False
Only one radio button displayed in a window can be selected at any time.
False A window can display multiple sets of radio buttons that are mutually-exclusive within each group.
Selecting a check button will automatically unselect any other check buttons in its group.
False Check buttons don't work in groups. They represent individual boolean situations.
The leftmost end point of a line segment must be specified as the start point of the line.
False Either side can be considered the start or end point
The askcolor method is defined in the webcolors module
False It's defined in the colorchooser module.
Detecting a combination key press (such as Control-z) requires two calls to the bind method
False Modifiers like Control- can be added to most key event strings to represent a key combination.
Each check button in a Python program must have its own event handler function.
False Multiple check buttons could use the same event handler, or none at all.
A polygon or polyline can have at most 10 vertices.
False Polygons and polylines can have as many vertices as needed.
In Python, a class can only be derived from one parent class.
False Python supports multiple inheritance
The selection_sort function uses a single loop to perform sorting by comparing each element exactly once
False Since there are two nested loops in selection_sort, most elements are compared many times.
Text color is determined by the font applied when calling the create_text method
False Text color is specified using the fill keyword parameter, and is not part of the font descriptor.
The size of a Text widget is specified using a string that indicates the width and height in pixels.
False That's how the window size is specified. The size of a Text widget is specified using optional parameters.
The variable a radio button updates determines its visual layout.
False The associated variable has nothing to do with the visual presentation of the button.
The default anchor point for text on a Canvas is the northwest (upper left) corner of the text.
False The default anchor is the center of the text
When a color chooser is first displayed, the initial color selected is black.
False The default color is white, but you can specify the initial color to be any color you'd like.
If left unspecified, the font applied to text displayed on a Canvas is 12-point Lucinda Grande.
False The default font used depends on the operating system running the program
The insertion sort algorithm only works on a list of integer
False The insertion_sort function will work on any values that can be compared with relational operators like greater than (>).
The optional argument called mask is used to specify a character that will be displayed in a Text widget instead of the actual characters.
False The parameter name is called show and it is used in the Entry widget.
The recursive solution for reversing a string is more straightforward than its iterative solution.
False The recursive version is used to show recursive processing, not as a practical solution.
A Canvas text string cannot contain a newline (\n) character
False The text will break to a new line when the newline character is encountered.
A polyline is created using a call to the create_polyline method.
False There is no create_polyline method. You use the same method used to draw a simple line.
If a == b is true, then a is b will also be true?
False They could be referring to diff. objects w/ the same value
A binary search only works if the number of elements to search is odd.
False a binary search can be performed on any number of elements
By default, rectangles and ovals drawn on a Canvas are filled with black.
False by default, the rectangles and ovals are unfilled
The values passed to the create_polygon method represent the lengths of the edges of the polygon.
False represent the x and y coordinate values of the polygon's vertices.
methods (class)
Functions that are part of classes ex: __init__ and __str__
Creating shapes (methods)
In Tkinter, drawing is done on a Canvas widget by calling its methods: create_line method: draws a line segment that extends from one point to another. The arguments to the method specify the start point and end point of the line. It doesn't matter which coordinate pair is designated the start or end point. create_line(startX, startY, endX, endY) create_rectangle method: accepts four arguments representing two points. One coordinate pair represents the upper left corner of the rectangle and the other represents the lower right corner of the rectangle. create_rectangle(startX, startY, endX, endY) create_oval method: draw both ovals and circles, since a circle is just an oval with a square bounding box. create_oval(startX, startY, endX, endY)
color models
Often, color choosers in programs such as Photoshop will let you specify a color using any of these models. In Python, colors are specified using the RGB color model, which stands for Red, Green, and Blue. This model is based on the way humans perceive color.
constructor
Once a class is defined, you can create as many objects of that class as you'd like by calling the constructor, a function that has the same name as the class; The constructor returns the newly created object
Python Imaging Library/ Pillow (PIL)
Package is not part of the Python Standard Library; need to install it using the package manager in your IDE or with pip from the command line: >pip3 install pillow more sophisticated image manipulation; can do pixel-level manipulations, rotation, zooming, cropping, masking and transparency, blurring, smoothing, edge finding, sharpening, as well as adjusting the brightness, contract, or color of the image. -The coordinates used for the cropping region are relative to the image, not the canvas. -When a Pillow Image object is cropped, rotated, or manipulated in other ways, a copy of the image is created. The original image is unchanged. -A Pillow Image object must still be converted to a Tkinter PhotoImage object to be displayed on a Canvas.
encapsulation
Python does not have private variables and doesn't enforce encapsulation. It is simply expected that any code that uses the object will respect the purpose of the instance data and update it accordingly.
Is constant's value permanent?
Python does not prohibit changing a constant's value; in Python the idea of a constant is itself a convention. ex: pi in the math module is a constant
Multiple Inheritance
Python supports multiple inheritance, which means a class can be derived from more than one superclass. multiple parent classes are separated by commas in the class header of the derived class: class Copier(Scanner, Printer): pass What happens when both parents define a method or variable with the same name? The answer is found in the way references get resolved. If a variable named machine refers to a Copier object, then a call to machine.reset() must be resolved to a particular method. First, the Copier class is checked. If it has its own reset method (maybe overriding a parent's version), then that is the method that gets invoked. Inheritance, really, is about how methods are found in a class hierarchy, rather than how they are "passed down" to child classes. ex: a scanner and a printer are two useful devices that perform particular jobs. If we were representing these devices in software, we might define separate classes with the following inheritance relationship: The Copier class inherits the methods and data from both classes, then adds any that are unique to copiers.
multidimensional lists
The concept of a two-dimensional list can be generalized for any number of dimensions. For example, a three-dimensional list would be a list of lists of lists.
self reference
The first parameter to any method is called the self reference. The parameter doesn't have to be called self, but by convention it should be. The self parameter is a reference to the instance that is executing the code (it's a reference to itself)
dunder methods
The leading and trailing double underscore characters set these apart as methods that play a special role ex: __init__ and __str__ The __init__ method is the object initializer. It is called automatically when a new object is created to give initial values to the data used that represent the attributes of the object. Typically, you'll define an initializer for a class, but not a constructor. The __str__ method is used to return a character string that describes the object.
bind (mouse-events)
To respond to a mouse event, a program must bind an appropriate event string to a function that serves as an event handler- calls the bind method of the Tkinter widget that will generate the event. Once the binding is established, whenever the event represented by the event string occurs, the event handler will be called-> ex. <B1- Motion> mouse drag syntax: canvas.bind('<Button-1>', handle_mouse_button) It's best to bind mouse events to the most relevant widget.
A Button can display text and an image at the same time.
True
A class represents a group of similar objects.
True
A generator expression has the same basic syntax as a list comprehension.
True
A subclass is a more specific version of its superclass.
True
A trackpad generates mouse events.
True
An object created from a class is called an instance of that class.
True
Big O notation is used to categorize algorithms by how efficient they are at solving a problem
True
Each object has its own instance data.
True
If an invalid number of sides is provided when a Die object is created, a die with 6 sides is created.
True
Keyboard events are generated immediately when a keyboard key is pressed or released.
True
Multiple strategies can be used to sort a list of elements
True
Radio buttons work in a group to provide a set of mutually-exclusive options.
True
Selection sort requires minimal extra memory as it can be performed in place in an array
True
The Internet of Things is made up of a growing number of devices that collect and transfer data over the Internet without human involvement.
True
The Pillow package can be used to perform more sophisticated image manipulation than the Tkinter package.
True
The human eye has three types of color receptors that correspond to wavelengths of red, green, and blue
True
The if clause in a comprehension is optional.
True
The in and is operators both produce boolean results
True
The in operator can be used to check the contents of a character string or a list
True
The items method returns a list of key/value tuples for all entries in a dictionary
True
The result of a comprehension could always be created using more verbose code.
True
The set method can be used to set the value of a text field
True
A cooperating group of radio buttons is determined by the variable each button updates.
True All buttons that update the same variable form a mutually-exclusive group.
An object's __str__ method is called automatically when an object is printed.
True Also called when an object is concatenated with a string
Each Person object has its own last name.
True Each objects has its own instance variable that can store a different name
In Python, swapping two values in a list can be done with one line of code
True In some other languages you'd need a temporary variable and three assignment statements.
Inserting a value in its correct position may require shifting one or more values to create an insertion point
True Insertion sort must shift values within the array to make room for a new value to be inserted in the correct spot.
Cropping an Image object does not change the original image file.
True It creates a new Image object with only the cropped pixels.
The askcolor method returns a tuple that specifies the color in two ways
True It returns the selected color as an RGB value and as a hex string.
The initializer method of the Person class is called __init__.
True It's a special method that initializes instance data
Each call to a recursive function has its own parameter values
True Memory space for the parameter is created for each call to the function.
The position of text on a Canvas is specified by the first two arguments to the create_text method.
True The coordinate point (x, y)
The event handler for a Button can be specified using a parameter to the Button constructor.
True The event handler is set using the command keyword parameter
The text of a Button can be displayed in various fonts.
True The font can be specified when the button is created or using the configure method
When drawing a polygon, the order in which the vertices are listed may matter.
True The order could affect the shape of the polygon.
The insertion_sort function uses two loops, one to scan the list and another to shift values in the list.
True The outer loop finds the insertion point of the new value and the inner loop shifts values over to make space for it.
A dash pattern of (8, 3) specifies a series of 8-pixel line segments separated by a 3-pixel gap.
True The pattern repeats as many times as necessary for the entire line
For a keyboard event to be recognized, the widget on which the binding is made must have the keyboard focus.
True The widget that has the keyboard focus is the "target" of keyboard input.
Whether text is displayed in bold or italic type is specified in the font descriptor
True They are specified w/ terms included in the optional style string
The subsample method is used to scale an image smaller, but not larger.
True You use the zoom method to scale an image larger.
You can use the is operator to check if a variable contains a certain type of data.
True using the isinstance built-in function
Two functions can have the same name if they are in different modules
True Modules provide a unique namespace in which to define functions and classes
Button Widget
a GUI widget that allows the user to initiate an action by pushing a graphical button using the mouse. In Tkinter, a button is represented by the Button class. A Button object invokes a function that acts as an event handler when it is pushed. ex. of code of button + photo added: b1 = Button(frame, text='Update My Order', font=('Helvetica', 16, 'bold'), background='gold', activebackground='orange', padx=20, pady=10) photo = PhotoImage(file='income_projection.png') b2 = Button(frame, text='Income Projection', image=photo, compound=LEFT, relief=GROOVE, padx=5, pady=5) b3 = Button(frame, image=photo, borderwidth=10, relief=RIDGE)
check button/ check box
a GUI widget that can be toggled on or off. Each check button represents a boolean option — it is either selected or it's not. check buttons operate independently of each other; you may have multiple check buttons in an interface, selecting one has no effect on the status of any of the others. Each Checkbutton is associated with a Tkinter object called a BooleanVar- maintains the status of the button (checked or not) and associated with the button using the var parameter. use the get method of the BooleanVar object- returns a boolean value indicating if its checked or not
text field
a GUI widget used to accept one or more lines of input that is typed on the keyboard The Tkinter package includes two text field widgets: The Entry widget: is used for a single line of input, such as a name, email address, or password; print_text, the get method of the entry field is used to retrieve its current contents optional argument 'show' of the Entry widget: used to specify a character that will mask the actual characters The Text widget: handles multiple lines of text, for longer input; get method of a Text widget returns a portion of the text currently in the field as specified by its arguments.
hex string
a color can be represented in Python as a hex string specifying the color's RGB value. A hex string is composed of the pound sign (#) followed by three pairs of hexadecimal digits. Each pair represents the individual R, G, and B components of the RGB value. example: the hex string '#6D24EC' represents a deep purple color
widgets
a graphical element, such as a label, button, checkbox, or text field
object
a program component that represents something, physical or otherwise, and performs related tasks. All Python values are objects, including integers, strings, lists, etc. The operations you can perform on those objects depend on the type, or class, of the object. An object is an instance of a class
Which string represents the event generated when the user presses the Enter key? a)'<Return>' b)'<Enter>' c)'<CR>' d)'<Entry>'
a)'<Return>' Return and Enter are names for the same key.
Which of the following is an appropriate analogy? a)Class: concept of a dog, Object: my dog Fido b)Class: house, Object: blueprint c)Class: cookie, Object: cookie cutter d)Class: score, Object: scoreboard
a)Class: concept of a dog, Object: my dog Fido
Which Python function can be used to call a method of a superclass? a)super b)parent c)self d)my
a)super
Which two terms mean the same thing? a)superclass and parent class b)child class and superclass c)base class and child class d)parent class and subclass
a)superclass and parent class
Images
an image represented as a PhotoImage object. The image can then be displayed on a Canvas, Label, or Button... *need to import represent GIF and PNG images on most systems. If you need to work with other image formats (i.e., JPG, BMP, etc.) or perform advanced image manipulations, you'll want to use the Python Imaging Library The file name of the image is specified using the file keyword parameter: img = PhotoImage(file='monkey.png')
Which string represents the event generated when the user presses the left mouse button? a)'<B1>' b)'<Button-1>' c)'<Button-3>' d)'<B3>'
b)'<Button-1>' That's the string used in the call to the bind method.
What is the output of the following code? die = Die(6) print('Die value:', die) a)Die value: 0 b)Die value: 1 c)Die value: 6 d)A random number from 1 to 6 will be printed.
b)Die value: 1
To display an image on a Canvas, it must be represented using which kind of object? a)Image b)PhotoImage c)CanvasImage d)ImageView
b)PhotoImage
When comparing sorting algorithms, what does the value n represent? a)The Big O category of the algorithm. b)The number of elements in the list to be sorted. c)The speed of the algorithm. d)The number of comparisons needed to sort the list.
b)The number of elements in the list to be sorted.
Overriding occurs in which of the following situations? a)When a subclass is derived from more than one superclass. b)When a subclass redefines a method it inherits from a superclass. c)When a subclass adds a new function that was not inherited from a superclass. d)When a subclass calls a method from a superclass.
b)When a subclass redefines a method it inherits from a superclass. The child overrides the inherited version of the method
Which of the following ovals is also a circle? a)canvas.create_oval(150, 150, 300, 250) b)canvas.create_oval(100, 200, 155, 255) c)canvas.create_oval(70, 70, 170, 140) d)canvas.create_oval(95, 120, 190, 240)
b)canvas.create_oval(100, 200, 155, 255) The width and height of the oval are the same
Which of the following ovals is thinner than it is tall? a)canvas.create_oval(90, 90, 150, 145) b)canvas.create_oval(140, 100, 160, 150) c)canvas.create_oval(150, 135, 230, 195) d)canvas.create_oval(270, 300, 450, 400)
b)canvas.create_oval(140, 100, 160, 150)
Which of the following rectangles extends furthest down? a)canvas.create_rectangle(80, 25, 180, 155) b)canvas.create_rectangle(50, 85, 120, 160) c)canvas.create_rectangle(150, 90, 220, 135) d)canvas.create_rectangle(100, 50, 150, 150)
b)canvas.create_rectangle(50, 85, 120, 160)
Which direction would the following arc "point"? That is, where is the center point of the oval relative to the arc?canvas.create_arc(200, 200, 270, 230, start=45, extent=90) a)up b)down c)right d)left
b)down The center point is below the arc.
Which of the following hex strings represents the color white? a)'#000000' b)'#640000' c)'#FFFFFF' d)'#646464'
c)'#FFFFFF' Full contribution of the red, blue, and green corresponds to white
How many times will the gcd function be called (including the initial call) to determine the greatest common divisor of 728 and 105? a)1 b)2 c)3 d)4
c)3 It's called as gcd(728, 105), which calls gcd(105, 98), which calls gcd(98, 7).
What is infinite recursion? a)A solution that terminates with an InifiniteRecursionError. b)A solution that uses an infinite loop. c)A situation in which the base case is never reached. d)A situation in which the recusive call is never made.
c)A situation in which the base case is never reached. The function will keep calling itself until the call stack limit is reached.
Which of the following algorithms is generally faster than the others? a)Bubble Sort b)Insertion Sort c)Merge Sort d)Selection Sort
c)Merge Sort
Which image formats are reliably supported by Tkinter? a)JPG and PNG b)BMP and PNG c)PNG and GIF d)JPG and GIF
c)PNG and GIF These are the only two formats you can safely use with the Tkinter package.
Which of the following is NOT a quadratic sorting algorithm? a)Selection Sort b)Bubble Sort c)Quick Sort d)Insertion Sort
c)Quick Sort
Which of the following best summarizes the selection sort algorithm? a)Repeatedly swap values with the next value in the list. b)Repeatedly select a random, unsorted value and put it in its sorted position. c)Repeatedly select the smallest remaining value and put it in its sorted position. d)Repeatedly swap values with the value in the first position.
c)Repeatedly select the smallest remaining value and put it in its sorted position. On each iteration, selection sort finds the smallest value that hasn't yet been selected.
Which Tkinter text field widget allows for multiple lines of input? a)Entry b)MLEntry c)Text d)MLText
c)Text
Which of the following contribute to the state of a Car object? a)The variable used to identify the car. b)The ability to turn. c)The car's color. d)The methods of the Car object.
c)The car's color
From where can the location of a mouse event be obtained? a)The widget generating the event. b)The event string. c)The event object passed to the event handler. d)The root window.
c)The event object passed to the event handler. The parameter to the event handler function has several fields that may be helpful.
What is the base case of a recursive definition? a)The situation that ignores the non-recursive case. b)The situation that requires a loop instead of recursion. c)The situation that requires no recursion. d)The situation that defines the problem in terms of itself.
c)The situation that requires no recursion. The base case is the alternative to the recursive case.
What value will the variable my_list hold after the following line of code is executed? my_list = [num for num in range(1, 20) if num % 3 == 0] a)[1, 2, 3] b)[1, 3, 9, 18, 20] c)[3, 6, 9, 12, 15, 18] d)[]
c)[3, 6, 9, 12, 15, 18]
Which of the following arcs is the same as this one? canvas.create_arc(200, 220, 280, 270, start=40, extent=140) a)canvas.create_arc(200, 220, 270, 280, start=40, extent=140) b)canvas.create_arc(100, 200, 180, 250, start=40, extent=140) c)canvas.create_arc(200, 220, 280, 270, start=-180, extent=-140) d)canvas.create_arc(200, 220, 280, 270, start=-40, extent=-140)
c)canvas.create_arc(200, 220, 280, 270, start=-180, extent=-140) This arc spans the same area of the ellipse, but is defined using negative angle values.
Which of the following creates the largest circle? a)canvas.create_oval(150, 175, 195, 220) b)canvas.create_oval(30, 80, 55, 105) c)canvas.create_oval(50, 50, 150, 150) d)canvas.create_oval(20, 100, 50, 130)
c)canvas.create_oval(50, 50, 150, 150) This circle, with a radius of 50, is larger than any of the others.
Equal contributions of the three components in an RGB color results in various shades of what? a)green b)red c)gray d)blue
c)gray
Which direction would the following arc "point"? That is, where is the center point of the oval relative to the arc?canvas.create_arc(150, 250, 250, 400, start=160, extent=40) a)up b)down c)right d)left
c)right
What value will the variable stuff hold after the following code is executed? state = 'Mississippi' stuff = {ch.lower() for ch in state if ch != 'i'} a)['m', 's', 's', 's', 's', 'p', 'p'] b){'m', 'i', 's', 'p'} c){'m', 's', 'p'} d)['M', 'i', 's', 's', 'i', 's', 's', 'i', 'p', 'p', 'i']
c){'m', 's', 'p'} It's a set containing unique lowercase letters besides the letter 'i'
Drawing texts
create_text method: typically takes at least three arguments. The first two represent the (x, y) position where the text is to be displayed. The third is a keyword parameter named text that specifies the text itself as a string. anchor: used to position the text relative to the point specified by the first two arguments. The value of anchor can be one of several Tkinter constants: NW, N, NE, W, CENTER, E, SW, S, and SE. The default anchor is CENTER. Any anchor constants used must be imported from the tkinter package.
Which of the following best summarizes the insertion sort algorithm? a)Repeatedly insert each value in a random position. b)Repeatedly swap values inside the sorted sublist. c)Repeatedly insert values in a second list and then shift them into the first list. d)Repeatedly insert each value into its correct position.
d)Repeatedly insert each value into its correct position. On each iteration, a new value is inserted into the right spot in a growing, sorted sublist.
Which of the following is NOT a logarithmic sorting algorithm? a)Quick Sort b)Merge Sort c)Heap Sort d)Selection Sort
d)Selection Sort The Big O category of Selection Sort is O(n2).
What are the names of the two text field widgets in Tkinter? a)EntryField and TextField b)Text and TextField c)Entry and TextField d)Text and Entry
d)Text and Entry The primary difference is the amount of text they accept.
Which of the following creates a horizontal line? a)canvas.create_line(30, 30, 50, 50) b)canvas.create_line(40, 20, 100, 70) c)canvas.create_line(75, 20, 75, 90) d)canvas.create_line(25, 70, 125, 70)
d)canvas.create_line(25, 70, 125, 70)
Deriving one class from another establishes what kind of relationship between the two classes? a)aggregation b)uses c)has-a d)is-a
d)is-a The subclass is-a more specific version of its superclass.
Which field of the event object passed to the event handler can be used to determine which key was pressed? a)keyfocus b)keypressed c)keychar d)keysym
d)keysym It contains a string that can be used to identify the key.
Which direction would the following arc "point"? That is, where is the center point of the oval relative to the arc?canvas.create_arc(170, 100, 220, 160, start=-20, extent=40) a)up b)down c)right d)left
d)left
Which of the following would be most appropriate to choose with a set of check buttons? a)your favorite ice cream flavor b)the highest educational level a person achieved c)your age range (0-12, 13-18, 19-29, etc.) d)the languages a person speaks
d)the languages a person speaks A person may speak multiple languages, whereas the others have mutually exclusive options.
dashes and arrows
dash argument specifies the pattern of the dashed line. It is passed as a tuple of values that represent the lengths of the segments and gaps. For example, a dash pattern of (7, 4) specifies a line segment of 7 pixels followed by a gap of 4 pixels, as shown in the red line. The gold line uses a pattern of (20, 5, 10, 5), which specifies a 20-pixel line followed by a 5-pixel gap followed by a 10-pixel line followed by a 5-pixel gap. Dash patterns can also be applied to the outlines of other shapes, such as rectangles. arrows- can add arrow to be only in one side (arrow=FIRST; arrow=LAST) or both sides (arrow=BOTH) *Some systems only support a limited set of dash patterns. The dash pattern displayed will be the closest pattern available. In these situations, experimentation will help you determine your best option.
Inheritance
defines an is-a relationship. The subclass is a more specific version of the superclass; the object-oriented programming technique that allows one class to be derived from another. The new class is created by extending the definition of an existing class. This is a form of software reuse. Whenever you're considering deriving one class from another, make sure the is-a relationship applies. ex: A Dog is a Mammal.
recursive definition
defines something in terms of itself. ex: factorial
attributes
describes the object; characteristics ; example, you may want to keep track of a car's make, model, color, current speed, and current direction.
geometry manager
determines how GUI elements are visually presented in the interface. The pack method organizes widgets in rows and columns. By default, the pack method centers each widget on its own row.
identity
distinguish one object from another, and to access it when needed. In a program, the variable that refers to an object serves as the object's identity.
What is the output of the following code? die = Die(20) die.roll() die.roll() print(die.value) a)0 b)1 c)20 d)A random number between 0 and 19. e) A random number between 1 and 20.
e) A random number between 1 and 20. Each call to the roll method assigns a random number to the die in the range 1 to the number of sides (20 in this case). *20 is inclusive due to randint; randrange is not inclusive of last parameter and it allows the step argument randrange([start], stop[, step])
frozenset
immutable version of a set. Once a frozen set is created, its elements cannot be changed. Any attempt to change the contents of a frozen set will result in an error.
color chooser
is a specialized dialog box that allows the user to select a color. The appearance and functionality of the color chooser will vary on the operating system. The Tkinter module called colorchooser contains a function: askcolor- pops up a color chooser dialog and returns the chosen color.
font
is known as the font family or font face, and specifies the general appearance of the characters. A font also dictates the size of the characters, specified in units called points
polyline
is like a polygon, except that it's not a closed shape. The last point of a polyline is not automatically connected to the first. created using the create_line method, the same one used to draw a simple line.
recursion vs. iterative
iterative solution to a problem is one that uses loops instead of recursion... sometimes a recursive solution is far more elegant and short than its iterative counterpart, however, there is the issue of efficiency
Drawing Arcs
keyword parameters -start and extent define the start angle and extent angle: The start angle indicates where the arc begins and the extent angle indicates the how far the arc sweeps along the oval's outline.
keyboard focus
means that keyboard input is currently directed to that widget. The root window has the keyboard focus by default unless its been redirected by other activity (such as the user clicking on a text field). To set a widget to have the keyboard focus, call its focus method.
mouse events:
mouse pressed event: occurs when a mouse button is initially pressed down mouse released event: occurs when the button is released mouse moved events: are generated as the mouse itself is in motion; generated in rapid succession, which allows a program to respond to the ongoing movement in real time mouse dragged events: If a mouse button is held down while the mouse is moved mouse entered event: when the mouse pointer is moved onto the widget (when the pointer enters its graphical space) mouse exited event: when the pointer moves off of the widget
radio buttons
mutually exclusive: only one can be chosen at a time; operate as a group the set method of the group variable: used to initialize the selected radio button, though calling the select method of a specific radio button will accomplish the same thing. The group variable's get method returns the value associated with the currently selected radio button.
nested, set, dictionaries, and generator comprehension
nested comprehension creates a lists of lists (ex: two dimensional): ex: matrix = [[x + y for x in range(5)] for y in range(5)] print(matrix) [[0, 1, 2, 3, 4], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8]] set comprehension is surrounded by curly braces ({}) like a set literal: ex: nums = [38, 188, 142, 99, 250, 188, 101, 85, 39, 188] big_num_set = {x for x in nums if x > 100} print(big_num_set) {101, 142, 188, 250} dictionary comprehension is also surrounded by curly braces, but the expression takes the form key:value to add each key/value pair to the dictionary. Otherwise, it works like all other comprehensions: ex: days = {n + 1 : day_names[n] for n in range(len(day_names))} print(days) generator comprehension: like a list representing an ordered sequence of values. However, a list represents the entire sequence in memory, whereas a generator produces values as needed.generator is needed only if the sequence of values is very large and memory efficiency is important. ex: gen = (x ** 2 for x in range(10000) if x % 2 == 0) *looks similar to a list comprehension, but is surrounded by parentheses rather than square brackets The use of parentheses around a generator expression DOESN'T create a tuple; python doeesn't have tuple comprehension. Yet, you can produce a tuple from a generator using the tuple constructor.
Tkinter
package is a popular framework for creating GUIs in Python; Tkinter is the de-facto standard Python GUI package. The 'tk' stands for toolkit and the 'inter' stands for interface. It is built on top of Tcl/Tk, a free and open-source, cross-platform scripting language and library of basic widgets for creating GUIs.
polygon
polygon: is a multi-sided shape with straight edges. vertices: The points where the edges connect A polygon is a closed shape; the last vertex is automatically connected to the first by an edge. create_polygon method: draws a polygon with as many edges as needed; accepts a variable number of integer or floating point values representing the x and y coordinates of the vertices, or a list of values to the method.
Sorting (sorting types)
process of putting a list of elements in a particular order. You might sort a list of numbers into ascending order, or a list of names into alphabetical order. The need to sort data occurs regularly in programming Big O notation puts sorting algorithms into categories and eliminates the irrelevant details of a particular algorithm; focuses on how fast the algorithm solves the problem in terms of n: quadratic sorts: O(n2) algorithms -Selection Sort -Insertion Sort -Bubble Sort logarithmic sorts: O(n log n) algorithms -Quick Sort -Merge Sort -Heap Sort Quadratic sorts are much slower than logarithmic sorts, however they are used b/c... - The strategies and implementations of quadratic sorts are generally easier to understand. It's a good way to introduce the exploration of sorting algorithms. -Comparing and contrasting sorting algorithms is a great way to understand algorithm efficiency.
state
represented by the values of its instance data. example: the state of a particular Car object might be that it's a green Honda CRV traveling northeast at 55 miles per hour. Another car's state might be that it's a black Ford Focus traveling south at 40 miles per hour.
bounding box
represents the argumentss passed into creating curved shapes such as an oval; The dimensions of the bounding box determine the shape of the oval that fits inside it- the arguments to the method represent the upper left and lower right corners.
arc style
set with the style argument. There are three styles of arc shapes: ARC: the curve along the oval's outline CHORD: an arc whose end points are connected by a straight line PIESLICE: an arc whose end points are connected by straight line segments to the center point of the underlying oval, forming a wedge shape with a rounded end. *default style
stroke
sometimes referred to the outline
pixel
stands for picture element
instance variables (fields)
this means that for each object or instance of a class, the instance variables are different. Unlike class variables, instance variables are defined within methods. The behaviors are defined by functions.
insertion sort
works by repeatedly inserting a new value into a portion of the overall list that is already sorted. One element at a time, the sorted sublist grows until the entire list is sorted. performed in an array, with minimal extra memory required. For each insertion, the elements in the sorted sublist have shifts to make room for the next element to be inserted.
selection sort
works by repeatedly selecting an element from the unsorted list and putting it into its final, sorted position. The element selected is typically the smallest (least) element. none of the elements are sorted. The smallest value is selected and swapped with the element at the first position
usage of set: checking containment
Checking if an element is in a set is an extremely efficient operation; the answer can be obtained in constant time, which means the size of the set doesn't matter Can use the in and not in operators on a list- however, Python sets are far more efficient in this regard especially if the number of elements is large
Why use constants?
-Constants convey more meaning than literals. -They help prevent errors caused by inappropriate modifications. -They make maintenance tasks easier and safer.
why use a dictionary?
1)Look up values 2)Count values of various types 3)Store a record of related values
one-dimensional list
A list with one index
two-dimensional list (2D list), with rows and columns
A table of data; is a concept, not a new data structure. A two-dimensional list is just a one-dimensional list of one-dimensional lists example: 7 rows (indexed from 0 to 6) and 5 columns (indexed from 0 to 4)
Using tuples
Indexing, concatenation, repetition, determining their length, slicing them, and iterating through their elements works; Like lists, tuple indexes go from 0 to len(tuple)−1. Since tuples are immutable, those methods aren't defined for tuples; tuples have no append or remove methods, only two methods: count and index. the index method is used to find an element in a tuple, returning either its index there, or generating a ValueError if not
The maximum indexes of a two-dimensional list with 6 rows and 10 columns are 5 and 9, respectively
True Each dimension is indexed from 0 to N-1, where N represents the number of elements in that dimension
import
you must import a module, or particular elements of a module, in order to use them except for built-in
accessing two-dimensional lists/ elements
A 2D list is often processed using nested loops, one for each dimension; Nested loops are the access the elements of a two-dimensional list- The outer loop sets the row index for each row and the inner loop sets the column index for each column in the current row When the matrix is first created, all elements stored in the matrix
A binary search works best on an unsorted list of values.
False
A dictionary is bidirectional — values can be used to look up keys and vice versa.
False
A dictionary key must be a character string
False
A for loop can be used to traverse a dictionary's keys, but not its values
False
Constants automatically convert between units of measure
False
The data science process is linear.
False
The from clause of an import statement lets you define an alias for a module or function
False
The primary difference between lists and tuples is that lists are immutable and tuples are not
False
The smallest index of any dimension of a two-dimensional list is 1.
False
Checking to see if an element is in a set is an efficient operation in Python.
True
Defining a class is an alternative to using a dictionary as a record.
True
If you use a 'from' clause on an import statement, you don't have to use the module name to refer to a function from that module
True
Python is probably the most popular programming language for data science.
True
Using square brackets to retrieve a value will result in a KeyError if the key is not in the dictionary
True
When using a dictionary as a record, the name of the attribute is used as the key.
True
access set elements
Unlike other sequences such as strings, lists, and tuples, you CANNOT access the individual elements in a set using an index. CAN use for loops; you're not guaranteed the elements will be retrieved in any particular order.
set methods
add single item: .add() update (add multiple items): .update() remove (KeyError w/o an item): .remove() discard(no effect w/o an item): .discard() *sets do not allow duplicate elements. Any attempt to add an element that already exists in the set will be ignored
dictionary
an object that lets you use a key to look up a value; you provide the word (the key), and the dictionary provides the definition (the value); unordered collection of keys and corresponding values; stores key/value pairs such that a value can be found efficiently given its key The keys must be unique, and can be immutable data type (ex: int/ str). The values don't have to be unique and can be of any type. Multiple keys could map to the same value. The type of a dictionary is dict, which is a Python built-in data type.
check key's existence
avoid generating a KeyError, you can verify that a particular key is present in the dictionary using the in operator before trying to access its value; also use the not in operator on a dictionary, which returns True if the key is not in the dictionary.
How many comparisons are necessary to find the value 43 in the following list using a binary search? 13 25 28 30 39 43 44 58 66 70 78 81 86 88 95 a)1 b)3 c)4 d)6
b)3 elements examined in order: 58, 30, 43
Which of the following is NOT a reason to use a constant? a)Constants prevent inadvertent programming errors. b)Constants minimize the need for input validation. c)Constants make maintenance tasks easier and safer. d)Constants convey more meaning than literals.
b)Constants minimize the need for input validation
Which of the following statements is true when using a dictionary for counting? a)The key is the item list, the value is the count list. b)The key is the item counted, the value is the count. c)The key is the count, the value is the item counted. d)The key is the count list, the value is the item list.
b)The key is the item counted, the value is the count.
If the value of weight is 7, what does the following statement print? print('The weight is ' + ('even' if weight % 2 == 0 else 'odd')) a)The weight is even b)The weight is odd c)The weight is void d)The weight is NAN
b)The weight is odd
Which of the following methods can be called on a tuple? a)extend b)index c)append d)reverse
b)index
When performing a binary search, how many comparisons are required to find a value in a list of N values, in the worst case? a)1 b)log2N + 1 c)N / 2 d)N2
b)log2N + 1
What set is stored in set3 by the following code? set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7, 8, 9} set3 = set1 | set2 a){3, 4, 5} b){1, 2, 3, 4, 5, 6, 7, 8, 9} c){6, 7, 8, 9} d){1, 2}
b){1, 2, 3, 4, 5, 6, 7, 8, 9}
dict
built-in function dict- which is the object constructor for the dictionary type. The dict function returns a new dictionary based on the arguments provided.
syntax: dictionaries
create: curly braces ({}) separate an initial list of key/value pairs: (:) retreive: square brackets ([key of the value]) change: specify the new value for an existing key using an assignment statement, as the old key is replaced by the new value new entry: use a new key remove entries: particular entry- pop method (.pop( ) )/ KeyError (N/A) entry/ entire dict.- del... have to specify key or else removes the whole dict. all entries except the dict.- clear method (.clear( ) )
tuples or lists?
if you need to add, remove, or change the contents over time, a list is the way to go. tuples are immutable, thus accessing tuple elements is faster than accessing list elements. Great for managing a large, constant set of values; helps avoid inadvertent errors caused by code written by someone who doesn't realize the data should not change.
tuple unpacking
lets you assign the values in a tuple to multiple variables in one step; often used with tuples, but this type of multiple assignment can be used to extract the elements of any iterable object, such as a list or string example: following code assigns the value 20 to x and the value 350 to y: x, y= (20,350) print('x is', x) print('y is', y)
script
main driver of the program; a program is not only composed of the script code that drives it, but is also made up of the functions that are used from imported modules
set
mutable built-in data type that represents an unordered collection of values that does not allow duplicate elements. In Python- models the mathematical concept of a set. The elements of a set cannot be accessed using an index. The main operations allow you to add or remove elements, and to check if it contains a particular element. Sets are unordered. When printed the elements may appear in any order. syntax: curly brackets ({})
comprehension filters
optional if clause can be added to a comprehension to filter the elements based on a boolean condition; For each element, a value is only added to the resulting collection if the condition is True list syntax: ['expression' for 'item' in 'sequence' if 'condition']
linear search
searches a list by starting at the beginning and looking at each element one at a time until the target is found or the end of the list is reached
iterating through dictionary
use for loop to iterate through a dictionary and access all of its members. If you iterate over the dictionary itself, the keys are obtained one at a time
ragged lists
When data is more suited to a ragged list, it may not be appropriate to think of it as a table b/c it has a non-aligning rows/columns.
conditional expression vs. if-else statement
An expression produces a value that, to be useful, you must do something with (print it, assign it to a variable, etc.). A statement stands on its own. The behavior of an if statement depends on the statements that are controlled by the condition.
The maximum number of dimensions a Python list can have is 3.
False The concept of multidimensional list can be extended to any # of dimensions
Functions of the math module do not have to be imported
False The only functions that don't need to be imported is the built-ins
An import statement finds a module and binds it to a name you can use in a program
True Refer to the function in the module by using a dot operator ex: import package.module
implementing binary search
It can accept arguments as a list of values to search and a target value to find; The efficiency of a binary search depends on being able to "jump" to the middle element. List indexing lets us do just that, whereas a linked list data structure does not. However, a binary search can be performed on linked data if it is organized into a binary search tree. there is no explicit binary search function in the library, the bisect module contains functions that can be helpful; bisect module is used to find the proper place in a list where a value can be inserted in order to keep the list sorted.
target element
The goal of a search among a possibly large list of elements, might also not be in the list
membership operators
The in and not in operators produce a boolean (True or False) result; be used to check the type of a variable (or, to be more precise, the type of the object to which the variable refers) ex: 'isinstance' (built-in) returns True if the first argument is of the type specified by the second argument if isinstance(x, str): print('x is in string')
identity operators
The is and is not operators are used to check if two variables refer to the same object checking identity is different than checking if two variables hold the same value. If x == y is true, then they refer to objects that contain the same value- doesn't mean they necessarily refer to the same object; if x is y is true, then it will also be true that x == y.
A dictionary is designed for efficient value retrieval
True
A two-dimensional list is really a one-dimensional list of one-dimensional lists.
True
A two-dimensional list is suitable for storing tabular data. True
True
An entire module can be imported using one import statement
True
Which of the following operations cannot be performed on tuples? a)indexing b)slicing c)element removal d)concatenation
True
If a is b is true, then a == b will also be true?
True If both variables refer to the same object, their values are the same
A example of a ragged list is a two-dimensional list where each row has a different number of columns.
True Ragged lists have at least one dimension of non-uniform length
set constructor
a built-in function returns a set based on other data ex: my_list = [11, 22, 33, 22, 44] my_set = set(my_list) print(my_set) *22 prints only once
comprehension
a compact programming expression used to create a new collection based on the elements of a sequence; uses a for loop to iterate over a sequence of values and determine value added in the new collection a syntactic convenience- same results can always be produced using more verbose, less pythonic code (like using separate for loops and append method), etc. ex: a list comprehension is used to create a new list based on a sequence such as a range, string, or another list
package
a group of modules; a folder containing modules and even other packages; a package is just a special kind of module that can contain other modules. Example: the tkinter package contains several modules that all contribute to the development of graphical user interfaces (GUIs). ex: Python Standard library
tuple
a sequence of values similar to a list. Like a list, a tuple can hold multiple values, and those values are referred to as its elements. However, they are immutable (like strings)- can't change its elements syntax: parenthesis ( )
module
a single Python file that contains a group of related functions, classes, and variables. Example: the math module- contains many functions that perform basic mathematical operations.
constant
a variable, except that its value never changes; whose value doe not vary at all. naming convention: all uppercase w/ individual words separated by an underscore can hold any type of data
If the value of num is 7 and the value of max is 10, what is the value of num after the following statement is executed? num = max if max < num else max - num a)3 b)4 c)7 d)10
a)3
Which of the following is NOT an appropriate use case for a Python dictionary? a)Representing an ordered sequence of values. b)Counting the frequency of values. c)Looking up a value. d)Representing a record of related values.
a)Representing an ordered sequence of values.
Which of the following is NOT a constant from the Python Standard Library? a)conversions.KILOMETERS_PER_MILE b)tkinter.NE c)math.pi d)math.e
a)conversions.KILOMETERS_PER_MILE
Which assignment statement is functionally equivalent to the following if statement? if num1 > total: num1 = total else: num1 = 0 a)num1 = total if num1 > total else 0 b)num1 = 0 if total > 0 else total c)num1 = 0 if num1 > total else total d)num1 = total if num1 > 0 else 0
a)num1 = total if num1 > total else 0
What set is stored in set3 by the following code? set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7, 8, 9} set3 = set1 - set2 a){6, 7, 8, 9} b){1, 2} c){1, 2, 3, 4, 5} d){1, 2, 6, 7, 8, 9}
b){1, 2}
module vs. script
both contain Python code: file names that have a .py extension. script- can be thought of as the main driver of a program module- is thought of as a library, containing functions and other elements that are imported and used in a script. A module can import other modules as needed.
How many comparisons are necessary to find the value 86 in the following list using a binary search? 13 25 28 30 39 43 44 58 66 70 78 81 86 88 95 a)2 b)3 c)4 d)5
c)4
Which of the following identifiers follows the naming convention for a Python constant? a)MAXPENALTIES b)maxPenalties c)MAX_PENALTIES d)Max_Penalties
c)MAX_PENALTIES
What does "cleaning" data mean? a)Truncating long floating-point values to a reasonable number of decimal places. b)Removing data that does not support the desired conclusion. c)Preparing data for analysis by improving its structure and organization. d)Presenting data in clear graphs and diagrams.
c)Preparing data for analysis by improving its structure and organization.
Which of the following is not a good description of the goal of data science? a)Turn data into information, and information into knowledge. b)Use data to answer real-world questions. c)Protect data against invalid access. d)Use data to gain insight, and use insight to take action.
c)Protect data against invalid access.
What does the following statement print? print('Invalid' if count <= 0 else count) a)Zero, or 'Invalid' if count is negative. b)Zero, or 'Invalid' if count is positive. c)The value of count, or 'Invalid' if count is negative. d)The value of count, or 'Invalid' if count is positive.
c)The value of count, or 'Invalid' if count is negative.
Which of the following is NOT a good reason to use a tuple rather than a list? a)Accessing tuple elements is faster than accessing list elements. b)It establishes that the data should not be changed. c)Tuples can hold more elements than lists. d)Some tuples can be used as keys in a dictionary.
c)Tuples can hold more elements than lists Not true- there is no limit to the # of elements in a tuple or a list
Which of the following is not a primary contributor to data science? a)domain expertise b)computer science c)procurement d)statistics
c)procurement
How many elements can be stored in a two-dimensional list with 5 rows and 10 columns? a)36 b)40 c)45 d)50 e)66
d)50 There are 5 rows and 10 columns, therefore room for 50 elements
What set is stored in set3 by the following code? set1 = {1, 2, 3, 4, 5} set2 = {3, 4, 5, 6, 7, 8, 9} set3 = set1 & set2 a){6, 7, 8, 9} b){1, 2} c){1, 2, 3, 4, 5, 6, 7, 8, 9} d){3, 4, 5}
d){3, 4, 5}
namespace
items in the module allow two items to have the same name as long as they are in different modules.
dictionary methods
items(): returns a list containing a tuple for each key/value pair get(key): returns the value of the specified key keys(): returns a list containing the dictionary's keys values(): returns a list of all the values in the dictionary.
binary search
requires the elements in the list to be sorted; more efficient- we can quickly reduce the group of viable candidates in the list where the target might still be found begins by examining the value in the middle of the list, then eliminates half of the data from consideration after only one comparison. Then jumps again to the middle of the remaining viable candidates and examine that element
set operators
the equality and relational operators can be used on sets, returning boolean results: s1 == s2 s1 != s2 s1 <= s2 s1 >= s2 One set (s1) is a subset of another (s2) if all elements in s1 are contained in s2. If s2 contains additional elements (not in s1), then s1 is a proper subset of s2. Similar definitions apply for the terms superset and proper superset. Other operators can be used to perform the classic set operations union, intersection, and difference, which produce new sets: s1 | s2 (union) s1 & s2 (intersection) s1 - s2 (difference) s1 ^ s2 (symmetric difference: defined as the set of elements that are in one set or the other, but not both)