Python Newbie

Ian Kelly ian.g.kelly at gmail.com
Fri Feb 22 00:55:44 CET 2013


On Thu, Feb 21, 2013 at 3:40 PM,  <piterrr.dolinski at gmail.com> wrote:
> 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.

If you need to search for variable names to see if you're overwriting
something, then your functions are too large and should probably be
refactored, or you're abusing globals, or possibly you just haven't
fully understood Python's scoping rules.

> 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.

Er, this doesn't sound right at all.  Javascript does have variable
declarations, using the "var" keyword.  Within a function, a declared
variable has local scope, but an undeclared variable has global scope.
 Despite having curly braces, Javascript does not have block scopes
like C# does.  More details can be found here:

http://stackoverflow.com/questions/500431/javascript-variable-scope

In Python, on the other hand, an undeclared variable in a function is
local by default (unless it is never assigned to).  To me, this makes
Python win out over Javascript because you're never going to
accidentally create a global variable just by failing to declare the
variable in the function where you use it.



More information about the Python-list mailing list