The Problem with Forgetting
Imagine if you had to re-introduce yourself every time you spoke to your best friend. “Hello, my name is Sam.” “Hello, my name is Sam.” “Hello, my name is Sam.”
That would be exhausting! Computers are the same. If we want them to remember something—like your name, your age, or your score in a game—we need to give them a place to put it.
Enter the Variable (The Magic Box)
In Python, a variable is just a box with a name on it.
name = "Sam"
score = 100
Here is what happened:
- We created a box label “name” and put the text “Sam” inside.
- We created a box label “score” and put the number 100 inside.
Now, whenever you type name, the computer looks in the box and sees “Sam”.
print(name)
Output:
Sam
Changing the Contents
The best thing about variables is that they can change (that’s why they are called vari-ables!).
Imagine you are playing a game and you get a bonus point.
score = 100
print(score) # Computer says: 100
score = score + 1
print(score) # Computer says: 101
You took the value out of the box (100), added 1 to it (101), and put it back in the box.
Rules for Naming Boxes
You can name your variables anything you want, but there are a few rules:
- No spaces: Use
player_score, notplayer score. - Start with a letter:
score1is okay,1scoreis not. - Be clear:
xis a bad name.player_nameis a great name.
Try It Yourself
Write a program that:
- Creates a variable called
wizard_name. - Creates a variable called
magic_power. - Prints them both out.
wizard_name = "Merlin"
magic_power = 50
print(wizard_name)
print("Power Level:", magic_power)
In the next lesson, we will make the magic boxes interactive!
This post is part of the Python Basics for Kids series, based on “Python for Kids from 8 to 88”.