I’m taking a class on Python and thought it would be helpful to compile my own “cheat sheet” of commands, functions, and common constructions that might be useful in the future. Following the mantra of “Do Good Work in Public” I’m posting it here.
Basic Stuff
Functions
Functions are a type of a Python object that can take parameters and can return something (a number, value, etc.) Basic design:
def functionname(parameter1, parameter2...):
statements
Repetition
Use a for loop to do something many times. Example
for i in range(10):
do something
This does something ten times. This uses the range function which can be formatted in three ways
- range(stop)
- range(start, stop)
- range(start, stop, step)
Relational Operators
Table from: http://pymbook.readthedocs.org/en/latest/operatorsexpressions.html
| Operator | Meaning |
| < | Is less than |
| <= | Is less than or equal to |
| > | Is greater than |
| >= | Is greater than or equal to |
| == | Is equal to |
| != | Is not equal to |
Selection Statements
if <condition>:
<statements>
else:
<statements>
- The “else” statement is not necessary; an if statement can stand alone
- Nesting selection statements is also fine – just indent appropriately.
- A “tail nesting” is when all the nesting occurs within the last else. Python provides the shortcut elif to address this situation.
String/List Functions
Indexing - [] - Access an element in a sequence Concatenation - + - Combine sequences together Repetition - * - Repeated concatenation Membership - in / not in - Asks whether an item is in a sequence / asks whether an item is not in a sequence. Length - len - Asks the number of items in a sequence Slicing- [:] - Extracts a part of a sequence.
There are also lots of ways to format strings – see table 3.2.
List Methods
append - listname.append(item) - adds a new item to the end of the list insert - listname.insert(i, item) - inserts an item at the i spot in the list pop - listname.pop() - removes and returns the last item from the list pop - listname.pop() - removes and returns the (i) item from the list. sort - listname.sort() - modifies a list to be sorted. reverse - listname.reverse() - modifies a list in reverse order. index -
Accumulator Function/Structure
Example. See page 95
Shortcut!
These do the same thing!
num = num +1 num += 1
Data Storage Options aka Collections
Strings
Strings are collections of stuff enclosed in quotation marks. For example, “Andy Meyer” is a good Python string. You can also retrieve things strings using the index. Strings cannot be changed; you can only point somewhere else.
nameString = "Andy Meyer" nameString[3] would return "y" because the character "y" is in the third index position.
Lists
List are like strings…but also different in several ways:
- List are enclosed in square brackets [].
- Can be heterogeneous (can store numbers, string, characters, etc.)
- List are mutable – they can be changed and updated. Items can be added and deleted.
nameList = ["Andy","Meyer", 30] nameList[1] will return "Meyer" because that is the item in index position 1.
There are a lot of list methods. See table 4.2 on page 125.
Dictionaries
Dictionaries are unordered, associative collections that associate keys with values. Dictionaries use curly brackets {} and follow this formula {key, value}
agedictionary = {"Andy":30}
You can do cool stuff with dictionaries!
agesdictionary["Jim"]=31 # This adds a new entry (key, value) to the dictionary. agesdictionary["Andy"] # this would return the value (30) associated with that key.
Working with Files
Three concepts:
- File name = the name of a file as a string
- File handler = the
- Contents of the file =
Examples!
filename = 'filename.txt'
filehandle = open(filename, "r") # this opens the file.
filehandle = open("anotherfilename.txt","w") # this opens the
contentsofthefile = filehandle.read()
Read the File
filename.read() = reads and returns the whole file as a single text string filename.read(n) = reads and returns the first n characters as a single text string filename.readline() = reads and returns the file one line at a time. # You can iterate this and read an entire file, line by line. filename.readlines() = reads and returns a list - each line is a seperate item in the list. ### filename.seek(n) = seeks out the nth place in a document.