[Tutor] How to perform variable assignment and
Oxymoron
moron.oxy at gmail.com
Sat Oct 3 08:14:54 CEST 2009
Hello,
On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain <didar.hossain at gmail.com>wrote:
> homedir = os.environ.get('HOME')
>
> if homedir:
> print "My home directory is %s" % homedir
>
>
> I do this in Perl -
>
> my $home;
>
> if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; }
>
> Can I do a similar shortcut statement like the above in Python?
>
>
There are probably various syntactic tricks to achieve the same, however,
the main reason you can't do it is that assignment in Python is a statement
rather than an expression, i.e. it does not return a value that the if
statement can evaluate.
While having an assignment as an expression could be convenient in places (I
have had my moments where I wish it was!), that particular usage is also a
source of common bugs. Often in conditional statements people want to do a
comparison using the == operator rather than an assignment (=) + eval.
Marking assignment as a statement rather than an expression prevents this
bug, since it is now a syntax error in this case - an if statement cannot
work on something that doesn't return anything.
My Perl is rusty at best! Not sure if there's an == operator, if there isn't
then the decision to allow this is probably more justified since comparison
and assignment are sufficiently different syntax-wise that the intent is
clear.
-- Kamal
--
There is more to life than increasing its speed.
-- Mahatma Gandhi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20091003/99a97777/attachment.htm>
More information about the Tutor
mailing list