Do Variables Have To Be Defined In Python Before Use?
Is Python much like PHP in that I can call a variable and if it doesn't exist it will be created? Or I need to declare them?
Solution 1:
In PHP if you call a variable and it doesn't exist, you'll get Notice: Undefined variable
. This doesn't create it -- doing the same thing again still returns a warning.
php > echo$some_uninitialized_var;
PHP Notice: Undefined variable: some_uninitialized_var in php shell code on line 1
php > echo$some_uninitialized_var;
PHP Notice: Undefined variable: some_uninitialized_var in php shell code on line 1
In Python if you call a variable and it isn't initialized you'll get a NameError
. Same thing - it won't get created - you'll get NameError
until you actually initialize it.
>>> print(some_uninitialized_var)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_uninitialized_var' is notdefined
>>> print(some_uninitialized_var)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'some_uninitialized_var' is notdefined
Initialization without declaration:
In both PHP and Python though, unlike say, C, you don't need to declare the variables before first using them, and that's perhaps what you meant. You can just assign them and they'll be created on first assignment.
// PHP$a_new_var = 12345;
// All is well...# Python
a_new_var = 12345# All is well...// C
a_new_var = 12345;
// Crash! Horror! Compiler complains!int a_new_var;
a_new_var = 12345;
// ok...
Post a Comment for "Do Variables Have To Be Defined In Python Before Use?"