Python Newbie

Chris Angelico rosuav at gmail.com
Thu Feb 21 18:21:27 EST 2013


On Fri, Feb 22, 2013 at 9:40 AM,  <piterrr.dolinski at gmail.com> wrote:
> Thanks to all for quick relies.
>
> Chris, you are (almost) spot on with the if blocks indentation. This is what I do, and it has served me well for 15 years.
>
> code
> code
>
>    if (some condition)
>    {
>       code
>       code
>    }
>

I understand you have the freedom to do that in most languages, but
that's simply a restriction of Python: you have to use a more
conventional indentation system. Personally, I don't see the 'if' as
being special here, and the body of it (which IS special, as it may or
may not be executed) is already standing out.

> I am nervous about using variables "out of the blue", without having to declare them. For example, when I write "i = 0" it is perfectly OK to Python without 'i' being declared earlier. How do I know that I haven't used this variable earlier and I am unintentionally overwriting the value? I find I constantly have to use the search facility in the editor, which is not fun.
>
> You see, Javascript, for one, behaves the same way as Python (no variable declaration) but JS has curly braces and you know the variable you have just used is limited in scope to the code within the { }. With Python, you have to search the whole file.

That's a fair point. The elision of variable declarations is a design
decision that Python is unlikely to reverse, and it happens to be one
I disagree with. But it's there, so when I code Python, I accept it :)
There are other languages similar to Python that have strict variable
declarations, and with them the awesomeness that is infinitely nested
scopes; Python just has global (module) scope and function scope, plus
'nonlocal' which can solve some problems (but I've yet to find it do
so without damaging code clarity).

> What about Python's ambiguity?
> For example, in C you would write
>
> if (myVar != 0)
>   do something
>
> in Python, this is legal
>
> if (not myVar):
>   do something
>
> What does this mean? Is it a test for myVar being equal to zero or a test for null, or else?

Python has a state called "truthiness". Generally speaking, something
with content is true, and something without content is false. The None
singleton, empty lists, empty tuples, the integer 0, and a regular
expression result that didn't match, all evaluate as False in a
boolean context; most other things evaluate as True. If you
specifically care if it's not zero, you ask if it's not zero; if you
want to know if it's falsy, you check "not X". The facilities are
there to do whatever you want.

ChrisA



More information about the Python-list mailing list