CPP To Python
CPP To Python
python:
Hi, Im a BSc4 Maths/Computer Science student. Unfortunately my curriculum did no
t include Python
programming yet I see many vacancies for Python developers. I studied programmi
ng Pascal, C++
and Delphi. So I need to catch up quickly and master Python programming. How do
you suggest that I
achieve this goal? Is python platform independent? What is the best way? And ho
w long would it take
before I can develop applications using python? Can you recommend websites that
feature a gentle
introduction to Python?
Stop thinking about how to start and just start. Python is pretty intuitive, es
pecially if you have other
language background to relate to. Download the Python dist for your platform (L
inux? probably
already there - Windows? binary installers from python.org or activestate will i
nstall in a snap). Run
through the first few pages of any of the dozen or more online tutorials to star
t getting your fingernails
dirty. You'll need a text editor with integrated building - I find SciTE and Py
Scripter to be good for
beginners (and I still use SciTE after 4 years of Python programming).
You know C++ and Pascal? You already know the basic if-then-else, while, and fo
r control structure
concepts.
Here are some C++-to- Python tips:
• There's no switch statement in Python. Make do with cascading if/elif/else unt
il you come across
the dict dispatch idiom.
• There's no '?' operator in Python. If you download the latest version (2.5), t
here is an equivalent
x if y else z
which would map to
y ? x : z
using the ternary operator. But lean towards explict readability vs. one-liner
obscurity at least for a
few days.
• Forget about new/delete. To construct an object of type A, call A's constructo
r using
newA = A()
To delete A, let if fall out of scope, or explicitly unbind the object from the
name "newA" with
newA = None
This will allow newA to be cleaned up by the garbage collector at some future ti
me.
• Forget about for(x = 0; x < 10; x++). Python loops iterate over collections, o
r anything with
an __iter__ method or __getitem__ method. This is much more like C++'s
for(listiter = mylist.first(); listiter != mylist.end(); ++listiter)
To force a for loop to iterate 'n' times, use
for i in range(n):
The range built-in returns the sequence [0, 1, 2, ..., n-1].
Don't commit this beginner's blunder:
list1 = [ 1, 2, 3 ]
for i in range(len(list1)):
# do something with list1[i]
• Compound return types - need 3 or 4 values returned from a function? Just retu
rn them. No need
for clunky make_pair<> templates, or ad hoc struct definitions just to handle so
me complex return
data, or (ick!) out parameters. Multiple assignment will take care of this:
def func():
return 4,5,6
a,b,c = func()
• Flexible and multiline quoting. Quoted string literals can be set off using ""
s, ''s, or triple quotes
(""" """, or ''' '''). The triple quote versions can extend to multiple lines.