Easy questions from a python beginner

Thomas Jollans thomas at jollans.com
Sun Jul 11 14:08:26 EDT 2010


On 07/11/2010 07:48 PM, wheres pythonmonks wrote:
> I'm an old Perl-hacker, and am trying to Dive in Python.  I have some
> easy issues (Python 2.6)
> which probably can be answered in two seconds:
> 
> 1.  Why is it that I cannot use print in booleans??  e.g.:
>>>> True and print "It is true!"

prior to Python 3.0, print is a statement, not an expression, which
means that it's rather unflexible.

In Python 3.x, print is a function, and you can use it as one:

Python 3.1.2 (release31-maint, Jul  8 2010, 09:18:08)
[GCC 4.4.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> True and print('It is true!')
It is true!
>>>

> 
> I found a nice work-around using eval(compile(.....,"<string>","exec"))...
> Seems ugly to this Perl Programmer -- certainly Python has something better?

Either use good old if:

if True: print 'It is true!'

or use a function instead of the print statement:

def print_(s):
    print s

True and print_("It is true!")

> 
> 2.  How can I write a function, "def swap(x,y):..." so that "x = 3; y
> = 7; swap(x,y);" given x=7,y=3??
> (I want to use Perl's Ref "\" operator, or C's &).
> (And if I cannot do this [other than creating an Int class], is this
> behavior limited to strings,
>  tuples, and numbers)

You can't. A function cannot modify the caller's namespace. "x" and "y"
are just names, not pointers you can edit directly.

But look at this:
>>> x = 1
>>> y = 2
>>> x,y = y,x
>>> x
2
>>> y
1
>>>

> 4.  Is there a way for me to make some function-definitions explicitly
> module-local?
> (Actually related to Q3 below: Is there a way to create an anonymous scope?)

Do you mean have the function visible inside the module, but not to the
importer?

Well, you could "del thefunc" at the end of the module, but then you
won't be able to access it from within other functions. You could in
principle create a function, pass it as a default argument to every
function that uses it, and then delete it. But that's just silly.

> 
> 5. Is there a way for me to introduce a indention-scoped variables in python?
> See for example: http://evanjones.ca/python-pitfall-scope.html

No.
exception: nested functions.

if you really want, you can always del variables after use.

> 
> 6.  Is there a Python Checker that enforces Strunk and White and is
> bad English grammar anti-python?  (Only half joking)
> http://www.python.org/dev/peps/pep-0008/

Huh?


  - Thomas



More information about the Python-list mailing list