Python Cheatsheet
Here's a collection of some useful pieces of Python code. This cheatsheet is designed to help you quickly look up how to do common, useful things and hopefully it clears up confusion about problems you may run into:
Also, here's a great external reference that provides an excellent list of tips and tricks in Python. Lots of the tips are great and you'll use right away. Some tips relate to advanced material or features that we won't use. Simply ignore anything that isn't immidiately beneficial to you.
30 Essential Python Tips and Tricks
Numbers
Force integer division with //
Import the random
library to gain access to all sorts of nice methods. Choose a random float number from 0.0 up to but not including 1.0.
Choose an integer from 2 up up and including 10.
if / else if / else Statements
Python uses silly spellings for "else if". Write it as elif
.
User Input
Write programs that allow users to type in input from the terminal. Everything the user inputs is returned as a string. Use the int
function to convert it to an integer.
Multiple Variable Assignment!
Ever have an array, or two variables and try to swap them, then find out that one value stomped the other? Python's got your back.
Classically you would need to use a third variable as a temporary variable to store one value while the second value overwrites the first.
Python supports multi-variable assignment. If you have N variables on the left side of an equals sign, and N values on the right side then Python automatically unpacks the values and stores them in the two variables simultaneously.
Strings
Strings have some different method names than JavaScript. Remember to use len()
to find out the length of something.
Fire up the ipython3
shell to play with things and see what they have. Create a variable s
equal to any string value, then types s.
and press TAB to have the ipython shell prompt you with useful auto-complete method names.
Strings support awesome Python "slice notation."
Don't forget about f-strings
for their awesome formatting potential!
Lists
Lists (arrays) also support the same slice notation!
Use the for foo in bar:
syntax to iterate through every item with a for each loop.
Use the enumerate
function to count the items as they pass through the for each loop.
Use the range
function if you just want to make a for loop that counts up to something. Iterating over a range with a for loop is a convenient way to get access to an i
variable that you want to interact with.
Range takes integers for min
, max
and step
to determine where to start, where to end, and how big of a step to take each time.
Run a for loop that starts at 1 and goes to the end of the length of the array. Starting at 1 guarantees that we'll be able to safely access the zero index and never exceed the length of the array.
Create an array of fixed size. Create an array from a range of numbers. The range
function excludes so we add one. Also, range
doesn't return a list itself, so we pass it to the list
function to convert the sequence it returns into an actual list.
Dictionaries (or hash maps, or "javascript objects")
Python is picky about the key value. If the key value is a string then it must be wrapped in quotation marks. Because, you know, it's a string.
Access key/value pairs with brackets. Use a for loop to iterate over the keys in a dictionary and use that key to access the values.
The for loop above prints out:
If you try to access a dictionary at a key that doesn't exist then the program will crash and you'll see an error:
The defaultdict
from the standard collections
library is a very useful dictionary implementation that can be configured to prevent that nasty KeyError
and return a default value.
Let's say we want to count up letters in a string. We'll use a dictionary to map letter -> count pairs. Each letter has it's own count. The defaultdict
allows us to express, "if the key isn't in the dictionary then return an integer".
You need to import the defaultdict from the collections library to use it.
That code prints out something like this:
Last updated