blog.dopana

Back

Welcome back! 🐍 Today, we are going to give our Python robot a superpower: Memory!

Right now, when we run a code like print(5 + 5), the robot calculates the answer, tells it to us, and immediately forgets it. But what if we are building a video game and need to remember the player’s score?

To do this, we use Variables!

What is a Variable? (The Box Analogy)#

Think of a variable as a cardboard box.

  1. You write a Label on the outside of the box (the variable name).
  2. You put One Thing inside the box (the value).
graph TD
    subgraph Memory ["💾 Computer Memory"]
        Label["🏷️ label: score"] --> Box["📦 Box"]
        Box --> Contents["100 (high score)"]
    end

In Python, we create a box by writing the label, an equals sign =, and the item we want to put inside:

score = 100
python

This code tells the robot: “Hey Python, make a box, write ‘score’ on the front, and put the number 100 inside.”

Changing What is Inside the Box#

A box can only hold one thing at a time. If you put something new into a box, the old item gets thrown away!

score = 100
score = 150
python
graph LR
    Step1["score = 100"] --> Box1["📦 score contains 100"]
    Step2["score = 150"] --> Box2["📦 score contains 150 (100 is deleted!)"]

If you print the score now, the robot will say 150:

print(score) # The robot prints 150
python

Different Box Shapes (Data Types)#

Our robot uses different types of boxes for different toys. Here are the three most common shapes:

1. The Word Box (String)#

Used for text. It always uses quotation marks:

hero_name = "Sonic"
python

2. The Number Box (Integer)#

Used for whole numbers without decimals:

lives = 3
python

3. The Yes/No Box (Boolean)#

Used for true or false facts. Note that True and False must start with capital letters:

is_game_over = False
python

Try It Yourself! 🎮#

Open your Python editor and try this magic trick:

toy = "Lego Brick"
print(toy)

toy = "Superball"
print(toy)
python

Can you guess what the robot will say? Run the code and see if you were right!

Next time, we will learn how to make the robot make decisions, like checking if we have enough coins to buy a magic sword. See you then!

References#