Posted at: https://laptrinhcanban.com/en
To use a variable, you need to assign a value to the variable. The variable assignments in python can be done at the same time or after you declare variables in python. You can assign a different value to a defined variable, or you can assign a variable to another. Let’s learn how to assign variables in python after this lesson.
Assign variables in python
Assign another value to a specified variable
When declaring variables in python, we need to specify a value to assign to that variable.
However, after declaring that variable, we can also assign another value to that variable like the following example:
price = 100 |
In python variable post you know what the variable in python is not the address of the location containing the value in memory, but just the tag to address that data only. So when we assign a different value to a specified variable, we simply change the address line on the variable.
Therefore, the variable nature does not change, only the address of the value in memory to which it is assigned has changed.
Again, the values used to assign to variables can be of different data types, but variables in python are automatically recognized the data type when assigned a value.
Therefore, you can assign a variable of a different data type to the same variable as shown in the following example:
name = "Kiyoshi" |
In the above example, although the variable name
is declared with the value as a string, it can then still be assigned by the value as a number. That’s thanks to in python, variables are automatically recognized the type of value assigned to it
Assign one variable to another
We can assign a variable already declared to another, like in the following example:
num1 = 100 |
In this case, both the variable num1and num2both write to and point to the same address, which is the location of the value 100in memory.
Note, however, that if we now assign a new value to the variable num1, the value of the variable num2will remain unchanged.
num1 = 100 |
If you assign a different value num1
instead of storing the new value in the location that it num1
is referencing, num1the address of that new value will be written in memory.
At this point, the variable is num2
still referring to the original position, so the variable num1
refers to the valued position 200 and the variable num2refers to the valued position 100.
So when printing to the screen, the values of these two variables will be different:
num1 200 |
Summary
Above, Kiyoshi showed you how to assign variables in python. To better understand the lesson content, practice rewriting today’s examples.
And let’s learn more about Python in the next lessons.
URL Link
HOME › python for beginners>>variables in python