Should variables be defined in Python before use?

Is Python very similar to PHP in that I can call a variable, and if it does not exist, it will be created? Or do I need to declare them?

+3
source share
1 answer

In PHP, if you call a variable and it does not exist, you will get Notice: Undefined variable. This does not create it - repeating the same result will still return 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 is not initialized, you will get NameError. The same thing - it will not be created - you will receive NameErroruntil you initialize it.

>>> print(some_uninitialized_var)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'some_uninitialized_var' is not defined

>>> print(some_uninitialized_var)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'some_uninitialized_var' is not defined

Initialization without declaration:

PHP Python, C, , , . , .

// 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...
+6

All Articles