Brief Python Documentation
Comments:
# anything after a hash is a comment.
Special Values:
True, False # boolean values
"....." or '.....' or '''.....'''' # strings (the last may include newlines)
anything surrounded by __ and __ is a System defined name
Variables:
place = value # assignment: put value into place
place, place, place = value, value, value # multiple assignment
global variable # declare variable global, not local
Operators:
+ - * / ** // % # arithmetic ** is power,
# // and % are integer division and remainder
< > <= >= # comparison
== !=
and, or, not # logical
# Note, 0, empty string/list/tuple are all treated as False
# almost everying else is treated as True
Input/Output;
print(val,val, ...) # print out values - must all be strings.
# Special args: sep=' ' and end='\n' for separator and end
input("prompt") # ask for user input and return as a string
Built-in functions
min(val,....), max(val,...) # take a sequence or tuple, or multiple arguments
abs(val), round(val)
float(val) int(val) # convert a string to a number
str(val) # convert a number or anything else to a string
range(i, j) # returns a sequence of integers from i to j-1
random() randint(a, b) choice(sequence) # requires: from random import *
Conditionals:
if condition :
statements
or (two-way)
if condition :
statements
else :
statements
or (multi-way, with as many elif's as you want)
if condition :
statements
elif condition :
statements
else :
statements
Loops:
while condition :
statements
for var in sequence : # ranges are particularly useful sequences
statements
break # get out of the for or while loop
continue # jump immediately to the next iteration
Defining Functions:
def name(param, param, ....) :
statements
return value # returns the value
Sequences: Strings, Lists, Ranges, Tuples:
names[i] # access i'th element of names
len(names) # number of items in sequence
n in names # true if names contains n (or a value equal to n) (substring for strings)
for n in name : # loop to process each value in a sequence
names[i:j] # the subsequence of names from i to j-1
names.index(n) # index of first occurrence of n in names
names1 + names2 # concatenate
Strings only:
str.capitalize() str.lower() str.upper()
str.startswith(substr)
str.isnumeric
str.split(" ") # return list of words in string
str.format(arg, arg, ...) # str is a format string; the arg's are substituted
# into the {...} in the string. The {} can contain
# format control codes, eg .3f for 3 decimal places
Ranges
range(start, stop) : # sequence from start to stop-1
range(stop) : # sequence from 0 to stop-1
range(start, stop, step) : # sequence from start by step up to stop
Lists only:
names = [] # empty list
names = ["john", "james", "jeremy", "justin"]
names[i] = "julia" # replace the i'th value by "julia"
del names[i] # remove the ith element
names1.append("julia") # add "julia" at the end of the list
names.extend(names2) # add every item in names2 to the end of the list
names.insert(i, "julia") # insert "julia" at position i, moving later items up
names.remove("julia") # remove the first occurrence of "julia" from the list
Tuples
flower = (x, y, 10) # a tuple of three values "stuck together"
flower[1] # access elements like any sequence "
# can't modify a tuple once constructed
Graphical Output:
from tkinter import * # make everything in the tkinter module available.
window = Tk()
canvas = Canvas(window, width=450, height=300, bg="white")
canvas.pack()
canvas.delete(ALL)
canvas.create_rectangle(left, top, right, bottom,
fill="orange", outline="black")
canvas.create_oval(left, top, right, bottom, fill="red")
canvas.create_line(x0, y0, x1, y1, ..., fill="red")
canvas.create_text(x, y, text="the message")
canvas.create_image(left, top, image=PhotoImage(file="image.gif"))
canvas.update()
Allows drawing on a window with "turtles" (like logo, and Scratch sprites).
import turtle
window = turtle.Screen() # make a window for the turtles to draw on
ben = turtle.Turtle() # make a turtle
ben.forward(20) # move it forward
ben.left(45) # turn it 45 degrees to the left
ben.penup() # lift the pen up
Some of the functions on turtles:
forward(d), backward(d), right(d), left(d), setposition(x, y), setheading(d)
pendown(), penup(), pensize(s), pencolor(c), shape(s)
Some of the functions on the screen:
clear() # clear the screen
delay(time) # set the delay between actions
turtles() # returns the current list of turtles
textinput(prompt) numinput(prompt) # dialog boxes to get string or number input
onkey(function, key) # make the function be called when the key (a string) is pressed
Event Input
moveButton = Button(window, text="Move", command=doMove) # A button that calls doMove
moveButton.pack()
label = Label(window, text="Name: ")
label.pack()
name = Entry(window) # Text entry box that user can type in
name.pack()
name.get() # get the current string out of the entry box
canvas.bind("<Button-1>", mousepress) # name of function to call
canvas.bind("<ButtonRelease-1>", mouserelease)
def mousepress(event):
pressX = event.x
pressY = event.y
Files
open("file name", mode='r' ) # open a file, mode is 'r' for reading, 'w'
# for writing new 'a' for appending
file.write(string) # write a string to a file
print(values file=file) # write out values to a file,
file.readline() # read one line from file as a string
file.read(n) # read n characters from file as a string
Classes and Objects
When defining a new class of object, you need do
- give the name of the class
- define a constructor function (called __init__)
- specify any "fields" that the objects will have to hold their data
- specify any functions that can be called on the objects
Note that all the functions (including the constructor) must have a first
parameter called self, which will contain the object itself.
Fields of the object can be accessed using self.fieldname
class Eye() : # define a new class of objects
# define the constructor for making new objects of this class
def __init__(self, x, y, colr) :
self.size = 10 #give an initial value to the size field
self.colour = colr #store the colr in the colour field
self.x = x #store the position in the x and y fields
self.y = x
def move(self, stepX, stepY) : #define a move method that changes object on a canvas
self.x = self.x + stepX
self.y = self.y + stepY
def grow(self) : #define a grow method that makes the object bigger
self.size = self.size + 10
def draw(self, canvas) : #define a draw method that draws the object on a canvas
wd = self.size
ht = wd/2
rad = self.size/4
smallrad = rad/2
canvas.create_oval(self.x-wd, self.y-ht, self.x+wd, self.y+ht, fill=self.colour)
canvas.create_oval(self.x-rad, self.y-rad, self.x+rad, self.y+rad, fill="black")
#Elsewhere in program, create two objects and draw them:
first = Eye(100, 100, "green")
secnd = Eye(200, 100, "red")
first.draw(canvas)
secnd.draw(canvas)
canvas.update()
:
for i in range(20)
canvas.delete(ALL)
first.grow()
secnd.move(20, 50)
first.draw(canvas)
secnd.draw(canvas)
canvas.update()