In Python, a variable is marked or pointed to a value. When a variable is encountered, Python replaces it with a pointer to a value.
>>> cost=2.99>>>. 1*cost0.29900000000000004
Variable naming rules:
- The length of the variable name is unrestricted, but the character must be a letter, a number, or an underscore (_), not a space, hyphen, punctuation, quotation mark, or other character.
- The first character of a variable name cannot be a number, but must be a letter or an underscore.
- Python is case-sensitive .
- You cannot use the Python keyword as a variable name .
For an assignment statement such as X=EXPR, you can read this: let x point to the value of the expression expr . Python automatically deletes a value that does not have any variables pointing to it. In general, Python keeps track of all values and automatically removes values that no longer have variables pointing to, which is called garbage collection, so Python programmers rarely need to worry about deleting values.
An assignment statement does not copy the value pointed to, but simply marks and re-marks the existing value. Therefore, the efficiency of the assignment statement is very high, no matter how large or complex the object is pointing to.
In Python, an important feature of numbers and strings is immutable , that is, they cannot be modified in any way. In the case of a change in numbers or strings, Python is actually creating a copy of the modified version.
>>> s='apple'>>> s+'s' Apples'>>> s'apple'>>> 5=1 Syntaxerror:can't assign to literal
In Python, there is a handy technique that allows you to assign values to multiple variables at the same time : ( multiple assignments )
>>> x,y,z=1,',3.0>>> x1>>> y' both '>>> z3.0>>> x, z (' ', 3.0)
As the last statement demonstrates, you can also display multiple values on a single line by grouping them as tuples. Tuples always end with a left parenthesis (beginning with a right parenthesis).
A useful use of multiple assignments is to exchange the values of two variables:
>>> a,b=5,9>>> A, B (5, 9)>>> a,b=b,a>>> A, B ( 9, 5)
The meaning of statement a,b=b,a is to assign a value to variables A and b at the same time.
Python Variable naming conventions