Python Syntax Cheatsheet


See also: Commonly Used Python Modules/Functions Cheatsheet

Created a cheat sheet for my Python scripting work :D :

Basic Syntax

# this is a comment

Variables:

myVar = 100
myVar = 0×64
myVar = 0o144 #octal
myVar = 0b01100100
intDiv = 11 // 2 #equals 5
powerVal = 2 ** 2 #equals 4

myString = ‘hello’ “world”
myString = ‘hello’ + “world”
myString = r“Special chars will not be escaped, e.g. \r\n”
world = myString[5:]
wo = myString[5:7]
myUnicodeString = “\u3041″ #code-point in hex
var1, var2 = “hello”, “World”

Flow Control:

if :
  do something
elif :
  do something
else:
  do something

for i in range(10):
  print(i)
else:
  print(“looped to the end!”)

while :
  do something
else:
  print(“looped to the end!”)
 

Functions

Function definitions

def myFunction(arg1, arg2):
  # do something
  return 123 # optional return statement

def defaultArgs(arg1=”hello”, arg2=”work”):
  # do something

def varArgs(*myVarArgs): # note that myVarArgs will be wrapped in tuple
  # do something

Function invocations

Keyword Arguments:
myFunc(arg1 = 1, arg2= 2)

Unpacking arguments list:
myList = [1,2]
myFunc(*myList)

Unpacking arguments dictionary:
myDict = {‘arg1′: 1, ‘arg2′: 2}
myFunc(**myDict)
 

Classes

Class definitions

class MyClass(Base1,Base2):
  myClassVar = 1

  def myClassFunc(arg1, arg2):
    #do something

  def __init__(self):
    super()
    self.instance_var_data = []

  …

#Note: there’s no private var in Python

Class Instantiation

var1 = MyClass()

Misc

isinstance(obj, int)

issubclass(bool, int)

 

Iterators & Generators

Iterators are classes that define the __iter__() and next() functions.

Iterators allow your class to be iterated via for …. in … statements

class MyIter:
  def __iter__(self):
    return self

  def next(self):
  #do something

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 index in range(len(data)-1,-1,-1):
    yield data[index]

for char in reverse(‘golf’):
  print(char)

 

Data Structures

Tuples

Tuples are immutable ordered sequences

myTuple = ()
myTuple = a, b, c
myTuple = (a, b, c)

myTuple[0] #a

Lists

myList = []
myList = [a,b,c,d]
myList.append(d)
myList2 = myList[:] # copy all elements
myList2 = myList[1:2] # copy the 2nd element
myList2 = myList[1:-1] # b,c

List comprehension:

mySquares = [x**2 for x in range(10)]
evenNumbers = [x for x in range(100) if x % 2 ==0]

Sets

Unordered collection with no duplicates

mySet = {a,b,c}
mySet = set() # NOTE: “mySet = {}” CREATES AN EMPTY DICTIONARY INSTEAD!!

Set operations: a – b, a | b, a & b, a ^ b (xor)

Dictionaries

Dictionaries are hash maps

myDict = dict()
myDict = {}
myDict = {“hello”: 123, “World”: “LOL”}
myDict["hello"] # 123

myDict.keys()

for k,v in myDict.items():
  print(k + “: ” + v)

Dict Comprehension: mySquares = {x:x**2 for x in range(10) if x % 2 == 0}

len(myList)

 

Exception Handling

try:
  #do something
  raise SomeException()
except ValueError:
  #do something
except ZeroDivisionError as err:
  #do something
except:
  #default event handling logic
else:
  #when no exception occurs
finally:
  #execute regardless if exception occurred or not

Exceptions derive from the Exception class:
class MyException(Exception):

 

Modules & Packages

“import” statement brings the module into the current scope

import sys
sys.byteorder #valid call

from sys import byteorder
byteorder #valid call

if __name == “__main__”:
  #this py file was executed directly
  import sys
else:
  #this py file was loaded as a module

Module search path:

  1. built-in module
  2. current dir
  3. PYTHONPATH env var

dir() #lists all the modules loaded and variables defined
dir(modulename) #lists all symbols defined in the module

Package is a specialized form of modules.
Any module that contains a __path__ attribute is considered a package
Subpackages are separated by “.”

 

Misc

str() 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 {food} was {adj}’.format(‘food’='spam’, ‘adj’='delicious’)

‘The value of pi is ~ %5.3f’ % (math.pi) #note: tuple

Serialization

Use the Pickle module:
  pickle.dump(x, fileobj)
 x = pickle.load(fileobj)

 

Bookmark and Share

- Lem

Tags: , , , , ,

Comments are closed.