Python: A Cheatsheet
Demonstration code is copied from an interactive Python session, including the “»>” prompt where we type in code lines, and “…” where we need to continue.
Variables and the Assignment Statement
A variable is a named container that holds a value. The assignment statement puts a value into a variable; the previous value is gone forever.
>>> x = 6*3
>>> print(x)
18
The expression on the right-hand side is evaluated, resulting in a value; the value is then stored into the variable on the left-hand side.
Datatypes
Values in Python are always of a certain type; the value assigned to a variable does not need to be the same type of the previous value of the variable. The built-in function type(e) will give you the type of value that the expression e results in (usually e is just a variable name).
>>> type(x)
<class 'int'>
Numeric types: int (integers), float (real values), and complex
Other basic types: bool (True or False), NoneType (only None), str (character strings, either in double quotes or single quotes)
>>> b = 9 > 10
>>> print(b)
False
>>> type(b)
<class 'bool'>
Sequences: range (integers), list (a list of modifiable values, use [] ), tuple (a sequence of unmodifiable values, use () ); all sequences can be indexed using [] notation and integer indices starting at 0; len(V) gives the length of sequence V. Note that strings are also sequences (of characters).
>>> r = range(3,7) # range example
>>> print(r)
range(3, 7)
>>> print(r[2])
5
>>> type(r)
<class 'range'>
>>> l = [7,8,9] # list example
>>> print(l)
[7, 8, 9]
>>> print(l[2])
9
>>> type(l)
<class 'list'>
>>> t = (6,7,8) # tuple example
>>> print(t)
(6, 7, 8)
>>> print(t[2])
8
>>> type(t)
<class 'tuple'>
>>> print(len(r),len(l),len(t))
4 3 3
>>> s = "Hello World" # string example
>>> print(s)
Hello World
>>> len(s)
11
>>> print(s[2])
l
Dictionary: dict – use {} with string keys (indices) and any type of values
>>> p = {'first':"Jon", 'last':"Cook"}
>>> print(p)
{'first': 'Jon', 'last': 'Cook'}
>>> type(p)
<class 'dict'>
>>> print(p['last'])
Cook
Other types: set, bytes, and others we do not explain here
Operators (Symbols for Computation)
Mathematical operators: + - * / are add, subtract, multiply, and divide; % is modulus (remainder); ** is exponentiation, // is integer division; the math library has many more higher math functions, like sine, cosine, logarithm, etc.
Comparison (relational) operators: == (equality), != (not equal), < (less than), > (greater than), <= (less than or equal), >= (greater than or equal); also is meaning ‘is same thing’ (use only with knowledge)
Logical operators: and (True if both sides are True), or (True if at least one side is True), not (True if following thing is False, but can also be used as ‘is not’)
Operators have a precedence order for evaluation – roughly ** then multiplicative then additive then comparison then logical. Use parentheses to control order of evaluation and to make complex expressions readable.
Nesting by Indentation
Python uses indentation (putting spaces at the beginning of a line of code) to control nesting – nested lines of code are in some way controlled or dependent on the unnested (or less nested) parent line above them. The parent line must end with a :
Conditionals: if-elif-else
The if statement provides conditional execution – the program only executes the true case. You can have multiple (or zero) elif cases, and can have just zero or one else case.
>>> x = 42
>>> y = 17
>>> if x < 100 and y > 20:
... print("the if-part!")
... elif x < 50:
... print("the elif (else-if) part!")
... else:
... print("the else part!")
...
the elif (else-if) part!
The For Loop: Counting and Item Iteration
The for loop repeats while automatically walking a variable down a sequence of values – each repetition of the loop uses the next value in the sequence. Any Python sequence can be used (and of course the sequence can be in a variable). Using range is the standard way to make a counting loop.
>>> for v in "Hello":
... print(v,end='-')
...
H-e-l-l-o-
>>> for v in [1,2,3]:
... print(v,end='-')
...
1-2-3-
>>> for v in range(4):
... print(v,end='-')
...
0-1-2-3-
A dictionary can be used but the variable is just the keys.
>>> for v in {'first':"Jon", 'last':"Cook"}:
... print(v)
...
first
last
General Looping: The While Loop
For repetition that is based on a generic condition, use a while loop.
>>> while x < y:
... print(x,y)
... x -= 1 # shorthand for x = x - 1
... y -= 3 # shorthand for y = y - 3
...
4 10
3 7
2 4
Functions: Organizing Code by Decomposition
A function is a piece of code that is given a name and then is used by calling it – using the function name in an expression. A function can be defined to use parameters – variables that are set to the argument values provided in the function call. Functions can return values or just act like procedures (non-value returning). The keyword def is used to define a function.
>>> def myProcedure(a,b):
... if a >= b:
... print(f"{a} is bigger than {b}!")
... else:
... print(f"{b} is bigger than {a}!")
...
>>> myProcedure(6,5)
6 is bigger than 5!
>>> myProcedure(9,3)
9 is bigger than 3!
A function that returns a value can be used in any expression.
>>> def myFunction(x,y,z):
... if x < y and x < z:
... v = y+z
... elif y < z:
... v = x+z
... else:
... v = x+y
... return v
...
>>> print(myFunction(4,6,7))
13
>>> print(myFunction(8,2,4))
12
>>> print(myFunction(9,1,7))
16
A Python Program File
A good template for a general Python program is shown below. Remember, lines (and partial end-of-lines) beginning with “#” are comments to be read by humans, not executed as part of the program. This template is mostly comments.
#!/usr/bin/python3
#
# A file header comment at the beginning is a good place to name and describe
# the Python program that is in this file.
# - special notes to someone using this program can be written here, so that
# the see it right at the top of the program file
#
#
# Library imports: effective programming in any language requires using
# its standard libraries; the Python "import" statement brings in library
# modules: see https://docs.python.org/3/library/index.html for a list of
# the standard libraries. Example imports are below
#
import math
import string
import datetime
#
# Next should come function definitions. Each function should have a
# comment header that describes what the function does
#
def myFunctionOne(param1,param2,...):
function body goes here, indented
#-------------------------------------------------------------
# Finally, the main program code should be the final part
# - it should have a comment header that clearly separates it
# from the stuff above, like this one does
#-------------------------------------------------------------
Main
Code
Goes
Here
The first line in the template above is “#!/usr/bin/python3”. Since it begins with “#” it is simply a Python comment line, but when this kind of line is the first line in a python script, it enables the file to be run directly as a command itself, on Linux, Unix, and MacOS systems. Windows is probably different. This line is never absolutely needed, we can always run the program by writing “python3 myprogram.py”, but if we use this line and set the permissions correctly, we can just run “myprogram.py” as a command itself. If you want to know more, go here.