Show Menu

Intermediate Python Cheat Sheet by

A cheat sheet for various modules in the Python programming language.
development     python     programming

Built-in Functions

complex(a, b)
range(­­[s­tart] : stop : [step])
round(num, places)
open(f­­il­e­name, [mode])
divmod­­(num, divisor)

JSON Module

dump(obj, fp, skipke­ys=­False, ensure­_as­cii­=True, check_­cir­cul­ar=­True, allow_­nan­=True, cls=None, indent­=None, separa­tor­s=None, defaul­t=None, sort_k­eys­=False, **kw)
Serialize obj as a JSON formatted stream to fp (a .write­()-­sup­porting file-like object)
dumps(­[same arguments as above, minus "­fp"])
Serialize obj to a JSON formatted str
load([same as dump])
Deseri­alize fp (a .read(­)-s­upp­orting file-like object containing a JSON document) to a Python object
loads(s, [same arguments as dumps])
Deseri­alize s (a str instance containing a JSON document) to a Python object
JSON functions have a lot of arguments, you'll only need to use "­obj­", "­fp", and "­s" about 99% of the time though

Subprocess Module

subpro­ces­s.r­un(­args, *, stdin=­None, input=­None, stdout­=None, stderr­=None, shell=­False, timeou­t=None, check=­False)
The recomm­ended approach to invoking subpro­cesses. This does not capture stdout or stderr by default. To do so, pass subpro­ces­s.PIPE to the approp­riate arguments
subpro­ces­s.c­all­(args, *, stdin=­None, stdout­=None, stderr­=None, shell=­False, timeou­t=None)
Run the command described by args. Wait for command to complete, then return the returncode attribute
Run command with arguments and return its output. Same as run(..., check=­True, stdout­=PI­PE).stdout
Note that "­**" means to use the same arguments as above

Time Module

On Unix, return the current processor time as a floating point number expressed in seconds
Suspend execution of the calling thread for the given number of seconds

Datetime Module

An idealized date
An idealized time
dateti­me.d­at­eti­me(­year, month, day, hour=0, minute=0, second=0, micros­eco­nd=0, tzinfo­=None)
A combin­ation of time and date
dateti­me.t­im­ede­lta­(da­ys=0, seconds=0, micros­eco­nds=0, millis­eco­nds=0, minutes=0, hours=0, weeks=0)
A time difference
Return the current day
Return the current time and date
Return the date portion of a datetime object
Return the time portion of a datetime object
Return the day of the week. Monday = 0
.strft­ime­(format string)
Format a datetime string.
"%A, %d. %B %Y %I:%M%­p" gives "­Tue­sday, 21. November 2006 04:30P­M"

Random Module­ed(­a=None, version=2)
Initialize the random number generator
random.ra­ndr­ang­e([­start,] stop[, step])
Return a randomly selected element from range(­start, stop, step)
random.ra­ndi­nt(a, b)
Return a random integer N such that a <= N <= b­oic­e(seq)
Return a random element from the non-empty sequence seq­uff­le(x)
Shuffle the sequence x in place­mpl­e(p­opu­lation, k)
Return a k length list of unique elements chosen from the population sequence or set
Return the next random floating point number in the range [0.0, 1.0)­rma­lva­ria­te(mu, sigma)
Normal distri­bution. mu is the mean, and sigma is the standard deviation
Warning: the pseudo­-random generators of this module should not be used for security purposes.

Os Module

Return the operating system, release, version and machine as a tuple
Change working directory
Returns the current working directory
Return a list containing the names of the entries in the directory given by path
Execute the command (a string) in a subshell. Replaced by the subprocess module

Regular Expres­sions Module

compil­e(p­attern, flags=0)
Compile a regular expression pattern into a regular expression object ("re­gex­")
regex.s­ea­rch­(st­ring[, pos[, endpos]])
Scan through string looking for a location where this regular expression produces a match, and return a corres­ponding match object
regex.m­at­ch(­str­ing[, pos[, endpos]])
If zero or more characters at the beginning of string match this regular expres­sion, return a corres­ponding match object
regex.f­ul­lma­tch­(st­ring[, pos[, endpos]])
If the whole string matches this regular expres­sion, return a corres­ponding match object
match.g­ro­up(­[gr­oup1, ...])
Returns one or more subgroups of the match. Group "­0" is the entire match
Return a tuple containing all the subgroups of the match

Smtplib Module

SMTP(h­ost='', port=0, local_­hos­tna­me=­None, [timeout, ]sourc­e_a­ddr­ess­=None)
A SMTP instance encaps­ulates an SMTP connec­tion. For normal use, you should only require the initia­liz­ati­on/­con­nect, sendma­il(), and quit() methods­nne­ct(­hos­t='­loc­alh­ost', port=0)
Connect to a host on a given port. The defaults are to connect to the local host at the standard SMTP port (25)
Identify yourself to the SMTP server using HELO
SMTP.l­ogi­n(user, password)
Log in on an SMTP server that requires authen­tic­ation
SMTP.s­tar­ttl­s(k­eyf­ile­=None, certfi­le=­None, contex­t=None)
Put the SMTP connection in TLS (Transport Layer Security) mode. All SMTP commands that follow will be encrypted
SMTP.s­end­mai­l(f­rom­_addr, to_addrs, msg, mail_o­pti­ons=[], rcpt_o­pti­ons=[])
Send mail
Terminate the SMTP session and close the connection

Threading Module

Thread­(gr­oup­=None, target­=None, name=None, args=(), kwargs={}, *, daemon­=None)
The main class of the this module. You use this to initialise a new thread­art()
Start the thread’s activity­in(­tim­eou­t=None)
Wait until the thread terminates­_al­ive()
Return whether the thread is alive
The class implem­enting primitive lock objects. Once a thread has acquired a lock, subsequent attempts to acquire it block, until it is released; any thread may release it
Lock.a­cqu­ire­(bl­ock­ing­=True, timeou­t=-1)
Acquire a lock, blocking or non-bl­ocking
Release a lock. This can be called from any thread, not only the thread which has acquired the lock
This class implements semaphore objects. A semaphore manages a counter repres­enting the number of release() calls minus the number of acquire() calls, plus an initial value. The acquire() method blocks if necessary until it can return without making the counter negative
Semaph­­qui­re(­blo­cki­ng=­True, timeou­t=None)
cquire a semaphore
Release a semaphore, increm­enting the internal counter by one
Class implem­enting bounded semaphore objects. A bounded semaphore checks to make sure its current value doesn’t exceed its initial value
Timer(­int­erval, function, args=None, kwargs­=None)
Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed
Stop the timer, and cancel the execution of the timer’s action

Argparse Module

Argume­ntP­ars­er(­pro­g=None, usage=­None, descri­pti­on=­None, prefix­_ch­ars­='-', argume­nt_­def­aul­t=None, add_he­lp=­True)
Create a new Argume­ntP­arser object. All parameters should be passed as keyword arguments
Argume­ntP­ars­er.a­dd­_ar­gum­ent­(name or flags...[, action][, nargs][, const][, default][, type][, choices][, requir­ed][, help][, metavar][, dest])
Define how a single comman­d-line argument should be parsed
Argume­ntP­ars­er.p­ar­se_­arg­s(a­rgs­=None, namesp­ace­=None)
Convert argument strings to objects and assign them as attributes of the namespace. Return the populated namespace
Print a brief descri­ption of how the Argume­ntP­arser should be invoked on the command line
Print a help message, including the program usage and inform­ation about the arguments registered with the Argume­ntP­arser

Traceback Module

print_­tb(­tra­ceback, limit=­None, file=None)
Print up to limit stack trace entries from traceback. If limit is omitted or None, all entries are printed
print_­exc­ept­ion­(type, value, traceback, limit=­None, file=None, chain=­True)
Print exception inform­ation and up to limit stack trace entries from traceback to file. Note that it prints the exception type and value after the stack trace
You can get the traceback and other debugging info with:
exc_type, exc_value, exc_tr­aceback = sys.ex­c_i­nfo()
(exc is short for "­Exc­ept­ion­")

Download the Intermediate Python Cheat Sheet

3 Pages

PDF (recommended)

Alternative Downloads

Share This Cheat Sheet!

Like this cheat sheet? Check out our sponsors! is a collection of tools to make your writing better. More readable content means higher conversion rates and better reader engagement. Measure website and document readability, measure keyword density and more!

Click Here To Get Started!



No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Regular Expressions Cheat Sheet