How to create a variable in python

By: On:

In this python tutorial, we will discuss what is a variable, python variable, naming conventions, How to declare (assign) python variable, How to reassign a variable and how to create a variable in Python.

Also we will cover below things.

  • Multiple assignments.
  • How to use + operator with python variables
  • Type of variable in python
  • Variable scope in python
  • How to create a global variable in python (Global Keyword in Python)
  • Python variable in string
  • How to create a private variable in python
  • How to create a protected variable in python
  • Create a static and boolean variable in python

What is a variable?

A variable is nothing but a container that stores information or values.

In another way, Variable is a form of reserving memory locations to store some information or values.

You can also check a very good article in How does python work? and Python download and Installation steps.

Python Variable

In Python, You no need to mention the type while declaring the variable. This is the reason python is known as dynamically typed.


When we assign the value to this, during the same time, based on the value assigned python will determine the type of the variable and allocates the memory accordingly.

Example:

A = 19
B = "Python"

Here, A and B are two variables those contains the values as 19 and Python respectively.

Python can understand that A is an integer variable seeing the value as “19” and B is a string variable seeing the value as “python”.

Python variable naming conventions.

There are some rules we need to follow while giving a name for a variable. I have written a blog in detail on How to use naming convention in python

Rule-1:

You should start variable name with an alphabet or underscore(_) character.

Rule-2:

A variable name can only contain A-Z,a-z,0-9 and underscore(_).

Rule-3:

You cannot start the variable name with a number.

Rule-4:

You cannot use special characters with the variable name such as such as $,%,#,&,@.-,^ etc.

Rule-5:

Variable names are case sensitive. For example str and Str are two different variables.

Rule-6:

Do not use reserve keyword as a variable name for example keywords like class, for, def, del, is, else, try, from, etc.

#Allowed variable names

x=2
y="Hello"
mypython="PythonGuides"
my_python="PythonGuides"
_my_python="PythonGuides"
_mypython="PythonGuides"
MYPYTHON="PythonGuides"
myPython="PythonGuides"
myPython7="PythonGuides"

Check the output here

Python variable declaration
#Variable name not Allowed

7mypython="PythonGuides"
-mypython="PythonGuides"
[email protected]="PythonGuides"
my Python="PythonGuides"
for="PythonGuides"
How to declare python variable

It shows invalid syntax. Refer to the above screenshot. It will execute one by one and will show the error.

Create a variable in python or declare a Python variable

Now, we will see how to create a variable in python. Also, how to declare (assign) python variable.

To declare a variable, You just need to assign a value to a variable.

When you want to assign a value to a variable, you need to use the “=” operator. The left side of the “=” operator is the variable name and the right side is the value assigned to it.

Examples:

a = 1
b = 11
c = 11.1
d = "Python"

print(a)
print(b)
print(c)
print(d)

Let’s run the above code and see the output. The output should be

1
11
11.1
Python
Python variable

We got the expected output. See above.

How to reassign a variable

You can reassign a variable in python meaning suppose you have assigned a = 3 and again you can assign a different value to the same variable i.e a=”Hello”.

Example:

a=3
print(a)
a="Hello"
print(a)
Reassigning python variable

Python variable multiple assignment

In Python, we can assign multiple variable in one line. To do this we have two approaches.

Approach-1:

Put all the variables in one line with multiple “=” operators and at the end we can keep the value.

Example:

a = b = c = d = 23

print(a)
print(b)
print(c)
print(d)

We can check the out put here

python variable multiple assignment

After executing the code, we got the above expected output.

Approach-2:

Put all the variables with comma separator and then put the “=” operator and then on the right side of the “=” operator put all the values with a comma separator.

Example:

a,b,c,d = 3
print(a)
print(b)
print(c)
print(d)

oops I got an error because you can not assign it in this way. Remember this. You will get an error “TypeError: cannot unpack non-iterable int object“. See below

Traceback (most recent call last):
  File "C:/Users/Bijay/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Variable.py", line 1, in <module>
    a,b,c,d = 3
TypeError: cannot unpack non-iterable int object
Python variable multiple assignment using python 3.8

So the correct way is as below. You need to specify a separate value for each one.

a,b,c,d = 3,4,5,6
print(a)
print(b)
print(c)
print(d)
python variable naming conventions

You can also assign different type of value to each one.

Example:

a,b,c,d = 3,4.2,5,"PythonGuides"
print(a)
print(b)
print(c)
print(d)
Assignment of multiple variable in python

How to use + operator with python variables

you can use + operator to do additional operation in case of two integer values or to concatenate two strings values.

Example:

a = 3
b = 5

print(a+b)
Create a variable using python

Example:

a = "Python"
b = "Guides"

print(a+b)
make a variable python

In the case of two different types of values, you cannot use + operator. You will get the error as “TypeError: unsupported operand type(s) for +: ‘int’ and ‘str'”

Example:

a = 7
b = "PythonGuides"

print(a+b)
how to add variables in python

Type of variable in python

As we discussed already, a variable will be decided by the system where to allocate the memory based on their type. So let’s discuss about few basic types of variables.

1- Number:

This type of variable contains numeric values.

There are four types of numeric values are available in python

i – int

Example:

a = 11
print(a)

ii – Long

a = 4568934L
print(a)
Note: Python 3.8 version doesn't support a trailing L. It will show you invalid syntax.

iii – Float

a = 11.5
print(a)

iv – Complex

a = 55.j
print(a)

2- String:

This type of variable contains string values. String can be used with pairs of single or double quotes.

Example:

s = "PythonGuides"

print(s)
s = 'PythonGuides'

print(s)
Python variable type

3- Lists:

A list contains items separated by commas and kept within square brackets ([]).

Example:

a = [11,12.3,'PythonGuides']

print(a)
How many types of variables are there in python

4- Tuples

A tuple is same as lists but it kept within parentheses ( () ). Items are separated by commas.

Example:

a = (11,12.3,'PythonGuides')

print(a)
Tuples in python

4- Dictionary

In Python, you can write dictionaries with curly brackets ( {} ). They have key and value pairs.

Example:

mydict = {
  "good": "Exposure",
  "Average": "Knowledge",
  "Score": 200
}
print(mydict)
Dictionary in python

Variable scope in python

See below for the scope

1- Local scope

A variable that is created inside a function has scope with in that function.

You can use that variable with in that function. Let’s see an example

Example:

def myLocal():
    a = 50
    print(a)
myLocal()
Local variable scope in python

2- Global scope

The variable created outside the function or in the main body of the program is known as the Global scope.

Example:

a = 50
def myLocal():

    print(a)
myLocal()
print(a)
Global scope variable in python

3- Enclosing Scope

In the below code, ‘b’ has local scope in myLocal() function and ‘a’ has nonlocal scope in myLocal() function. This is known as the Enclosing scope.

def myTest():
            a = 50
            def myLocal():
                      b = 3
                      print(a)
                      print(b)
            myLocal()
            print(a)
myTest()
Enclosing scope variable in python

Nonlocal Keyword in Python

The nonlocal keyword was introduced in python 3.

Remember nonlocal keyword is case sensitive.

We can use the nonlocal variable in the nested function whose local scope is not defined. Meaning the variable either belongs to the local or global scope.

Example:

def Test1():
  a = "Raj"
  def Test2():
    nonlocal a
    a = "You there"
  Test2()
  return a

print(Test1())
nonlocal keyword in python

How to create a global variable in python (Global Keyword in Python)

The use of the global keyword can make the variable global even though the variable is present inside the function. Let’s see an example.

Example:

def myLocal():
global a
    a = 50
myLocal()
print(a)
Global keyword in python

Example-2:

If you want to change the value of a global variable inside a function

a = 150
def myLocal():
  global a
  a = 50
myLocal()
print(a)
Global variable in python

Python variable in string

Let’s see how can we put a variable in side a string.

age = 60
print(age)

I want a out put like “Your father is 60 years old”. How can we do that?

You can do this in multiple ways

1- Concatenation

Use the format like below to achieve this.

age = 60
print(age)
Mystatement = "Your father is " + str(age) + " years old"
print(Mystatement)
Python variable in string

2- The format() method for python strings

This is one more way to achieve the above requirement.

age = 60
print(age)
statement = "Your father is {} years old".format(age)
print(statement)
how to use python variable in string

How to create a private variable in python

By declaring your variable private you mean, that nobody can able to access it from outside the class.

In Python, adding two underscores(__) at the beginning makes a variable as private. This technique is known as name mangling.

Let’s see an example to see how exactly python private variables behaves.

Example:

class Test:
    __age = 30
    def __Test2(self):
        print("Present in class Test")
    def Test3(self):
        print ("Age is ",Test.__age)
t = Test()
t.Test3()
t.__Test2()
t.__age

see the output here

Age is  30
Traceback (most recent call last):
  File "C:/Users/Bijay/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Variable.py", line 9, in <module>
    t.__Test2()
AttributeError: 'Test' object has no attribute '__Test2'
Private python variable

In the Test3() method, the __age variable can be accessed as shown above (age is printed).

How to create a protected variable in python

By declaring your variable protected you mean, that it is same as private variable with one more advantage that they can be accessed in sub classes which are called derived/child classes

In Python, adding single underscores(_) at the beginning makes a variable as protected.

Example:

class PythonGuides:
    # protected variable
    _name = "Raj"

    def Test(self):
        # accessing protected variable
        print("Name: ", self._name)
        # creating objects of the class
p = PythonGuides()

# functions of the class
p.Test()

See the output

Name:  Raj
Protected variable in python

In the case of inheritance, the protected variable which is created in the parent class can be accessed in the derived class.

How to create a static variable in python

All the variables declared inside class and outside the method are known as static variables.

Static variables are also known as class variables.

There is no specific keyword in python to declare a static variable.

Example:

class Test:
    var = 2           # static variable

print (Test.var)     # prints 2   (static variable)

# Access with an object
obj = Test()
print (obj.var)    # still 2


# difference within an object
obj.var = 3      #(Normal variable)
print (obj.var)    # 3   (Normal variable)
print (Test.var)     # 2   (static variable)


# Change with Class
Test.var = 5       #(static variable)
print (obj.var)    # 3  (Normal variable)
print (Test.var )

See the output below

how to create a static variable in python

How to create a boolean variable in python

Here, boolean variables are defined by True or False keyword.

An important thing to note here is True and False should be with the first letter as Uppercase. If you will write true and false it will show you error. Let’s check this scenario.

Example

a = true;
b = True;
c = True if a == b else False
print (c);

Oops, I got the error on the very first line “NameError: name ‘true’ is not defined”.

The above error is because we did the mistake to mention true .It should be True (First letter Uppercase)

Now the correct syntax is

a = True;
b = True;
c = True if a == b else False
print (c);

Output will be as below

How to create boolean variable in python

You may like following below Python Tutorials:

Conclusion

Python is the most popular open-source object-oriented programming language and it is easy to learn and syntax wise it is very simple.

You no need to mention the type while declaring the variable. This is the reason python is known as dynamically typed.

Naming convention, we need to follow while giving a name for a variable that we discussed already.

It has local scope,global scope and Enclosing scope.

You can use this in side a string.


The use of the global keyword can make the variable global even though the variable is present inside the function.

This python tutorial explains the below points:

  • What is a variable?
  • how to create a variable in python
  • Naming conventions.
  • How to declare (assign) it
  • How to reassign a variable
  • Multiple assignments.
  • How to use + operator with python variables
  • Type
  • Scope
  • How to create a global variable in python (Global Keyword )
  • Python variable in string
  • How to create python private and protected variable

Leave a Comment