Think of a variable as a box where you can store something important, like a number, a word, or a list of items. When you want to use that "something" later, you can simply call the name of the box, and Python will remember what's inside!
What are variables?
In Python, a variable:
- Has a name that identifies it.
- Holds a value that you assign to it.
For example:
name = "Alice"
age = 25
is_student = True
Here:
name
is a variable storing the word"Alice"
.age
is a variable storing the number25
.is_student
is a variable storing a True/False value.
Assigning values to variables
You assign a value to a variable using the =
symbol. This doesn't mean "equal" in math terms but rather "assign this value to this variable."
For instance:
x = 10 # This assigns the value 10 to the variable x.
y = x + 5 # y gets the value 15 because x is 10.
You can also reassign a variable to a new value:
x = 50 # Now, x holds 50 instead of 10.
Rules for naming variables
- A variable name must start with a letter or an underscore (
_
). - It can include letters, numbers, and underscores, but no spaces or special symbols.
- Names are case-sensitive:
myVar
andmyvar
are different.
Examples of valid names:
score, high_score, _temp
Examples of invalid names:
3name, my-var, user name
Why use variables?
Imagine writing a shopping list program. Instead of writing the item names repeatedly, you can store them in variables and use them throughout the program. This makes your code cleaner and more flexible.
Example:
item1 = "Apples"
item2 = "Bananas"
item3 = "Oranges"
print("Shopping list:")
print(item1, item2, item3)
Now you can quickly change the value of a variable if needed!