Variables in Python
Tags: python, programming, writing, beginners
Published: 2021-12-04 17:13:14

A variable in programming is generally a container or location in the computer’s memory used to store values temporarily. Variables in Python are nothing different from the general programming definition of a variable. Values stored in the variable can then later be used or modified in our programs. This article discusses all the basics you need to know in Python programming language.

### Table of Contents
- [What are variables?](#what-are-variables)
- [Variables in Python](#variables-in-python)
  - [Variable Naming convention](#variable-naming-convention)
  - [Variable declaration and usage](#variable-declaration-and-usage)
  - [Reassigning variables](#reassigning-variables)
  - [Operation on variables](#operation-on-variables)
  - [Variable scope: Local and global variables](#variable-scope-local-and-global-variables)
- [Conclusion](#conclusion)


### What are Variables?
Variable are reserved locations in the memory of the computer used to hold values that can be used later.
Because the computer stores variables in the Random Access Memory (RAM), variables are created in the memory only when our program is in execution and are lost immediately after the program is terminated. What this means is that the value of a variable can only be accessed when a program is running. When the program has finished execution, these variables are not accessible anymore from anywhere in the computer. In order to use them again, you will have to run the program once again.

If you wish to store and retrieve variable values in your programs, consider using a file or database to store these variables. Variables stored in files and databases are stored in the secondary storage of the computer (e.g. Hard Disk Drive (HDD)) and remains for as long as you want them. They can also be retrieved from the computer’s memory even after shutting down and booting up the computer.

### Variables in Python
In Python, variables are nothing different from the definition above. Python allows us to create variables and use them in our programs, as well as manipulate the values of these variables. 

####Variable Naming Convention
Below are some of the rules that variables you must abide by when naming variables in Python.
1. Do not use reserved keywords as a variable name. For example , keywords like class, int, def, while, else, try, e.t.c. 
2. You cannot use special characters such as @, #, $, %, ^, & , e.t.c. when naming variables
3. Variable names are case sensitive. For example, age and Age are two different variables.
4. Variable names should start with an alphabet or an underscore(_) character.
5. A variable name can only contain the characters A-Z, a-z, 0-9 and underscore(_).
6. You cannot start the variable name with a number.

#### Variable Declaration and Usage
Variables in python can be declared and used in different ways. Here, we will be exploring some of the ways variables can be declared and used.
The snippet below declares and used the variable `message`

```py
# prints the value of message to the console
message = "Hello, World!"
print(message) 


## output
# Hello, World!
```

The snippet above is the simplest way you can declare a variable in Python. But wait, what if I need to make my variable names more descriptive?  Python has got your back. According to [PEP 8 Style guide](https://www.python.org/dev/peps/pep-0008/#id43), variable names should be lowercase, with words separated by underscores as necessary to improve readability. In a situation where you might want to use long and descriptive variable names, you can simply separate it with an underscore like in the snippet below:

```py
# long and descriptive variable names
secret_message = "Hey, here is my secret"
print(secret_message)


## output
# Hey, here is my secret
```

Python also allows you to declare variables in a more flexible and dynamic way. Unlike other statically typed programming languages like Java, Python is a dynamically typed language and you don’t need to care much about the type of a variable during declaration. You can declare multiple variables of different types on the same line. Let’s see how this looks:

```py
# Declare multiple variables in a single line
# doing it the conventional way
name = "Prince"
age = 12
hobby = "Swimming"
print("Name:", name, " Age:", age, " Hobby: ", hobby)

# doing it the Python way
my_name, my_age, my_hobby = "Prince", 12, "Swimming"
print("Name:", my_name, " Age:", my_age, " Hobby: ", my_hobby)


## output
# Name: Prince  Age: 12  Hobby:  Swimming
# Name: Prince  Age: 12  Hobby:  Swimming

```

#### Reassigning Variables 
Python allows you to reassign variables after they are declared, just like most programming languages allow you to. This process is known as “writing into a variable”. When you reassign a variable, the previous value is lost and the new value is then stored. 

```py
# Reassigning variables
my_age = 20
print(my_age)

# reassign the value of my_age
my_age = 21
print(my_age)


## output
# 20
# 21
```

The value of `my_age` was initially 20, but after printing it on the console and then reassigning it, the value changed to 21. 

#### Operation on Variables
You can also perform some operations on the values of your variables. This is one of the great benefits variables give to us. In a situation where you want to perform operations on a very lengthy value many times in your programs. You don’t need to use that length value everywhere in your program. You can simply store the value with a shorter variable name and use it throughout your program. Let’s try this out:

```py
# Operations on variables

PI = 3.142857143
radius = 44
perimeter = 2 * PI * radius
print(perimeter)


## output
# 276.571428584
```

You can perform any arithmetic operations on numbers in Python. From the snippet above, we can also operate on variables and literals (2 from the code example), provided they are all numbers (either integers or with decimal points). The value 3.142857143  from the code example is long and you might have a hard time holding it in your head. Storing it in PI makes it easily accessible and can be used throughout our programs.
Strings are also not left out here as well as you can perform operations on strings as shown in the code example below.

```py
# String operations
msg1 = "Hello"
msg2 = "World"
full_msg = msg1 + msg2
print(full_msg)


## output
# HelloWorld
```

The most common operation on string is **concatenation**. This is simply appending one string to the end of the other using the (+) operator. You can only concatenate a string with another string. If you try to do otherwise, Python will throw a `TypeError`.
The (*) operator can also be used on strings. But instead of appending to the end of the string, it rather duplicates the string according to the integer value specified.

```py
# String operations
fav_language = "Python"
output = fav_language * 5
print(output)


## output
# PythonPythonPythonPythonPython
```

Also note that the value specified must be an integer. Using otherwise will also throw a `TypeError`.

#### Variable Scope: Local and Global Variables
Variables declared in the programs we have written so far are available throughout the program. This means it can be accessed from anywhere in the program.
But things begin to get complicated when we start writing complex programs that involve functions which carry out a particular task. This is where the concept of **variable scope** come in.
The scope of a variable is the region of our program where the variable can be accessed. A variable can either have two scopes: Local and Global. 
A `local` variable is a variable accessible within the function or method it is defined. This is useful when we want to isolate a variable from the remaining part of our program. 

```py
# Variable scope
# local variable 
def some_function():
    my_real_age = 19
    print(my_real_age) # my__real_age is locally available in some_function

some_function() # execute some_function
print(my_real_age) # my_real_age is not available outside some_function 


## output
# 19
# NameError: name 'my_real_age' is not defined
```

When `some_function()` is executed, it prints out the value of `my_real_age` to the console because `my_real_age` is defined inside the function. But again, when we tried to print `my_real_age` outside `some_function`, a `NameError` was thrown because `my_real_age` is only available inside `some_function` and not throughout the program. This is because `my_real_age` is a local variable.
A `global` variable is a variable accessible throughout our program. It remains the same throughout our program and also throughout the module. Use the global variable when you want to use the variable throughout the methods and functions of your program. Let us use the same example from above, but this time making `my_real_age` a global variable:

```py
# Variable scope
# global variable
def some_function():
    global my_real_age
    my_real_age = 19 # globally available throughout this program
    print(my_real_age) 

some_function()
print(my_real_age) # my_real_age is now available outside the some_function 


## output
# 19
# 19
```
The program above runs successfully without any errors because `my_real_age` is now declared as a global variable.
Declaring variables either local or global is useful in cases where you wouldn't want variables to clash in your Python packages and modules. Other programming languages like Java use class variables, instance variables, and local variables for this concept. But it is more simplified with just local and global variables as presented by Python.

### Conclusion
Having a good knowledge of variables in any programming language is as important as learning the language itself. This article discusses an overview of variables in Python. It starts with a general view of a variable and then narrows down to the Python view of a variable.
And then discussed the naming convention of variables, declaration and usage, how to reassign variables, the numerous operations you can perform on variables, and finally the scope of a variable.

Check out the [official Python documentation ](https://docs.python.org/3/tutorial/index.html) to know more about variables.

Feel free to drop your thoughts and suggestions in the discussion box. I will be available to attend to them. And also, if you have any questions, you can as well drop them in the discussion box.