A Comprehensive Python 3 Cheat Sheet

Using extracts from Learn Python in Y Minutes.

Maths

Integer Maths:

3  # => 3

# Math is what you would expect
1 + 1  # => 2  
8 - 1  # => 7  
10 * 2  # => 20  
35 / 5  # => 7

# Division is a bit tricky. It is integer division and floors the results
# automatically.
5 / 2  # => 2  

Floating point maths:

# To fix division we need to learn about floats.
2.0     # This is a float  
11.0 / 4.0  # => 2.75 ahhh...much better  

DIV Functions:

# Result of integer division truncated down both for positive and negative.
5 // 3     # => 1  
5.0 // 3.0 # => 1.0 # works on floats too  
-5 // 3  # => -2
-5.0 // 3.0 # => -2.0

Modulo Operation:

7 % 3 # => 1  

Exponentials:

# Exponentiation (x to the yth power)
2**4 # => 16  

Boolean Operations

Boolean Operators:

# Note "and" and "or" are case-sensitive
True and False #=> False  
False or True #=> True  

Boolean operators with ints:

0 and 2 #=> 0  
-5 or 0 #=> -5
0 == False #=> True  
2 == True #=> False  
1 == True #=> True  

Negating booleans with not:

not True  # => False  
not False  # => True  

Equating is

1 == 1  # => True  
2 == 1  # => False  

Inequality is !=

1 != 1  # => False  
2 != 1  # => True  

More comparrisons:

1 < 10  # => True  
1 > 10  # => False  
2 <= 2  # => True  
2 >= 2  # => True  

Comparrisons can be chained:

1 < 2 < 3  # => True  
2 < 3 < 2  # => False  

Don't use the equality "" symbol to compare objects to None. Use "is" instead:

"etc" is None  # => False
None is None  # => True  

Variables and collections

Python has a print statement:

print ("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you!  

The simplese way to get data from the console uses input():

input_var = input("Enter some data: ")  

If can be used as an expression:

"yahoo!" if 3 > 2 else 2  # => "yahoo!"

Control Flow

If statement:

if some_var > 10:  
    print "some_var is totally bigger than 10."
elif some_var < 10:    # This elif clause is optional.  
    print "some_var is smaller than 10."
else:           # This is optional too.  
    print "some_var is indeed 10."

For loop iterate over list. The example below prints
dog is a mammal cat is a mammal mouse is a mammal

for animal in ["dog", "cat", "mouse"]:  
    # You can use {0} to interpolate formatted strings. (See above.)
    print "{0} is a mammal".format(animal)

"range(number)" returns a list of numbers from zero to the given number
prints:
0 1 2 3

for i in range(4):  
    print i

"range(lower, upper)" returns a list of numbers from the lower number to the upper number
prints:
4 5 6 7

for i in range(4, 8):  
    print i

While loops go until a condition is no longer met.
prints:
0 1 2 3

x = 0  
while x < 4:  
    print x
    x += 1  # Shorthand for x = x + 1

Exceptions can be hanndled with a try/except block:

try:  
    # Use "raise" to raise an error
    raise IndexError("This is an index error")
except IndexError as e:  
    pass    # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):  
    pass    # Multiple exceptions can be handled together, if required.
else:   # Optional clause to the try/except block. Must follow all except blocks  
    print "All good!"   # Runs only if the code in try raises no exceptions
finally: #  Execute under all circumstances  
    print "We can clean up resources here"

Instead of using try/finally to cleanup resources you can use a with statement:

with open("myfile.txt") as f:  
    for line in f:
        print line
   

Functions

Use "def" to create new functions:

def add(x, y):  
    print "x is {0} and y is {1}".format(x, y)
    return x + y    # Return values with a return statement

Functions can be called with paramaters or keyword arguments:

# Calling functions with parameters
add(5, 6)   # => prints out "x is 5 and y is 6" and returns 11

# Another way to call functions is with keyword arguments
add(y=6, x=5)   # Keyword arguments can arrive in any order.  

We can do more fancy stuff with functions if we like!

# You can define functions that take a variable number of
# positional args, which will be interpreted as a tuple by using *
def varargs(*args):  
    return args

varargs(1, 2, 3)   # => (1, 2, 3)

# You can define functions that take a variable number of
# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):  
    return kwargs

# Let's call it to see what happens
keyword_args(big="foot", loch="ness")   # => {"big": "foot", "loch": "ness"}


# You can do both at once, if you like
def all_the_args(*args, **kwargs):  
    print args
    print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:  
    (1, 2)
    {"a": 3, "b": 4}
"""

# When calling functions, you can do the opposite of args/kwargs!
# Use * to expand positional args and use ** to expand keyword args.
args = (1, 2, 3, 4)  
kwargs = {"a": 3, "b": 4}  
all_the_args(*args)   # equivalent to foo(1, 2, 3, 4)  
all_the_args(**kwargs)   # equivalent to foo(a=3, b=4)  
all_the_args(*args, **kwargs)   # equivalent to foo(1, 2, 3, 4, a=3, b=4)

# you can pass args and kwargs along to other functions that take args/kwargs
# by expanding them with * and ** respectively
def pass_all_the_args(*args, **kwargs):  
    all_the_args(*args, **kwargs)
    print varargs(*args)
    print keyword_args(**kwargs)

Python has first class functions:

def create_adder(x):  
    def adder(y):
        return x + y
    return adder

add_10 = create_adder(10)  
add_10(3)   # => 13  

Creating classes

# We subclass from object to get a class.
class Human(object):

    # A class attribute. It is shared by all instances of this class
    species = "H. sapiens"

    # Basic initializer, this is called when this class is instantiated.
    # Note that the double leading and trailing underscores denote objects
    # or attributes that are used by python but that live in user-controlled
    # namespaces. You should not invent such names on your own.
    def __init__(self, name):
        # Assign the argument to the instance's name attribute
        self.name = name

        # Initialize property
        self.age = 0


    # An instance method. All methods take "self" as the first argument
    def say(self, msg):
        return "{0}: {1}".format(self.name, msg)

    # A class method is shared among all instances
    # They are called with the calling class as the first argument
    @classmethod
    def get_species(cls):
        return cls.species

    # A static method is called without a class or instance reference
    @staticmethod
    def grunt():
        return "*grunt*"

    # A property is just like a getter.
    # It turns the method age() into an read-only attribute
    # of the same name.
    @property
    def age(self):
        return self._age

    # This allows the property to be set
    @age.setter
    def age(self, age):
        self._age = age

    # This allows the property to be deleted
    @age.deleter
    def age(self):
        del self._age

Instantiate a class:

i = Human(name="Ian")  
print i.say("hi")     # prints out "Ian: hi"

j = Human("Joel")  
print j.say("hello")  # prints out "Joel: hello"  

We can call our class method:

i.get_species()   # => "H. sapiens"  

Change the shared attribute:

Human.species = "H. neanderthalensis"  
i.get_species()   # => "H. neanderthalensis"  
j.get_species()   # => "H. neanderthalensis"

We can call the static method:

Human.grunt()   # => "*grunt*"  

Update the property:

i.age = 42  

Get the property:

i.age # => 42  

Delete the property:

del i.age  
i.age  # => raises an AttributeError  

Built in Classes

String Class

Strings are created with " or ':

"This is a string."
'This is also a string.'  

Strings can be added too:

#Adding with +
"Hello " + "world!"  # => "Hello world!"
# Strings can be added without using '+'
"Hello " "world!"  # => "Hello world!"

Strings can be multiplied:

"Hello" * 3  #=> "HelloHelloHello"

Strings can be treated like a list of characters:

"This is a string"[0]  # => 'T'

Strings can be formatted like so:

# A newer way to format strings is the format method.
# This method is the preferred way
"{} is a {}".format("This", "placeholder")
"{0} can be {1}".format("strings", "formatted")
# You can use keywords if you don't want to count.
"{name} wants to eat {food}".format(name="Bob", food="lasagna")

List Class

Lists store sequences, and are defined like this:

li = []  

You can start with a prefilled list:

other_li = [4, 5, 6]  

And you can append items to the end of a list:

li.append(1)    # li is now [1]  
li.append(2)    # li is now [1, 2]  
li.append(4)    # li is now [1, 2, 4]  
li.append(3)    # li is now [1, 2, 4, 3]  

You can remove items from the end with pop:

li.pop()        # => 3 and li is now [1, 2, 4]  

You can access items in a list like you would any array:

li[0]  # => 1  

And assign new values to indexes that have already been initialised:

li[0] = 42  
li[0]  # => 42  
li[0] = 1  # Note: setting it back to the original value  

Look at the last element of a list:

li[-1]  # => 3  

Look at ranges with slice syntax:

# (It's a closed/open range for you mathy types.)
li[1:3]  # => [2, 4]

# Omit the beginning
li[2:]  # => [4, 3]

# Omit the end
li[:3]  # => [1, 2, 4]

# Select every second entry
li[::2]   # =>[1, 4]

# Reverse a copy of the list
li[::-1]   # => [3, 4, 2, 1]

# Use any combination of these to make advanced slices
# li[start:end:step]

You can remove arbitary elements from a list with "del":

del li[2]   # li is now [1, 2, 3], this removes the element in location 2  

You can add lists:

li + other_li   # => [1, 2, 3, 4, 5, 6]  
# Note: values for li and for other_li are not modified.

You can concatenate lists with extend():

li.extend(other_li)   # Now li is [1, 2, 3, 4, 5, 6]  

You can remove the first occurence of a value:

li.remove(2)  # li is now [1, 3, 4, 5, 6]  
li.remove(2)  # Raises a ValueError as 2 is not  

Get the index of the first item found:

li.index(2)  # => 1  
li.index(7)  # Raises a ValueError as 7 is not in the list  

Check for existence in a list with in:

# Check for existence in a list with "in"
1 in li   # => True  

Examine the length with len():

len(li)  

Tuples

Tuples are like lists but are immutable:

tup = (1, 2, 3)  
tup[0]   # => 1  
tup[0] = 3  # Raises a TypeError  

You can do all the list thingies on tuples too

len(tup)   # => 3  
tup + (4, 5, 6)   # => (1, 2, 3, 4, 5, 6)  
tup[:2]   # => (1, 2)  
2 in tup   # => True  

You can unpack tuples (or lists) into variables:

a, b, c = (1, 2, 3)     # a is now 1, b is now 2 and c is now 3  
d, e, f = 4, 5, 6       # you can leave out the parentheses

# Tuples are created by default if you leave out the parentheses
g = 4, 5, 6             # => (4, 5, 6)

# Now look how easy it is to swap two values
e, d = d, e     # d is now 5 and e is now 4  

Dictionary Class

Dictionaries store mappings between keys and values.

You can initialise an empty dictionary:

empty_dict = {}  

Or you can prefill a dictionary:

filled_dict = {"one": 1, "two": 2, "three": 3}  

You can look up values with []:

filled_dict["one"]   # => 1  

Get all the keys in a dictionary as a list with "keys()":

filled_dict.keys()   # => ["three", "two", "one"]

# Note - Dictionary key ordering is not guaranteed. 
# Your results might not match this exactly.

You can get all the values as a list with values():

filled_dict.values()   # => [3, 2, 1]  
# Note - Same as above regarding key ordering.

You can check for the existence of keys in a dictionary with "in":

"one" in filled_dict   # => True
1 in filled_dict   # => False  

Looking up a non-existant key is a key error:

filled_dict["four"]   # KeyError  

Use the get() method to avoid this, as a None type will just be returned if the key does not exist:

filled_dict.get("one")   # => 1  
filled_dict.get("four")   # => None  

The get method also supports a default argument thwn a value is missing:

filled_dict.get("one", 4)   # => 1  
filled_dict.get("four", 4)   # => 4  

You can set the value of a key:

filled_dict["four"] = 4  # now, filled_dict["four"] => 4  

"setdefault()" inserts into a dictionary only if the given key isn't present:

filled_dict.setdefault("five", 5)  
# filled_dict["five"] is set to 5

filled_dict.setdefault("five", 6)  
# filled_dict["five"] is still 5

Sets

Sets store sets (which are like lists but contain no duplicates).

You can initialise a set like so:

#Initialise an emptu set
empty_set = set()

# Initialize a "set()" with a bunch of values
some_set = set([1, 2, 2, 3, 4])   # some_set is now set([1, 2, 3, 4])

#Or

filled_set = {1, 2, 2, 3, 4}   # => {1, 2, 3, 4}  

Order is not guaranteed, even though it may look sorted:

# order is not guaranteed, even though it may sometimes look sorted
another_set = set([4, 3, 2, 2, 1])  # another_set is now set([1, 2, 3, 4])  

You can add more items to a set:

filled_set.add(5)   # filled_set is now {1, 2, 3, 4, 5}  

Carry out set intersection with &:

other_set = {3, 4, 5, 6}  
filled_set & other_set   # => {3, 4, 5}  

Carry out set union with | :

filled_set | other_set   # => {1, 2, 3, 4, 5, 6}  

Find set difference with - :

{1, 2, 3, 4} - {2, 3, 5}   # => {1, 4}

Find a symmertic difference with ^ :

{1, 2, 3, 4} ^ {2, 3, 5}  # => {1, 4, 5}

Check if the set on the left is a superset of the set on the right:

{1, 2} >= {1, 2, 3} # => False

And likewise check if set on the left is a subset of set on the right:

{1, 2} <= {1, 2, 3} # => True

Finally use "in" to check for existence in a set:

2 in filled_set   # => True  
10 in filled_set   # => False  

Optional Imported Classes

Math

Import math:

Find the square root:

print (math.sqrt(16))```

Round variables up to the nearest integer:

Round variables down to the nearest integer:

print (math.floor(3.7))```

Random

Import the random module with

For a random float between 0 and 1 use:

random.random()```

To generate a specific range of random float numbers, use:

To generate a random integer in a given range:

random.randint(0, 5)```

If you want to randomly choose one item from a list, use:

If you want to randomly shuffle the position of items in a list:

random.shuffle(list)```

And if you want to generate a randomly selected number from a range, use randrange(start, stop, step):

##Extras

###Extended Class Behaviour

####Inheretance

Use the keyword super to call the initialisation function of the class you inherited. 

i.e.

class A00(object):

def __init__(self, val):
    self._val = val
    print("A00._init__(",self._val,")")

class A11(A00):

def __init__(self, val, val2):
    super().__init__(val)
    self._val2 = val2
    print("A11._init__(",self._val,",",self._val2,")")
####Private attributes, getters and setters

There is no completley private atributes in python, but this can be simulated using:

__attributename```

To manipulate a private attribute you should use accessor and mutator methods.

class P(object):  
    def __init__(self, x):
        self.__x = x

    @property
    def x(self):
        return self.__x

    @x.setter
    def x(self, x):
        if x < 0:
            self.__x = 0
        elif x > 1000:
            self.__x = 1000
        else:
            self.__x = x

This can then be called using:

p1.x = 333

print(p1.x)  

Abstract/Concrete class

An abstract class is one which will never be instantiated. They are intended only as a base class for a inheritance hierachy.

A concrete class is a class from which an object can be created/instanciated.

We use @abc.abstractmethod to define which functions have to be overwritten.

import abc ## module for abstract classes  
class GeometricObject(object, metaclass=abc.ABCMeta):  
    """Abstract base class GeometricObject""“

    def __init__(self):
        self._lineColor = 'black‘
        self._lineWidth = 1

    @abc.abstractmethod
    def draw(self):
        """Abstract method; derived classes must override"""

Class Variables

Class variables are consistent across all objects, allowing us to keep the principles of encapsulation.

class Pair(object):  
    _pair_number_instances = 0

    def __init__(self, x = 0, y = 0):
        Pair._pair_number_instances += 1
        self._x = x
        self._y = y

The @classmethod allows you to easily externally modify this variable.

class Pair(object):  
    _pair_number_instances = 0

    @classmethod
    def get_number_instances(cls):
        return cls._pair_number_instances

A static method allows for the creation of a function inside a class that is not part of the class. It is instead called by ClassName.FunctionName() Note the lack of the self variable in this decleration:

class Pair(object):  
    @staticmethod
    def get_centroid(pairs):
        length = len(pairs)
        centroid = Pair(0,0)
        for pair in pairs:
            centroid += pair * (1/length)
        return centroid

Extend Class Behaviour

The repr method returns a string containing a printable representation of the object. For many types, this
function makes an attempt to return a string that would
yield an object with the same value when passed to eval(),
otherwise the representation is a string enclosed in angle
brackets that contains the name of the type of the object
together with additional information often including the
name and address of the object.

The str method returns a string containing a nicly printable representation of an object.

str()```

We can use operator overloading on then + operator to provide native addition for our objects.

__add__ ()

Pair3 = pair1 + pair 2 

#->

Pair3 = pair1.__add__(pair2)  

Other special methods include __sub__() for subtraction, ___mul___() for multiplication and ___div___() for division.

We can also use special methods for comparrison operators.

== : __eq__

!= : __ne__

< : __lt__

<= : __le__

> : __gt__

>= : __ge__

Other stuff:

None is an object:

None  # => None  

Jacob Unwin

Read more posts by this author.

Subscribe to Jacob-Unwin.com

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!