To create a variable in Python, all you need to do is specify the variable name, and then assign a value to it
<variable name> = <variable_value>
Python uses = to assign values to variables. There's no need to declare a variable in advance (or to assign a data
type to it), assigning a value to a variable itself declares and initializes the variable with that value. There's no way to
declare a variable without assigning it an initial value.
Rules for variable naming:
1. Variables names must start with a letter or an underscore.
2. The remainder of your variable name may consist of letters, numbers and underscores.
3. Names are case sensitive.
Even though there's no need to specify a data type when declaring a variable in Python, while allocating the
necessary area in memory for the variable, the Python interpreter automatically picks the most suitable built-in
type for it:
When using such cascading assignment, it is important to note that all three variables a, b and c refer to the same
object in memory, an int object with the value of 1. In other words, a, b and c are three different names given to the
same int object. Assigning a different object to one of them afterwards doesn't change the others, just as expected:
You can assign multiple values to multiple variables in one line. Note that there must be the same number of
arguments on the right and left sides of the = operator:
The error in last example can be obviated by assigning remaining values to equal number of arbitrary variables.
This dummy variable can have any name, but it is conventional to use the underscore (_) for assigning unwanted
values:
Note that the number of _ and number of remaining values must be equal. Otherwise 'too many values to unpack
error' is thrown as above:
Comments :
Post a Comment