In Python, the concept of variables is basically the same as the equation variables of the middle school algebra.
For example, for an equation y=x*x
, it x
is a variable. When, the result of the x=2
calculation is 4
, when x=5
, the computed result is 25
.
Just in a computer program, a variable can be not only a number, but also any data type.
In a python program, a variable is represented by a variable name, and the variable name must be a combination of uppercase and lowercase English, numeric, and underscore (_) and cannot start with a number, such as:
A = 1
a
A variable is an integer.
t_007 = ' T007 '
t_007
A variable is a string.
In Python, the equals sign =
is an assignment statement that assigns any data type to a variable, the same variable can be repeatedly assigned, and can be a variable of different types, for example:
A = 123 # A is an integer print AA = ' Imooc ' # A becomes a string print a
This type of variable itself is called Dynamic language, which corresponds to static language.
Static languages must specify the variable type when defining the variable, and if the type does not match, an error is given. For example, Java is a static language, and assignment statements are as follows (//for comments):
int a = 123; A is an integer type variable a = "Mooc"; Error: Cannot assign string to integer variable
This is why dynamic languages are more flexible than static languages.
Do not equate an equal sign of an assignment statement with a mathematical equal sign. For example, the following code:
x = 10x = x + 2
If mathematically understood x = x + 2 That is not true anyway, in the program, the assignment statement first calculates the right expression X + 2, obtains the result 12, and assigns the variable x. Since the value before X is 10, the value of X becomes 12 after the value is re-assigned.
Finally, it is important to understand the representation of variables in computer memory. When we wrote: a = ‘ABC‘
The Python interpreter did two things:
1. Create a string in memory ‘ABC‘
;
2. Create a variable named in memory a
and point to it ‘ABC‘
.
You can also assign a variable A to another variable B, which actually points the variable B to the data that the variable a points to, such as the following code:
A = ' ABC ' b = aa = ' XYZ ' Print B
The above content transferred from MU class net, only for individual study!
Variables in Python