Do variables have to be defined in Python before use?

Question:

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?

Asked By: antonpug

||

Answers:

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

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...
Answered By: Michael Berkowski