Welcome to the exciting world of programming! In Python, we need a way to store information so we can use it later. This is where variables come in. Think of a variable as a labeled box where you can put a piece of data. You give the box a name (the variable name) and then you can put something inside it (the value).
To put a value into a variable, we use the assignment operator, which is the equals sign (=). It's super straightforward: you write the variable name, then an equals sign, and then the value you want to store. This operation is called 'assignment'.
my_variable = 10In the code above, my_variable is the name of our variable, and 10 is the value we are assigning to it. Python will create a box named my_variable and place the number 10 inside.
Variables can hold different types of data. Let's see some examples:
name = "Alice"
age = 25
height = 5.9
is_student = TrueHere, name holds a string of text, age holds an integer (a whole number), height holds a floating-point number (a number with a decimal), and is_student holds a boolean value (either True or False). Python is smart enough to figure out the type of data you're storing.
graph TD;
VariableBox["my_variable"]
Value[10]
VariableBox --> Value;
The assignment operator always works from right to left. The value on the right side of the equals sign is evaluated and then stored in the variable on the left side. You can also reassign a new value to an existing variable. The old value is discarded, and the new value takes its place.
counter = 5
print(counter) # Output: 5
counter = 10
print(counter) # Output: 10