Python: Variables and Scope [global and local]

When a program runs, it stores the data it requires, in the memory(RAM). A variable is used to store a reference address of a memory. So the program can store that in the reference address and retrieve data when required.

In simple language- A variable is a named identifier(of some memory location), and we can use the named identifier to store data on it.

Variable Declaration

To define a variable we just need an identifier(which is valid). We can assign any value to the identifier and use it as a variable.

Check the following code:

# variable.py

# Declare a variable and assign value
my_val = 100

print(my_val)

# Change the value of the variable
my_val = 900

print(my_val)

# Change the value again
my_val = my_val * 2

print(my_val)
Python

Output:

100
900
1800
Plaintext

Here are some more examples of variable declaration assignments in Python-

In the code below we have used 2 variables-

  • siteName
  • siteURL

As we can see, we can store data/values, in these named identifiers, and use these data/values when we need them, later in the program.

# site_info.py

# Here we have used the variable name
# "siteName" to store the name of the site
siteName = "BigBoxCode"

# Here we are using the variable
# "siteName" to print the value stored in it
print("Name of the site is:" + siteName)

# Here we are taking some input
# and saving in the variable "siteURL"
siteURL = input("Enter the URL of {}: ".format(siteName)) 
# the above line will prompt for an input and will continue after we input some string using keyboard


# Here we are using the "siteURL" variable
print("Entered url: " + siteURL)
Python

Output:

It will generate output as below. In the process, the script will prompt for input. So we have to input some string, and then press enter “enter”

Name of the site is:BigBoxCode
Enter the URL of BigBoxCode: bigboxcode.com
Entered url: bigboxcode.com
Plaintext

Variable Reassignment

We can assign any type of value in Python, and then replace it by reassigning some other type of value-

# variable_assign.py

# Assign some integer value
big_box = 20

print("Value of big_box: ", big_box)
print("Type of big_box: ", type(big_box))

# Assign string to the same variable
big_box = "Some string value here"

print("Value of big_box: ", big_box)
print("Type of big_box: ", type(big_box))

# Assign some float to the same variable
big_box = 99.99

print("Value of big_box: ", big_box)
print("Type of big_box: ", type(big_box))
Python

Output:

Value of big_box:  20
Type of big_box:  <class 'int'>

Value of big_box:  Some string value here
Type of big_box:  <class 'str'>

Value of big_box:  99.99
Type of big_box:  <class 'float'>
Plaintext

Variable Naming Rules

Variable names should follow certain rules. We can not just name a variable anything we want, as that can cause some readability issues.

WARNING

Variable names are case-sensitive. So my_var, My_Var, and mY_VAR represent different variables.

Here are the criteria for a valid Python identifier. An identifier should be-

  • A non-empty sequence of characters.
  • Must start with a letter or an underscore(_).
  • Can only contain letters, numbers, and underscore(_).
  • Can not be a reserved Python keyword(mentioned below).

WARNING

The following keywords are reserved keywords in Python, and can not be used as variable names in Python-

and
as
assert
async
await
break
class
continue
def
del
elif
else
except
false
finally
for
from
global
if
import
in
is
lambda
None
nonlocal
not
or
pass
raise
return
True
try
while
with
yield

Try the following code-

for = 100
Python

Output will be-

 File "variable.py", line 1
    for = 100
        ^
SyntaxError: invalid syntax
Plaintext

If you want to get the list of reserved(builtin) keywords, then use the following code-

dir()
dir(__builtins__)
Python

You will get the list of all keywords, that can not be used as an identifier-

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']


['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError',
...... 
'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
Plaintext

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.