[Tutor] C to Python

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 20 Feb 2001 23:07:32 -0800 (PST)

On Tue, 20 Feb 2001, Katharine Stoner wrote:

> How is Python like C/C++?  Can it do everything C/C++ can do?

Hmmm... Well, they're both programming languages.  *grin*

More seriously: Python has some features that make it "higher-level" than
C++.  For example, Python has a "long integer" type built into the

>>> def factorial(x):
...     if x == 0: return 1
...     else: return x * factorial(x-1)
>>> factorial(20)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
[ some error messages cut ]
  File "<stdin>", line 3, in factorial
  File "<stdin>", line 3, in factorial
OverflowError: integer multiplication      # oh.  Must use long ints.
>>> factorial(20L)
2432902008176640000L                       # ah.  Better.

So if you every deal with large numbers, just append an "L" to it, and you
have long integers of unbounded size.  (Well, unbounded if you have
unbounded memory.)  You also have access to complex numbers, lists and
tuples, and hashtables.

Classes are less complicated in Python --- in C++ terms, everything is
"virtual" and "public" by default.  The classic Account class in C++:

class Account {
    Account(int amount) { this->money = amount); }
    void deposit(int amount) { this->money += amount; }
    void report() { cout << this->money; }
    int money;

looks this this in Python:

class Account:
    def __init__(self, amount): self.money = amount
    def deposit(self, amount): self.money += amount
    def report(self): print self.money

Because there's less that needs to be formally declared in Python, writing
Python programs feels less constraining than in the C-ish languages.  
Whether this is a good thing or a bad thing depends on your outlook: do
you like straitjackets?  *grin*

You'll probably want to look more closely at the language introductions
and tutorials section on Python org; there's even the infamous "language
comparision" page linked there:


Finally, what's very neat about Python is that if you ever find something
that's difficult in Python, you can do in C/C++, and extend your results
as a "C Extension": you can allow Python to use those new features!  
You'll probably want to look at the material here:


which talks about C/C++ extension stuff.

If you have any questions, please feel free to ask us.