A Beginner’s Guide To Variables in Python

Python Variables: A Beginner’s Guide

What is a variable in Python?

Python variables are the suggestive names for a piece of stored information. The variable’s name usually describes what information the variable holds. They are known as variables because the information can change, but the functions of the variable stay the same.  

Simply put, variables in computer programming are identical to “Buckets” or “Envelopes” to which information can be held and referenced—the bucket name on the outside. When we refer to the bucket, the bucket’s name is used and not the data stored in the bucket.

Creating Python Variables

Python programming language does not require an explicit declaration to create a variable. In Python, variables are created when you assign a value to them. The equal sign (=), the assignment operator, sets a variable a value.

Syntax:

<variable/operand> = <value/operator>

Example:

name = "Zara Ali" # Creates a string variable
age = 100 # Creates an integer variable
miles = 1000.0 # Creates a floating point variable

Printing Python Variables

When a Python variable is created and assigned a value, we print it using the print() function. Below is the extension of the previous example that shows how to print the earlier variables in Python:

name = "Fred All" # Creates a string variable
name = "Fred All" # Creates a string variable
Phone = "+123456974566" # Creates a floating point variable
print (name) 
print (age) 
print (phone)

Multiple Assignment of Python Variables

In Python, you can assign a single value to multiple variables simultaneously, which implies that you can create multiple variables simultaneously. 

example:

x = y = z = 192

print (x)
print (y)
print (z)

Result:

192
192
192

In the above code, we created an integer variable with the value 1, and the three variables were assigned a single memory location. Various values can be assigned to multiple variables on a single line. 

Example:

x,y,z = 0,1,"Fred All"

print (x)
print (y)
print (z)

Result:

0
1
Fred All

In the above code, two integer variables with values of 0 and 1 are assigned to variables x and y, respectively. We also have one string variable with the value “Fred All” assigned to the variable z.

Python Variable Naming Convention

In Python, variable names must be unique a, b, c. A variable name can be suggestive, like color, age, name, etc. There are specific rules which should be taken into consideration while naming a Python variable:

  • A variable name must start with a letter or the underscore character
  • A variable name can not begin with a number or special character like $, (, * %, etc.
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Python variable names are case-sensitive, which means Hello and HELLO are two different variables in Python.
  • Python-reserved keywords should be used to name a variable.

Example:

Below are valid Python variable names:

counter = 100
_count = 100
name1 = "Fred"
name2 = "Mike"
Age = 20
daily_salary = 100000

print (counter)
print (_count)
print (name1)
print (name2)
print (Age)
print (daily_salary)

Result:

100
100
Fred
Mike
20
100000

Example

Below are invalid Python variable names:

1counter = 100
$_count = 100
daily-salary = 100000
print (1counter)
print ($count)
print (daily-salary)

Result:

File "main.py," line 3
    1counter = 100
           ^
SyntaxError: invalid syntax

Python Variable Scope

A variable scope defines the region where the variable can be accessed. Therefore, variables can be classified into one of three scopes: 

  1. local scope
  2. global scope
  3. nonlocal scope.

Python Local Variable

When a variable is declared inside a function, it will belong to the local scope (within a function). It cannot be accessed from outside of the function. Therefore it is called local variables. 

Example:

def hello():
    # local variable
    message = 'Hello'
    print('Local,' message)
hello()

# try to access the message variable 
# outside greet() function
print(message)

Output

Local Hello
NameError: name 'message' is not defined

In the above code, the message variable is local to the hello() function, so it can only be accessible inside the function.

That is why we get an error when accessing it outside the hello() function. To resolve this problem, we can create a global variable called message.

Python Global Variable

When a variable in Python is declared outside of a function, it will belong to the global scope and be known as a global variable. A global variable can be accessible both inside and outside of a function.

Example:

# declare a global variable
message = 'Hello'

def hello():
    # declare a local variable
    print('Local', message)
hello()

print('Global', message)

Result:

Local Hello
Global Hello

This time, we accessed the message variable outside the hello() function because we declared the message variable as the global variable.

# declare a global variable
message = 'Hello'

Now, we can access the message variable from any scope (region) in the program.

Python Nonlocal Variables

Nonlocal variables are utilized in nested functions whose local scope is not specified. This implies that the variable can be neither in the local nor the global scope.

We use the nonlocal keyword to create nonlocal variables.

Example:

# outside function 
def outer():
    message = 'local'
    # nested function  
    def inner():
        # declare nonlocal variable
        nonlocal message
        message = 'nonlocal'
        print("inner:", message)
    inner()
    print("outer:", message)

outer()

Result:

inner: nonlocal
outer: nonlocal

In the above example, there is a nested inner() function. We have used the nonlocal keywords to create a nonlocal variable.

The inner() function is defined in the scope of another function outer().

See my older post on how to install python on windows 10 PC.

Leave a Comment

Your email address will not be published. Required fields are marked *