Variables are integral to the working of every python program. When programs run, everything that they need remains in the memory. The code and the data it works on also remains in the memory. This is true for python as well.
A variable is a way of giving a name to an area of memory. Different values remain in this area of memory. When we create a variable say, myVar
Python allocates an area of memory. Python recognizes it with the name myVar
.
When we assign a value to a variable, python itself decides the type of the variable. This is because python is a dynamically typed language. In python, data type of the value needs not be specified.
There is no specific command to declare a variable in Python. Assigning a value to a variable name creates a variable at the same instant.
- Naming a Variable in python
- Valid Variables in Python
- Invalid Variables in Python
- Declaring a variable in Python
- Multiple Assignment of Variables in Python
- Type( ) Function in Python
- Printing a variable in python
- NameError in Python
- Scope of Python variable
- Local Variable in Python
- Global Variable in Python
- Multi word variables in python
- Deletion of variable in python
- Tips for efficient naming of variables in python
- To sum up
Naming a Variable in python
Variable names can be short (like a, b) as well as long (first_name
, last_name
). However, naming a variable follows certain rules. They are as follows.
- A variable name starts with an alphabet or an underscore( _ ).
- The variable name cannot start with a number.
- The first alphabet can be in lowercase (a-z) as well as uppercase (A-Z).
- The variable name must not contain a special character (!, #, $, %, @, ^, &, *).
- The variable name should be different from the reserved keywords in Python. A few keywords include True, False and None.
- Variable names are case- sensitive. Example, first_name and FIRST_NAME are different variables.
Valid Variables in Python
Here are a few examples of variables which are valid in python.
a1, list1, first_name, f_n, last_name, l_n, first_11, _a, x, y, Student_name, Roll_NO
Invalid Variables in Python
Here are a few examples of variables which are invalid in python.
19name, first name, first^name, first%name, 123, True, False
Declaring a variable in Python
Python is a dynamically typed language. In python, the data type of variable need not be specified on declaration. We simply use the assignment operator to bind the value on right to the variable on left. Let us look at a few examples.
x = 100 #A number
name = "Avid Python" #A string
a = (11, 12) #A tuple
b = [11, 12] #A list
new = {"A":"1", "B":"2"} #A dictionary
Now look at the below example.
Here, 5 students numbered from s1
to s5
have scored the same marks.
s1 = 50
s2 = 50
s3 = 50
s4 = 50
s5 = 50
All the 5 variables have the same value. Assigning these scores individually to each element is not efficient in this case. A better way to do it is as follows.
Multiple Assignment of Variables in Python
We can assign the same value to multiple variables at once in Python.
s1 = s2 = s3 = s4 = s5 = 50
print(s1, s2, s3, s4, s5)
Output:
50 50 50 50 50
Here, a single value is bound to different variables. We can also bind multiple values to multiple variables in a single line. This is done below.
x, y, z = 11, 12, "Avid Python"
print(x, y, z)
x, y, z = (11, 12, 13)
print(x, y, z)
x, y, z = [10, 20, 30]
print(x, y, z)
Output:
11, 12, Avid Python
11, 12, 12
10, 20, 30
What if the number of variables is not equal to the number of values? That obviously gives us an error as below:
x, y, z = 11, 22, 33, 44
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
x, y, z = 11, 22, 33, 44
ValueError: too many values to unpack (expected 3)
Type( ) Function in Python
In python, specification of data type on declaration is not required but there is a function that we can use to find the data type of a specific variable or value.
Type( ) function returns the type of a variable or a value in python. Below are a few examples.
- Assigning integer to a variable.
x = 1
print(type(x))
Output:
<class 'int'>
2. Assigning string to a variable.
name = "Avid Python"
print(type(name))
Output:
<class 'str'>
3. Assigning a python list to a variable.
marks = [100, 96, 100]
print(type(marks))
Output:
<class 'list'>
4. Assigning a python tuple to a variable.
marks = (100, 96, 100)
print(type(marks))
Output:
<class 'tuple'>
5. Assigning a python dictionary to a variable.
y = {"1" : "A"}
print(type(y))
Output:
<class 'dict'>
Printing a variable in python
Python uses the print()
function to print the value of a variable. This is done below.
x = 10
print(x)
Output:
10
Here, only the variable is passed in the print()
function. But we can also print a variable as shown below.
x = 10
print("The Value of this variable is", 10)
Output:
The Value of this variable is 10
NameError in Python
In the above example, we first defined the variable x and then used it in the print statement. But if we try to access a variable before defining it, then we run into an error. This error is called NameError
.
In python, variables are accessed sequentially. Look at the below example.
x = 10
print(y)
y = 11
Output:
NameError: name 'y' is not defined
Here, accessing the variable ‘y
‘ before defining it gives an error.
Scope of Python variable
Scope defines an area in which we can access a variable. Every variable has 2 scopes:
- Local Scope
- Global Scope
Local Variable in Python
If the scope of a variable is only within a defined class or function in python, then the variable is called local variable. There is a set boundary out of which we can not use that variable. On accessing this variable outside the defined scope, we get a NameError
.
Look at the below example to understand this concept:
def student():
roll_no = 10
print(roll_no)
student()
print(roll_no)
Output:
10
NameError: name 'roll_no' is not defined
Here, the function student( )
has a variable roll_no
. The print statement inside this function executes and we get the output as 10. But when the last print statement executes, we get an error. This happens because in the last print statement, we are trying to access a variable which is local to the student()
function.
The variable roll_no
is defined inside the function student and so, it is local to that function only. Below is another example:
def student():
roll_no = 10
print(roll_no)
Output:
NameError: name 'roll_no' is not defined
Here, although the variable roll_no
is present, we still get an error. This happens because the scope of this variable is local to the function student( )
. On trying to access a local variable outside its scope, we get an error.
Global Variable in Python
A variable which is accessible from anywhere in a Python program is a Global Variable. Look at the below example to understand this:
roll_no = 10
def student():
print(roll_no)
student()
print(roll_no)
Output:
NameError: name 'roll_no' is not defined
In the above example, the variable roll_no
has a global scope and accessing it from both, either inside a function or from outside a function is valid. Both the print statements execute without throwing any error. This is how a global variable works.
Multi word variables in python
Usually, naming of variables is done such that the name makes sense to you when you come back to work with that code after some time. Also, while working in a team, variables should make sense to everyone in the group. But sometimes, these names might get long and multi-word.
Such multi-word long variables should follow any one of the below conventions. These are the different cases in which we write a multi-word variable.
- Camel Case : Here, each new word except the first, begins with a capital letter. Eg:
firstName
,nameOfStudent
,rollNo
- Pascal Case : Here, each new word including the first too, begins with a capital letter. Eg:
FirstName
,NameOfStudent
,RollNo
- Snake Case : Here, each word is separated by an underscore. This is the most used case. Eg:
first_name
,name_of_student
,roll_no
Deletion of variable in python
To delete a variable, we use del statement. After deletion, accessing the variable will give an error. Let us see an example.
>>> roll_no = 10
>>> print(roll_no)
10
>>> del roll_no
>>> print(roll_no)
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
print(roll_no)
NameError: name 'roll_no' is not defined
>>>
After deletion, accessing the variable is not possible.
Tips for efficient naming of variables in python
We should not use random variable names. They should have some meaning and should make sense to anyone who looks at the code. Here are a few common ways in which you can assure this while writing your own code.
- Use a mix of small case letters, numbers and underscores.
- For multi-word variables, underscore is the best way to separate different words.
- Since python has many libraries and built-in functions which use keywords and variables with a starting and ending underscore, we should not start and end a variable name with an underscore.
- However, the name of a private variable starts with an underscore.
- Use words which are applicable in the context of use and convey some meaning.
- Although there is no limit for the length of a variable, one should keep them small and precise.
To sum up
Python variables are also known as Identifiers and are used in almost all python programs. Here in this article, we talked about defining a variable, finding the variable type, printing the variable, deleting a variable, scope of a variable and naming of a variable in the most efficient way.
I hope you enjoyed reading this article. Stay tuned for more informative articles.
Happy Learning!