Before we start the tutorial, let me ask a question: Did everyone learn from the previous lesson? If you have, then you can go ahead with this one.
What is a variable?
Variables are the same as in mathematics. For example: a = 1 + 2 (Note: the '=' here is not the mathematical equals sign, but an assignment sign. The equals sign in a comparison is '=='). Here, 'a' is a variable, and the result of 1 + 2 is assigned to 'a'. Moreover, 'a' can change with changes in 1 or 2, so it can vary and is not fixed.
The function of variables
Variables are created to make it easier for programmers to input and output in coding. Python variables are relatively simple to use; they don't need to be declared in advance and can be used directly. See the code in Figure 1:
a = 1 # assign 1 to a
b = 2 # assign 2 to b
c = a + b # assign the sum of a and b to c
print(c) # output c
As shown in Figure 2:
You probably noticed that 'c' doesn't have single quotes. Why is that? Because what we want to print is not the letter 'c', but the result of a + b, so we cannot use quotes here.
Variable naming rules:
1. Composed of letters, numbers, or underscores, no spaces, and no Chinese characters!
2. Must start with a letter! Variables starting with an underscore have a special meaning!
3. Cannot have the same name as system variables, that is, identifiers! For example, 'def' is a function declaration, so you cannot use it as a variable name!
After you assign a value to a variable, you can reassign it, for example:
a = 1
a = 2
With this assignment, 'a' will be 2, not 1.
Variable deletion
When a variable is no longer needed, it's best to release the memory it occupies. A variable consumes a certain amount of storage space, and the use of a large number of unnecessary variables can slow down the system!
Deletion method:
del variable_name
Note: After using the above statement, the variable no longer exists and cannot be used again.
(Have you noticed? Isn't this a bit similar to Python on Symbian? Because this part is the same, so…)
Do you remember the previous method of printing "hello world"? Here, we can assign "hello world" to 'a' and then print it as shown above. Now, let's do a homework assignment: use the method we just learned to print "hello world".
The third file is the code used in the tutorial, change it to .py
Visa status: Not required