Variables
In Python, variables serve as symbolic names for values or objects in your program.
They allow you to store and manipulate data easily.
Variable Assignment
x = 42
Here, we define a variable x and assign it the value 42.
The "=" sign is used for assignment, representing a non-mathematical equals sign.
Outputting the Value of a Variable
print('value of x:', x)
# value of x: 42
We use the print function to display the value of x.
Understanding Object Identity
xstring = 'stringx'
ystring = 'stringy'
print('id of stringx:', id(xstring))
# Output: id of stringx: 140395292848112
print('id of stringy:', id(ystring))
# Output: id of stringy: 140395290122992
ystring = xstring
print('id of string x after it has been set to the value of x:', id(ystring))
# Output: id of stringx after it has been set to the value of x: 140395292848112
Variables are references to objects.
Here, we show that variables can point to the same object.
The id() function returns the unique identifier of an object, allowing us to observe the identity of variables.
Modifying Variables
x = x + 36
# Alternative: x += 36
print(x)
# Output: 78
Variables can be modified using various operators like "+", "-", "*", "/", "**" (exponentiation), "//" (integer division), and "%" (modulo).
Here, we demonstrate incrementing the value of x.