A variable is a container that can hold values. The variable type is determined by the nature of the values stored and we call them as data type.
Declaring a Variable
Declaring a variable in python is simple,
Syntax: VARIABLENAME = VALUE
>>> employeeNo = 101
As you can see that the data type (int,float,string,etc) is not mentioned instead it implicitly understands that the variable employeeNo is of type integer based on the value we had assigned to it.
Below are some of the rules that one should follow when naming a variable.
A variable name should always start with either underscore (_) or an alphabet. It cannot start with a number.
A variable name can only contain alphabets, numbers and underscores. It cannot contain special characters like %#@ etc.
You cannot use reserved keywords as variable names, for example so far we might have seen that print is a python keyword and hence you cannot use it as a variable name.
Variable names are case-sensitive. Which means the variable name salary, sALARY and SALARY are all different.
Try the below code:
>>> salary = 5000
>>> sALARY = 6000
>>> SALARY = 5000
>>> print(salary, sALARY, SALARY)
You can also assign the same value to multiple variable in a single line as shown below,
The above statement will print 13 since a, b and c all hold the same values. You can also check if a, b and c hold the same values using the below statement:
>>> a is b
>>> a is c
The above will return a Boolean value True.
What if you want to assign different values to different variables but you would like to do that also in a single line?
>>> a,b,c = (1,2,3)
The above will assign values in the order specified to the variables.
Declare Variable without Value
If you want to declare a variable without a value then assign the value None to it.
>>> temp_variable = None
The main reason for which we use a variable is to hold values and manipulate them to get the desired result that we want.
The below example concatenates the strings in variables strVariable1 and strVariable2 and places it in a resultVariable variable.
>>> strVariable1 = "Hello"
>>> resultVariable = strVariable1 + " " + strVariable2
In the same way if you want to add two numbers by getting input from the end user then use the below commands,
>>> number1 = int(input())
>>> number2 = int(input())
>>> number3= number1 + number2
When you execute the first and second line you will have to enter numbers. As you can see we have input() which will get the user input. The int keyword around the input() is used to convert or typecast the value that the user enters into integer. By default the value entered will be string so we need to convert it into integer.