Python Summary

The textbook has many useful tables describing various functions and what they do. here I have tried to bring everything together so that you can have it as an easy reference. While I have included everything that was in the tables in the book, I have rearranged some parts to avoid duplication and add some extra commands where I thought they may be useful.

Common Syntax

Only doing something if a condition is true:


  if condition:
      statements
  

Do one thing if a condition is true, and something else if false:


  if condition:
      statements
  else:
      statements
  

Having multiple conditions to check and only ever entering one:


  if condition1:
      statements
  elif condition2:
      statements
  elif condition3:
      statements
  

While statements:


  while condition:
      statements
  

For statements:


  for var in seq:
      statements
  

Function definitions:


  def name(parameters):
        statements
  

Return statement:


  return expression
  

Built-in Functions

abs(x) Returns the absolute value of x
max(x, y, ...) Returns the largest of the arguments
min(x, y, ...) Returns the smallest of the arguments
round(x) Returns the closest integer to x
int(x) Truncates x to an integer
float(x) Converts x to an floating-point number
len(s) Returns the length of the string argument s
str(x) Converts x to a string

Common Libraries

Mathematical Constants

pi The mathematical constant π
e The mathematical constant e (the base for natural logarithm)

General Mathematical Functions

sqrt(x) Returns the square root of x
floor(x) Returns the largest integer less than or equal to x
ceil(x) Returns the smallest integer greater than or equal to x
copysign(x,y) Returns x with the sign of y

Logarithmic and exponential functions

exp(x) Returns the exponential function of x (\(e^x\))
log(x) Returns the natural logarithm (base e) of x
log10(x) Returns the common logarithm (base 10) of x

Trigonometric functions

cos(theta) Returns the cosine of the radian angle theta
sin(theta) Returns the sine of the radian angle theta
tan(theta) Returns the tangent of the radian angle theta
atan(x) Returns the principal arctangent of x, which lies between \(-\pi/2\) and \(+\pi/2\)
atan2(y, x) Returns the angle between the x-axis and the line from the origin to (x,y)
radians(angle) Converts an angle measure in degrees to radians
degrees(angle) Converts an angle measured in radians to degrees

Random integers

randint(min, max) Returns a random integer between min and max, inclusive
randrange(limit) Returns a random integer from 0 up to but not including limit
randrange(start, limit) Returns a random integer from start up to but not including limit

Random floating-point numbers

random() Returns a random floating-point number in the range between 0 and 1
uniform(min, max) Returns a random floating-point number between min and max

Random functions on sequences

choice(seq) Returns a random element from the specified sequence
sample(seq, k) Returns a list with k elements random chosen from seq without replacement
shuffle(list) Rearranges the list in a random order

Initialization functions

seed() Randomizes the internal number generator
seed(k) Sets the internal state of the random number generator so that it generates the same sequence for any specific value of the integer k

String Methods

Finding patterns

str.find(pattern) Searches the string str for the string pattern, starting at the beginning of str. Returns the first index at which the pattern appears, or -1 if not found
str.find(pattern, k) Same as abov, but starts the search at index k
str.rfind(pattern) Searches backward in str for the last instance of pattern, starting at the end of str. Returns the last index at which the pattern appears, or -1 if not found
str.rfind(pattern, k) Same as above, but starts at index k
str.startswith(prefix) Returns True if str stars with the characters in prefix
str.endswith(suffix) Returns True if str ends with the characters in suffix

Creating transformed strings

str.lower() Returns a copy of str with all letters converted to lowercase
str.upper() Returns a copy of str with all letters convert to uppercase
str.capitalize() Returns a lowercase copy of str, but with the first letter capitalized
str.lstrip() Returns a copy of str aftr rmoving any whitspace characters from the left side
str.rstrip() Returns a copy of str after removing any whitespace characters from the right side
str.strip() Returns a copy of str after removing any whitespace characters from both sides
str.replace(old, new) Returns a copy of str after replacing all instances of the string old with the string new
str.replace(old, new, max) Returns a copy of str after replacing max instances (starting from the beginning) of the string old with the string new

Testing for character properties

str.isalpha() Returns True if str is non-empty and contains only letters
str.isdigit() Returns True if str is non-empty and contains only numeric digits
str.isalnum() Returns True if str is non-empty and contains only letters or digits
str.islower() Returns True is str has at least one letter and all letters are lowercase
str.isupper() Returns True if str has at least one letter and all letters are uppercase
str.isspace() Returns True if str is non-empty and contains only whitespace characters (e.g. space, tab, or newline)

Formatting Strings

str.center(width) Returns a copy of str centered in a field of the specified width
str.ljust(width) Returns a copy of str flush to the left in a field of the specified width
str.rjust(width) Returns a copy of str flush to the right in a field of the specified width

Portable Graphics Library

GWindow(width, height) Creates a new Gwindow object of the specified size.
gw.get_width() Returns the width of the graphics window.
gw.get_height() Returns the height of the graphics window.
gw.add(obj) Adds the object to the graphics window.
gw.add(obj, x, y) Repositions the object to (x,y) and adds it to the graphics window.
gw.remove(obj) Removes the given object from the graphics window.
gw.clear() Removes all objects from the graphics window.
gw.get_element_at(x, y) Returns the topmost graphical object covering the point (x,y). If no such object exists, then None is returned.
gw.add_event_listener(type, func) Prepares the window to respond to events of the specified type by calling func
gw.set_interval(func, delay) Prepares the window to repeatedly call func every delay milliseconds.
gw.set_timeout(func, delay) Prepares the window to call func once after waiting delay milliseconds.
GRect(x, y, width, height) Creates a GRect object with the specified dimensions.
GRect(width, height) Creates a GRect object at (0,0) with the specified dimensions.
GOval(x, y, width, height) Create a GOval object that fits inside the corresponding rectangle of the specified size.
GOval(width, height) Creates a GOval object in which the oval fits inside a rectangle of the specified size. The origin of the GOval is at (0,0).
GLine(x1, y1, x2, y2) Creates a GLine object connecting (x1, y1) to (x2, y2).
GLabel(str, x, y) Creates a GLabel object containing the specified string with its baseline origin at the point (x,y).
GLabel(str) Creates a GLabel object containing the specified string with its baseline origin at the point (0,0).
GArc(x, y, width, height, start, sweep) Creates a GArc object at the specified point and dimensions which starts at start degrees and extends counter-clockwise sweep degrees.
GPolygon() Creates an empty GPolygon object, which then needs vertices to be added.
GCompound() Creates an empty GCompound object, into which other objects can then be added.

Methods that control the location

object.set_location(x, y) Sets the location of this object to (x,y).
object.move(dx, dy) Moves the object by the displacements dx and dy.
object.move_polar(r, theta) Moves the object r pixels in the direction of theta.

Methods that control the appearance

object.set_color(color) Sets the color used to display this object.
object.set_line_width(width) Sets the width of the lines (in pixels) used to draw the object.
object.set_visible(flag) Sets whether the object is visible on the window, where flag is a boolean.
object.rotate(theta) Rotates the object theta degrees about its origin.
object.scale(sf) Scales the object by sf both horizontally and vertically.

Methods that control the stacking order

object.send_backward() Moves this object one step backward in the stacking order.
object.send_forward() Moves this object one step forward in the stacking order.
object.send_to_back() Moves this object all the way to the back of the stacking order.
object.send_to_front() Moves this object all the way to the front of the stacking order.

Methods that return object properties

object.get_x() Returns the x coordinate of the object.
object.get_y() Returns the y coordinate of the object.
object.get_width() Returns the width of the object.
object.get_height() Returns the height of the object.
object.get_color() Returns the color used to display this object.
object.get_line_width() Returns the width of the lines used to draw the object.
object.is_visible() Returns a boolean indicating whether the object is currently visible.
object.contains(x, y) Returns a boolean indicating whether the point (x,y) is inside the object.

GFillableObjects include GRects, GOvals, GArcs, and GPolygons

object.set_filled(bool) Sets whether the object is filled according to the boolean bool.
object.set_fill_color(color) Sets the color used to fill the interior of the object.
object.get_fill_color() Returns the color used to display the interior of the object.
object.is_filled() Returns a boolean indicating whether the object is currently filled.
object.set_font(str) Sets the font for the label. The format of the font specification is a CSS string as described in the text.
object.set_label(str) Sets the text of the label to the provided string.
object.get_label() Returns the text of the label as a string.
object.get_ascent() Returns the font ascent (the maximum distance above the baseline a character extends).
object.get_descent() Returns the font descent (the maximum distance below the baseline a character extends).
object.set_start_point(x, y) Changes the starting point of the line to (x,y) without changing the end point.
object.set_end_point(x, y) Changes the end point of the line to (x, y) without changing the starting point.
object.get_start_point() Returns the coordinate of the starting point of the line as a GPoint object, which is a type of GObject.
object.get_end_point() Returns the coordinate of the ending point of the line as a GPoint object, which is a type of GObject.
object.set_size(width, height) Sets the size of the object to the specified width and height.
object.set_bounds(x, y, width, height) Sets both the location of the object and the size of the object to the newly indicated values.
arc.set_start_angle(start) Sets the start angle of the arc to start degrees.
arc.get_start_angle() Returns the start angle of the arc in degrees.
arc.set_sweep_angle(sweep) Sets the sweep angle of the arc to sweep degrees.
arc.get_sweep_angle() Returns the sweep angle of the arc in degrees.
arc.get_start_point() Returns the starting point of the arc as a GPoint, which is a type of GObject.
arc.get_end_point() Returns the ending point of the arc as a GPoint object, which is a type of GObject.
poly.add_vertex(x, y) Adds a vertex at the point (x,y) in the GPolygon coordinate system.
poly.add_edge(dx, dy) Adds a vertex shifted by dx and dy from the previous vertex location.
poly.add_polar_edge(r, theta) Adds a vertex shifted by r units in the direction of theta from the previous vertex location.
poly.get_bounds() Returns a GRect object of the bounding rectangle of the polygon (the smallest rectangle that can contain the polygon).

List Methods

Methods that leave the original list unchanged

list.index(value) Returns the first index matching value. This method raises a ValueError exception if no match is found.
list.index(value, start) Starting from the start index, returns the next index matching value. This method raises a ValueError exception if no match is found.
list.count(value) Returns the number of times that value appears in the list.
list.copy() Returns a shallow copy of the original list.

Methods that add or remove elements

list.append(value) Adds the element value to the end of the list.
list.extend(list2) Adds the elements of list2 to the end of the list.
list.insert(index, value) Inserts the element value before the specified index position (so that the value is position at that index).
list.remove(value) Removes the first instance of value from the list, raising a ValueError exception if it does not appear.
list.pop() Removes and returns the last element of the list.
list.pop(index) Removes and returns the element at the specified index position.
list.clear() Removes all elements from a list.

Methods that reorder the elements of a list

list.reverse() Reverses the order of the elements in the list.
list.sort() Sorts the elements of the list in ascending order.
list.sort(key) Sort the elements of the list in ascending order according to a particular key.
list.sort(key, reverse=True) Sort the elements of the list in descending order according to a particular key.

String methods that involve lists

str.split() Splits the string str into a list of substrings by dividing it at each occurrence of a whitespace character.
str.split(separator) Splits the string str into a list of substrings by dividing it at each instance of the string separator.
str.splitlines() Splits the string str into a list of substrings by dividing it at each line break.
sep.join(list) Joins the elements of list into a string using sep to separate the elements in the string.