Variables in Python
Variable can be defined as the named location for data that we need to store and manipulate in the program. For example, suppose we need to
store
the weight of a person. In order to do that we can define a variable named weight and store the value of weight in it using the
below line of
code.
weight = 0
Once we define the variable, the program will allocate a certain area in the memory. Later on, when we need to fetch the value of data stored in it
we can directly access it by its name. Also whenever we declare a variable we need to provide its initial value. In the above example, we gave the
initial value of weight to 0.
Naming a variable:
While defining a variable name, certain point should be kept in mind.
- Variable name should contain only alphabets (a-z, A-B), numbers or underscore ("_").
- First letter of the variable name cannot be a number. For example, "variable_name_5" is a valid variable name but "5_variable_name" is a invalid one.
- Variable name is case sensitive. It means "VariableName" and "variablename" will become two different variables.
- It is not allowed to use the name of the Python's reserved keyword as variable name. For example keywords like "return","while","do","elif","else", etc cannot be use as variable names.
Value assignment:
Unlike the other languages, in Python, it is not necessary to explicitly declare the variable for reserving space in memory. The declaration is done on
its own when a value is assigned to the variable. For assigning the value assignment operator ("=") is used. Whenever we will assign a value to the variable
then the variable will gain the datatype (integer, float, char, etc) depending on the assigned values.
Ex: val_1 = 10;
val_2 = 10.5;
val_3 = "Daniel";
Here "val_1" is the variable of type integer having value 10, "val_2" is the variable of type float having value 10.5 and "val_3" is a variable of
type
string having value "Daniel".
Multi Value assignment:
Multi value assignment is a way to assign the same value to multiple variables.
Ex. val_1 = val_2 = val_3 = 50.
Here we are assigning the integer value 50 to the variables "val_1", "val_2" and "val_3"