Tutorial: Python Variables
Introduction
Variables in any programming language are similar to the variables in mathematics. For instance, we write x = 5 in mathematics. This means that x is the name of a variable and it stores the value 5. Similar is the case in programming. We can use the variables to store the values for use in our programs to perform operations on them. Also, in computers, the values are stored in memory locations that have long hexadecimal addresses. So, it is very difficult to access any value using the address directly. Hence, we give a name of our choice to the memory address so that we can refer to it whenever we want.
The image above shows that we have to store the value 5 and, as shown in the image, the address is a complex value to remember. So, we have given the name x to this memory location. Now, when we try to access the value of variable x, we will get 5. So, now that we have a basic understanding of what variables are, let us understand the variables in Python.
Python Variables
So, if you come from any programming language except Python, like Java, C++, etc. you might have seen the declaration and use of variables like this:
//declaration of a variable x
int x;
//initialization of x
x = 5
//using x or operations on x
x = x + 10;
Please note that declaration and initialization of the variable x can be done simultaneously also. One another important thing is that initializing a variable is not necessary. In most programming languages, the variable takes a default value by itself while in some programming languages, if the initialization is not done, the variable takes a garbage value. For instance, in the case of Java, if you do not initialize an integer variable, it will take the default integer value i.e. 0.
However, the conclusion that comes from this discussion is that the variables have to be declared first before we use them. We cannot directly use them without declaring them. Also, their data types have to be mentioned while declaring them.
These types of languages in which the data type of a variable is compulsory to mention while declaring the variable and its declaration is compulsory before its use are called statically typed languages.
Python is dynamically typed i.e. the variables in Python need not be declared before we use them. Also, the types of the variables are not necessary to be mentioned while using them. This is often stated as Python being an infer language i.e. a programming language that is smart itself to get and understand the data type of the variable.
Let us now see some of the rules that are used for naming the variables in Python.
Rules for Naming Python Variables: Following are the rules for naming the Python variables:
- A Python variable can only contain the set of characters i.e. (A-Z) and (a-z) and only one special symbol i.e. underscore (_) in its name.
- The name of a Python variable has to start with a character i.e. A-Z or a-z, or an underscore (_). For instance, some of the valid variable names will be: val, Val, _val, etc.
- So, it is obvious that anything that is not stated in the above rule cannot start our variable name in Python. For instance, the variable names in Python cannot start with a number like 2x, 345val, etc. Also, we know from the first rule that the special symbols except for underscore () are not allowed in the Python variable names. Hence, they cannot start the variable names in Python. However, according to the second rule, underscore () can start the variable names.
- Python variables are case-sensitive in nature. This means that the variables x and X are not the same. Also, the variable names like var and vAr, var and vaR, var and Var, and var and VAR are not the same. This means that even if one character’s case is different, the variables are not the same.
- Like any other programming language, Python also has a bunch of keywords. These keywords are reserved for Python and these cannot be used as variable names. So, variable names should not be any of the Python keywords. For instance, def is a Python keyword, and hence def is not a valid variable name. However, because Python is case-sensitive, Def can be used as a variable name in Python.
So, let us see some programs now to understand the remaining concepts regarding the python variables.
Python Program for Creating Some Variables and Displaying them.
if __name__ == "__main__":
# An Integer variable
marks = 80
# A floating point type variable
Distance = 10989.567
# A String variable
_name = "InterviewBit"
# printing all the variables
print(marks)
print(Distance)
print(_name)
pass
Code Explanation:
So, in the code above, we have three variables and we have named them according to the rules that we have already discussed above. We have mentioned the data type in the comments just to show you that in the code, we have not mentioned the data type of variables and Python is smart enough to understand the data type of the variable automatically. We just assigned the 3 variables with some values and later printed them. There is no declaration of the variables done.
Reassigning a Python Variable
A python variable can also be reassigned to take some other value than that it was holding before. Also, the data type of the value can change too. This is shown in the code below:
if __name__ == "__main__":
a = 10
print("After first assignment the value of a is", a)
a = "InterviewBit"
print("After second assignment the value of a is", a)
pass
Output:
Code Explanation
So, as shown in the code above, the variable a was first assigned with the value 10 and on printing its value, we get 10. Later, it was assigned with the string “InterviewBit” and we got the output as “InterviewBit”.
Assigning Multiple variables with the Same Value in Python
We can assign multiple variables with the same value in Python like in any other programming language. The method to do this is shown below:
if __name__ == "__main__":
a = b = c = 10
print("a =",a,"b =",b,"c =",c)
pass
Output:
Code Explanation:
In the above program, we created 3 variables and assigned them with the same value. Then, we printed the values and got the desired output.
How to know the data type of Python Variable?
The data type of any variable can be known by using the type() function in Python. Let us see a Python program to use the type() function.
if __name__ == "__main__":
#assigning a variable with integer type value
x = 5
# assigning a variable with floating point type value
y = 5.555
# assigning a variable with string type value
str = "InterviewBit"
# printing the data types of the variables
print(type(x))
print(type(y))
print(type(str))
pass
Output:
Code explanation:
We have assigned three variables with 3 different data types. Now, we are printing their data types using the type() function.
Python Variables are actually Objects
You saw the output of the above code. Did you notice something? Yes, the output says that the variables belong to a particular class. For instance, class ‘int’, class ‘float’, or class ‘str’. This is because Python is highly object-oriented. The variables that we create are actually the objects of a particular class in Python.
x = 10
This statement creates an object of class ‘int’ with value 10 and x is in a way, a pointer to that object as shown in the image below.
So, the image shows that writing x = 10 created an object of class int and it holds the value 10 in it and x is a pointer to that object. Basically, in terms of OOPS, we can say that x = 10, created an object of class int and x is the reference pointing to the instance.
Now, let us see what happens when we write y = x in Python.
x = 10
y = x
So, we have assigned the value 10 to x and then we wrote y = x. The below image shows what happens behind the scenes in Python.
So, as you can see, y also became the reference to the same instance. However, if we assign y with some different value, a new instance will be created and y will be the reference to that instance. This is shown below.
x = 10
y = 20
So, we have now understood what Python variables actually are and how they work behind the scenes.
Follow up for you
You might have heard this before that python is quite slow as compared to C++ and Java. One of the major reasons is the concept that you saw above. Creating an object (objects are created inside the heap section of the memory) takes time and python creates objects for almost everything, on the other hand, C++ creates these primitive data types in Stack Memory and so does Java unless we want to create an object using Wrapper Classes. Hence, Python is slow as compared to these languages.
So, we have now covered almost everything regarding the Python variables. Let us move to one last topic of discussion i.e. Global and Local Variables.
- Local Variables:The variables assigned/declared inside a function are local to it. They cannot be accessed by outside functions. Hence they are called local variables. An example to understand the local variables is shown below:
if __name__ == "__main__":
def fun():
local = 10
print(local)
fun()
pass
Output:
Code Explanation:
Inside the function named fun(), we have created a variable named local. This is a local variable because it is declared within the function. We can only access this variable within the function itself. So, when we call this function fun() in the main code, the function fun() gets to the function call stack and a variable local is created for this function only and its value gets printed.
If we try to access this variable from outside this function, we will get an error as shown below:
if __name__ == "__main__":
def fun():
local = 10
print(local)
fun()
print(local)
pass
Output:
As you can see, the error says that ‘local’ is not defined as it is not within the scope of the main function.
- Global Variable:
A global variable is a variable that can be accessed and used from anywhere in the program. However, in order to make changes to a global variable inside a function, the global keyword is used. Note that the global keyword is used only when we are trying to make changes to a global variable within the function. There is no need to use this global keyword if we are just trying to access the variable. If the global keyword is not used, the variable is treated as a local variable inside that function.
if __name__ == "__main__":
g = 10
def fun():
global g
print(g)
g = "InterviewBit"
print(g)
fun()
print(g)
pass
Output:
Code Explanation:
So, in the code above, a global variable is assigned the value 10 at the top of the function and it is used inside the function fun using the global keyword. Its value is printed inside the function and we get the output 10. Then, we change its value to the string “InterviewBit” and we can see that the changes are made both inside the function as well as globally.
So, this was all about the variables in Python. We hope that you understood everything and got an in-depth understanding of Python variables and how they work behind the scenes.
Conclusion:
So, we saw that Python variables are not just variables, they are objects. We also saw a lot of concepts related to the scope of the variables, their naming, and their working. It is very important to understand how variables work in Python to go into further concepts.