Python textbook exercises for C/C++ programmers

Christos TZOTZIOY Georgiou tzot at sil-tec.gr
Mon Jul 21 22:03:12 EDT 2003


Tests to let you know if you grok "the Python way".
Definition: TOPKA = The Object Presently Known As



[A] Variables/values vs names/objects.

Write a function in C/C++ and one in Python that:
1. accepts an integer as an argument named i (enforced in C/C++, assumed
in Python)
2a. [C/C++] prints the address of the i variable using printf, "%p" and
the & operator
2b. [Python] prints the id of TOPKA i using print and the id() builtin
3. adds 1 to i using the += operator
4a. same as 2a
4b. same as 2b

Explain why the C/C++ function *always* outputs two identical values,
then why the Python function *always* outputs two different values.



[B] Assignment and mutable/immutable confusion.

Fill out the ellipses in the following Python program:

a = ... # any valid expression you like
b = a
# --------------------
# if TOPKA a and/or b is mutable, you are free
# to mutate it here by calling some of its methods
# then ascertain that they still are the same object
# --------------------
b = ... # any valid expression you like
print "a = <%s>" % a
print "b = <%s>" % b

Explain why there is no friggin' way to change TOPKA a by assigning
anything to the name b (hint: you might print two identical strings, but
you can't change TOPKA a.)



[C] "By reference if mutable, by value if immutable" confusion.

Given the following two Python functions:

def foo(arg):
    dummy = arg
    bar(arg)
    assert dummy is arg

def bar(arg):
    try:
        arg = "anything but " + repr(arg)
    except:
        arg = "nice try"

Choose an appropriate mutable or immutable argument so that foo fails at
the assert statement (hint: rewrite python from scratch).



A particular disclaimer by Knuth comes to mind that seems appropriate
here...  anyway, I only wrote this so that, next time someone complains
about how python does things, I can point them to the post; should their
answers satisfy me, I might consider helping them write a PEP to change
things the way they want them to be.

Cheers everyone.
-- 
TZOTZIOY, I speak England very best,
Microsoft Security Alert: the Matrix began as open source.




More information about the Python-list mailing list