Hello,<br><br><div class="gmail_quote">On Sat, Oct 3, 2009 at 3:56 PM, Didar Hossain <span dir="ltr"><<a href="mailto:didar.hossain@gmail.com">didar.hossain@gmail.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
homedir = os.environ.get('HOME')<br>
<br>
if homedir:<br>
print "My home directory is %s" % homedir<br>
<br>
<br>
I do this in Perl -<br>
<br>
my $home;<br>
<br>
if ($home = $ENV{'HOME'}) { print "My home directory is $home\n"; }<br>
<br>
Can I do a similar shortcut statement like the above in Python?<br>
<br></blockquote><div> <br>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. <br>
<br>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. <br>
<br>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.<br>
<br>-- Kamal<br></div></div>-- <br>There is more to life than increasing its speed.<br> -- Mahatma Gandhi<br>