Support Our Site

To ensure we can continue delivering content and maintaining a free platform for all users, we kindly request that you disable your adblocker. Your contribution greatly supports our site's growth and development.

How To Use Variables In Python

4 min read

One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value. Variables are an essential programming concept to master.

Python is a dynamically typed programming language, which means you do not need to declare variables or its datatype before using them.

This tutorial will guide you through the basics of variables in Python 3.

When to use Variables?

Imagine that in your code somewhere you need this number 3726529215.733739. You might need to do some calculation with this number a couple of times in your entire program.

In such scenario storing this value in a Variable is better than hardcoding it every time.

Variables in Python

Variable is a storage location for a value tied with an identifier called variable name. The variable name is used to reference the value in the program when needed.

For the above example, we can store our number  3726529215.733739 in a variable named my_number.

Now our number can be addressed anywhere by the identifier my_number.

In order to assign the value to a variable, You need to use the assignment operator (=). The variable name should always be on the left side followed by the assignment operator and the value after it.

Variable = value
my_number =  3726529215.733739

Now we can use this variable anywhere in the program.

print(my_number)

We can also perform operations on the variable

print(my_number /3)

We can also store the result of this operation in another variable to reference later

my_result =  my_number /3

Unlike other programming languages such as Java and C, we don't need to specify the datatype of the variable in Python.

Python itself does that work for us; this can be seen in the below example:

my_list = ['item_1', 'item_2', 'item_3', 'item_4'] 

If we print the above list, Python will print the list for us.

print( my_list )
['item_1', 'item_2', 'item_3', 'item_4'] 

In Python, every variable is an object. Basically, you are giving a name to the object.

Variables are quite handy if used properly, however there are rules and norms to follow while naming Variables.

Naming Variables

Variable names can be arbitrarily long. They can contain both letters and numbers, but they have to begin with a letter(not a number). It is allowed to use uppercase letters, but it is a good idea to start variable names with a lowercase letter.

A variable name should always be in one word without any space in between. If the variable name has two words separate them with an underscore (_) just like we did for my_number and my_list.

Do keep in mind variable named are case sensitive which means, My_number, my_number, mY_number all are different so always stick with lowercase letters.

In programming, there are two conventions of naming a variable :

Camel Case - In camel case the variable name consisting of two words is formed by capitalizing the first letter of every word then appending it without any space or underscore, you will see a lot of this in javascript.

Example - myVariable, myResult, myInteger, myList

Snake Case - Snake case in the convention of naming variable in which the words are separated with an underscore and the first letter of each word beginning with a lowercase letter.

Example - my_variable, my_result, my_integer

You should always be consistent with the convention and stick to snake case in Python to make your code more readable and appealing to others.

Reassigning variables

We can assign new values to previously assigned values, the Variable will hold the most recent value. Assigning different datatype to the same variable is also possible.

my_var = "This is my awesome string"
>>> print(my_var)This is my awesome string

Now let's reassign my_var with an integer.

 my_var = 123
>>> print(my_var)123

Multiple Assignment

In Python, we can assign one single value in numerous different variables, like this :

>>> a=b=c=123
>>> print(a)123
>>> print(b)123
>>> print(c)123

The None Variable 

A predefined variable called None is a special value in Python. This variable has a type of its own and is used when you define a variable but not assign it with any value.

 my_none_var = None

 Local and Global Variables

On the basis of Scope, Variable can be divided into two kinds, Local variables, and global variables.

Global Variables are declared outside any function, and they can be accessed anywhere in the program whereas Local Variables are maintained and used only inside a function any other function can't access them.

Keep in mind there can be Local variables of the same name in different functions.

Let's look at the following example,

# assigning global variable
global_var = "I am global variable"
#declaring function
def my_function():
    local_var = "I am local variable" # assiging local variable
    print(local_var)my_function()
 # calling function
print(global_var)

This gives us the following output,

I am local variable
I am global variable 

Here we need to call the function to print the local variable however global variable can be addressed directly.

Now let's see if Global variable is available in the function or not,

# assigning global variable
global_var = "I am global variable"
#declaring function
def my_function():
    local_var = "I am local variable"
 # assiging local variable
    print(local_var)
    print(global_var)

my_function() # calling functionprint(global_var)

And we get the following output:

I am local variable
I am global variable
I am global variable 

We can see the global variable is printed twice which indicates that the Global variable is available to the function.

But when we try to print the local variable outside the function directly, it will give us an error.

A programmer should take benefit of this nature of variables. Usually, it is better to keep the variable local, but if you are using a variable in many several other functions then make it global.

Despite, there are some predefined keywords in Python. You can not use these names as an idetifier or a varibale name in your code. These are reserved words for Python.

So never use the following keywords as variable names,

● False ● None ● Assert ● True ● As ● Break ● Continue ● Def ● Import ● In ● Is ● And ● Class ● Del ● For ● From ● Global ● Raise ● Return ● Else ● Elif ● Not ● Or ● Pass ● Except ● Try ● While ● With ● Finally ● If ● Lambda ● Nonlocal ● Yield


PYTHON

Latest Articles

Latest from djangocentral

How to Use Subquery() in Django With Practical Examples

In the realm of web development, Django stands as a powerful and versatile framework for building robust applications. One of the key aspects of developing efficient and optimized web applications is handling database queries effectively. In this article…
Read more →

4 min read

DRF Serializer: Handling OrderedDict and Converting It to a Dictionary or JSON

In Django Rest Framework (DRF) tests, when you access serializer.data, you might encounter an OrderedDict instead of a regular dictionary. This behavior is intentional and reflects the design of DRF's serialization process.Understanding the Problem The u…
Read more →

3 min read

Django Rest Framework CheetSheet: Mastering API Development

Django Rest Framework (DRF) is a powerful toolkit that makes building robust and scalable web APIs with Django a breeze. Whether you're a seasoned Django developer or a newcomer, having a comprehensive cheat sheet at your disposal can be a game-changer. …
Read more →

5 min read

How to Perform NOT Queries in Django ORM

In Django, performing NOT queries allows you to exclude certain records from the query results based on specific conditions. The NOT operator, represented by the tilde (~) when used in conjunction with the Django ORM's Q object, helps you construct compl…
Read more →

3 min read