Python styles guide, and examples of common python idioms and patterns:
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]
Use the str() function
a = 1
name = "abc"
print(name + str(a))
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
def add(a, b):
print "adding %d + %d" % (a, b)
return a + b;
contrast to JS
function add(a, b) {
return a+b;
}
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 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
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"]
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__()
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
string.strip(s[, chars])
-
Return a copy of the string with leading and trailing characters removed
N = int(raw_input().strip())
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'
import pdb; pdb.set_trace()