Before learning variables and assignment, we need to know what variables are!
In Python language, the equal sign [=] is used to indicate assignment. Python assignment does not directly assign a value to a variable. In Python, objects are passed by reference; When passing, no matter whether the object is newly created or already exists, the reference of the object is assigned to the variable.
For example, 3 * 4 = 12. When writing an arithmetic program, we often encounter many 3 * 4 = 12
In many There are two ways to use this program for the first time:
One method is to type 3 * 4 directly in the code
The other is to use a variable to store 3 * 4
For example:
The output result is 12
If variables are used, just enter z in the program, and you can directly call z, from From a strict perspective of code, using variables directly can make the code more beautiful. From a convenience perspective, using variables can shorten the time of writing code. Like z = x * y, you only need to call the result z, and the output result is as follows It turns out to be the same. In other words, z now points to the number 12. Therefore, z is a variable and its value is 12.
Look at the following example:
The values of a and b are 3 and 4 respectively. The equal sign ("=") in the middle is called the assignment symbol. , it is different from the equal sign in mathematics, do not confuse
Variable naming and usage rules
Variable names can only contain Letters, numbers and underscores. The variable name can start with a letter or an underscore, but it cannot start with a number, and it cannot start with Chinese
The variable name cannot contain spaces, but underscores can be used to separate the words. For example, the variable name greeting_message will work, but the variable name greeting message will raise an error
Variable names should be short and descriptive. For example, name is better than n, student_name is better than s_n
Use the lowercase letter l and the uppercase letter O with caution, because they may be mistaken for the numbers 1 and 0.
The above is the detailed content of How to assign a value to a variable in python. For more information, please follow other related articles on the PHP Chinese website!