See also: Commonly Used Python Modules/Functions Cheatsheet
Created a cheat sheet for my Python scripting work
:
Basic Syntax# this is a comment Variables: myVar = 100 myString = ‘hello’ “world” Flow Control: if for i in range(10): while FunctionsFunction definitions def myFunction(arg1, arg2): def defaultArgs(arg1=”hello”, arg2=”work”): def varArgs(*myVarArgs): # note that myVarArgs will be wrapped in tuple Function invocations Keyword Arguments: Unpacking arguments list: Unpacking arguments dictionary: ClassesClass definitions class MyClass(Base1,Base2): def myClassFunc(arg1, arg2): def __init__(self): … #Note: there’s no private var in Python Class Instantiation var1 = MyClass() Misc isinstance(obj, int) issubclass(bool, int)
Iterators & GeneratorsIterators are classes that define the __iter__() and next() functions. Iterators allow your class to be iterated via for …. in … statements class MyIter: def next(self): Generators can also be used in for .. in .. statements, but they use the yield keyword to pass control instead. I.e. “automatic” state saving. def reverse(data): for char in reverse(‘golf’):
|
Data StructuresTuples Tuples are immutable ordered sequences myTuple = () myTuple[0] #a Lists myList = [] List comprehension: mySquares = [x**2 for x in range(10)] Sets Unordered collection with no duplicates mySet = {a,b,c} Set operations: a – b, a | b, a & b, a ^ b (xor) Dictionaries Dictionaries are hash maps myDict = dict() myDict.keys() for k,v in myDict.items(): Dict Comprehension: mySquares = {x:x**2 for x in range(10) if x % 2 == 0} len(myList)
Exception Handlingtry: Exceptions derive from the Exception class:
Modules & Packages“import” statement brings the module into the current scope import sys from sys import byteorder if __name == “__main__”: Module search path:
dir() #lists all the modules loaded and variables defined Package is a specialized form of modules.
Miscstr() and repr() returns the string representation of an obj. classes can define the __str__() function string.rjust(2) Formatting strings ‘{0} and {1}’.format(‘spam’, ‘eggs’) ‘The value of pi is ~ %5.3f’ % (math.pi) #note: tuple Serialization Use the Pickle module:
|
- Lem
Tags: Cheatsheet, Development, programming, Programming Languages, Python, scripting

