Show Menu
Cheatography

Python 3 Basics Cheat Sheet Cheat Sheet (DRAFT) by

basic commands and operations in python 3

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Operators

Assignment
=
Arithmetic
+, -, *, /, %
Comparison
>, >=, <, <=, ==, !=
Logical
not, and, or

String operations (string s)

s.coun­t(s­ubs­tring)
Count occurences
s.find­(su­bst­ring)
Index of first occurence
s.join­(se­quence)
Concat­enate sequence
s.plit­([d­eil­imi­ter])
Split into list

List operations (list l, element e)

l.appe­nd(e)
Add e
l.remove
Remove e
l.pop(e)
Remove and return e
l.count(e)
Count occurences
l.reve­rse()
Reverse l
l.sort()
Sort l

Dictionary operations (dict d, key k)

d.clear
Clear d
d.get(k)
Return d[k]
d.keys()
Return keys in d
d.values()
Return values in d
d.items()
Return key-value pairs in d

File operations (file f)

f = open(path)
Open file at path as f
f.read()
Read f
f.read­line()
Read line from f
f.read­lines()
Return list of lines in f
f.write(s)
Write s to f
f.close()
Close f
When using:
with open(path) as f:
the file gets opened as f and closes after leaving the "­wit­h" statement
 

Base functions

int(), float(), str(), bool() ...
Type casting
len(data)
Return length of data
min(va­lues), 
max(values)
Minimum / Maximum
pow(x, y, [z])
x to the power y [mod z]
range(­start, stop, [step])
Ordered list
input(), print()
Console input/ output
filter­(fu­nction, iterable)
Filter iterable
map(fu­nction, iterable)
Map function onto iterable
id(object)
Unique object ID
round(n, [x])
Round n [x decimal places]
create your own functions with:
def functi­oname:

Control flow

if(cond): <co­de> else:
<code>
If-else statement
if(cond): <co­de> elif(c­ond): <co­de> else: <co­de>
If-els­eif­-else statement
for i in range(­[st­art], stop, [step]): <co­de>
For loop over range
for i in items: <co­de>
For loop over iterable
while(­cond): <co­de>
While loop
break
Exit loop
continue
Skip to next iteration
 

Object­-or­iented

class Person:
Class definition
x = Person­(age, height)
Object creation
x.age
Filed access
x.birt­hday()
Method access

List compre­hen­sions

List compre­hen­sions can be used to generate lists with the use of functions in just one line
S = [x**2 for x in range(10)]
M = [x for x in S if x % 2 == 0]
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)]
primes = [x for x in range(2, 50) if x not in noprimes]
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]

Module Import

import module
Imports a module
import module as x
Imports a module as x
from module import submodule
Imports specific submodule