Skip to content

Instantly share code, notes, and snippets.

@dkirkby
Last active April 30, 2025 16:21
Show Gist options
  • Save dkirkby/56efb119c8fc737dc3065938e974e634 to your computer and use it in GitHub Desktop.
Save dkirkby/56efb119c8fc737dc3065938e974e634 to your computer and use it in GitHub Desktop.
Python Cheat Sheet

P53 Python Cheatsheet

Expressions

Basic Types

  • bool: yes = True, no = False
  • int: year = 2001
  • float: g = 9.81, G = 6.67e-11
  • str: name = "Welcome to 'P53'"

Collection Types

  • list: vec = [ 1.23, -0.5, 2 ]
  • tuple: date = (1999, 12, 31)

Arithmetic Operators

  • 1 + 1 = 2, -1 - 1 = -2
  • "hi" + "world" = "hiworld"
  • 2 * 3 = 6, 3 / -2 = -1.5
  • "hi" * 3 = "hihihi"
  • power: 2 ** 3 = 8
  • modulus: 7 % 3 = 1
  • floor div: 7 // 3 = 2

Comparison Operators

  • equality: 1 + 1 == 2 is True
  • inequality: 1 + 1 != 2 is False
  • 2 >= 1 is True, 2 > 2 is False
  • 2 <= 1 is False, 2 < 3 is True

Logical Operators

  • True and False is False
  • True or False is True
  • not True is False
  • 2 >= 1 or 2 > 2 is True

Indexing

  • now = ['Apr',13,[9,15,'am']]
  • now[0] is 'Apr'
  • now[1] and now[-2] are 13
  • now[2] is [9,15,'am']
  • now[2][-1] is 'am'

Slicing

  • digits=[0,1,2,3,4,5,6,7,8,9]
  • digits[:4] is [0,1,2,3]
  • digits[6:] is [6,7,8,9]
  • digits[4:6] is [4,5]
  • digits[2:8:2] is [2,4,6]
  • len(digits[2:3]) is 1

List Comprehension

  • [2*n+1 for n in range(5)]
  • [n-1 for n in range(5) if n%2==1]

Tuples

  • can be indexed and sliced like lists
  • cannot be modifed after creation
  • tuple(1, 2, 3)
  • tuple([1, 2, 3])
  • (1, 2, 3)
  • 1, 2, 3
  • (1,) has length 1
  • (,) has length 0

String Interpolation

a = 1
b = 3
print(f'a={a}, b={b}, a/b={a/b:.2f}')

Control Flow

if ?:
    pass
elif ?:
    pass
else:
    pass
while ?:
    pass
for value in values:
    pass
for i, value in enumerate(values):
    pass
  • break: break out of enclosing loop
  • continue: jump to next iteration

Functions

Built-In

  • utility: print,help
  • numeric: abs,min,max,pow,round
  • types: bool,int,float,str,list,tuple
  • iterable: len,enumerate,range

Math Library

  • import math
  • math.sin(math.pi / 2) is 1.0

User-Defined Functions

def myfunc(x, y):
    return x + y, x - y

assert myfunc(1, 2) == (3, -1)
def combine(x1, x2, c1=1, c2=1):
    return c1 * x1 + c2 * x2

assert combine(2, 3) == 5
assert combine(2, 3, c1=0.5) == 4
assert combine(2, 3, c2=2) == 8

Numerical Python

  • import numpy as np

Array Creation

  • x = np.array([0.0,0.2,0.4,0.8,1.0])
  • x = np.linspace(0, 1, 5)
  • np.zeros((2, 3)) is 2x3 array of zeros
  • np.ones((3, 2, 3)) is 3x2x3 array of ones

Array Attributes

  • x.shape is tuple of dimensions
  • x.dtype is type of each element value
  • x.size is total number of elements

Math

  • trig: sin,cos,tan,asin,acos,atan,atan2
  • angles: deg2rad,rad2deg
  • constants: pi,e,inf,nan

Random Numbers

  • rng = np.random.default_rng(seed=123)
  • rng.uniform(lo, hi, size=(3, 2, 3))
  • rng.normal(loc=mu, scale=stddev, size=9)

Plotting

  • import matplotlib.pyplot as plt
  • plt.plot(x, y, 'r-')
  • plt.hist(z, bins=50, range=(-5,5))
  • colors: r(ed),g(reen),b(lue),(blac)k
  • line styles: - -- :
  • symbols: . o + x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment