Hello,

On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain <didar.hoss...@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
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to