The concept of variable is similar to as in other programming languages. A variable is a name which can be used as a reference to a value. A variable can be treated as some memory location where it can store some data or any value assigned to it. When a value is assigned to a variable it stores in some memory location.
Let’s have a look on variables in brief:
Declaration of variables in different formats
|>>> x=16 # integer variable
>>> y=13.26 #float variable
>>> z=”Flipkart” # string variable
To print the above examples use print( )
You can also check the type of the variable as shown in below.
We can also re-declare the variable even after once it is already declared. It is shown in below:
Note: After re-declaring a variable, it will print the recently assigned value.
You can also delete a variable by using ‘del’ command.
>>> del var
Traceback (most recent call last):
File “<pyshell#10>”, line 1, in <module>
NameError: name ‘var’ is not defined
We can increase the value of specific variable and it shown in below
Note: The variable type changes every time during execution. It is shown in the following example.
|>>> k=26 #int variable
>>> k=26+1.4 #addition of int and float but resultant is float
>>> k=”Sixty” #and now it is string
If you want to integrate both the text and variable, just look at the below example
>>> print(“Python is”+var)
Python is interesting
If you want to integrate a variable with the other variable then:
|>>> s=”Hello” #in case of strings
>>> i=3 #in case of integers
As we discussed earlier the variable has some memory location. So to find the location of specific variable we use identity function (id( )).
1492447408 #Memory location of variable ‘a’
>>> >>> b=14
Multiple assignment of variables
We can assign a value to the multi variables at a time.
Do’s and Don’ts of variables
|1.Must start with a letter or an underscore (‘_’).
Ex: _python or python_.
2.It must include characters from (a-z/A-Z/0-9) and ‘_’.
Ex: abc12, 5A2, pr_ogra_mmin_g.
3.Variables are case-sensitive.
Ex: Snow,snow,SNOW are considered as three different variables.
4. An identifier consists of letters and digits.
5. In case of identifiers special ‘_'(underscore) can be used.
6. Examples of valid declaration of identifiers in Python are : BeHappy,mychoice,Twoapples, The_Movie
1. Do not start with number.
2. Avoid the usage of both lowercase and uppercase of letter ‘i’ and uppercase letter ‘o’. because ‘i’ and ‘o’ look like 1 and 0.
3. A variable name cannot match with the existing reserve words/keywords.
4. An identifier cannot begin with ‘_’ and a digit.
5. Spaces and quotes are not considered to be part of an identifier.
6. Examples of invalid declaration of identifiers in Python:
a.’BeHappy’ — quotes are ignored
b. my choice — spaces are ignored
c. 2apples — we cannot start with a digit.
d. _TheMovie — we cannot start with ‘_’.