Skip to content

Instantly share code, notes, and snippets.

@whwkong
Last active January 11, 2017 14:02
Show Gist options
  • Select an option

  • Save whwkong/7352888d6167ee03557b398dd1bade89 to your computer and use it in GitHub Desktop.

Select an option

Save whwkong/7352888d6167ee03557b398dd1bade89 to your computer and use it in GitHub Desktop.
Python Cheatsheet

Python cheatsheet

Styleguides

Python styles guide, and examples of common python idioms and patterns:

Conditionals

Boolean Logic

C++	        Python
-------------------
&&	        and
|| 	        or
!	        not
true	    True
false	    False

General forms of if-else if-else statement

if <conditional test> :
    [commands]
    
if <test> :
    [commands]
elif <test>:
    [commands]
else:
    [commands]

Strings

Concatenating strings and integers

Use the str() function

a = 1
name = "abc"
print(name + str(a))

Loops

for i in range(5):
    print i, 

>>> 0 1 2 3 4 

for i in range(0,5):
    print i,
>>> 0 1 2 3 4 

i = 0 
while i<5:
    print i, 
    i += 1      # note : there are no ++ operators in Python 
    
>>> 0 1 2 3 4 

Functions

def add(a, b):
    print "adding %d + %d" % (a, b)
    return a + b;

contrast to JS

function add(a, b) {
    return a+b; 
}

Classes and Objects

class Car(object):
    def __init__(self): 
        self.speed = 0 
        self.wheels = 0
        self.engines = 1
        self.seat = 5 
    
    def accelerate(self, a):
        self.speed += a;
    
    def speed(self):
        return self.speed
        
mustang = Car()

contast to JS

var Car = function {
    var speed = 10; // private variable  
    
    // public members
    this.wheels = 4;
    this.engines = 1;
    this.seats = 5;
    
    // these are public methods
    this.accelerate = function(change) {
      speed += change;
    };
};

Class variables

Return to top

class Movie(object):
    VALID_RATINGS = ["G", "PG", "PG-13", "R", "NC-17"]
    
    def __init__(self,
                     movie_title,
                     movie_storyline,
                     poster_image,
                     trailer_youtube):
            self.title = movie_title
            self.storyline = movie_storyline
            self.poster_image_url = poster_image
            self.trailer_youtube_url = trailer_youtube

Predefined Class Variables

Classes have five predefined attributes:

__doc__     : documentation string
__name__    : name of class
__module__  : name of module
__bases__   : name of parent class
__dict__    : class name space

Example of setting documentation string.

class Movie(object):
    """ This class provides a way to store movie related information."""
    
    VALID_RATINGS = ["G", "PG", "PG-13", "R", "NC-17"]

super() : calling the Parent's constructor

Within context of single-inheritance, using super() means that you don't have to hard-code the base class' name. However, super() is far more useful during multiple-inheritance.
see : http://stackoverflow.com/questions/222877/what-does-super-do-in-python

class Child(Parent):
    def __init__(self):
        super(Child, self).__init__()

Passing parameters using super()

If you use super(), then the parent class must extend from object.

The correct format is :

class Parent(object):
    def __init__(self, arg):
        pass

class Child(Parent):
    def __init__(self, a):
        super(Child, self).__init__arg

input/output

string.strip(s[, chars])

  • Return a copy of the string with leading and trailing characters removed

    N = int(raw_input().strip())

sys.stdout.write vs print

print is a thin wrapper, and calls the write() function on a given object.
The default object is sys.stdout but it could also be a file.

print >> open(`file.txt`, 'w'), 'Hello', 'World'

Debugging

import pdb; pdb.set_trace()

Return to top

Python SP

  • nested list comprehension
  • generators, yield
  • *operator, splat.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment